code
stringlengths
2.5k
150k
kind
stringclasses
1 value
statsmodels statsmodels.multivariate.pca.PCA.plot_scree statsmodels.multivariate.pca.PCA.plot\_scree ============================================ `PCA.plot_scree(ncomp=None, log_scale=True, cumulative=False, ax=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/multivariate/pca.html#PCA.plot_scree) Plot of the ordered eigenvalues | Parameters: | * **ncomp** (*int**,* *optional*) – Number of components ot include in the plot. If None, will included the same as the number of components computed * **log\_scale** (*boot**,* *optional*) – Flag indicating whether ot use a log scale for the y-axis * **cumulative** (*bool**,* *optional*) – Flag indicating whether to plot the eigenvalues or cumulative eigenvalues * **ax** (*Matplotlib axes instance**,* *optional*) – An axes on which to draw the graph. If omitted, new a figure is created | | Returns: | **fig** – Handle to the figure | | Return type: | figure | statsmodels statsmodels.sandbox.distributions.transformed.LogTransf_gen.isf statsmodels.sandbox.distributions.transformed.LogTransf\_gen.isf ================================================================ `LogTransf_gen.isf(q, *args, **kwds)` Inverse survival function (inverse of `sf`) at q of the given RV. | Parameters: | * **q** (*array\_like*) – upper tail probability * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **x** – Quantile corresponding to the upper tail probability q. | | Return type: | ndarray or scalar | statsmodels statsmodels.regression.recursive_ls.RecursiveLS.prepare_data statsmodels.regression.recursive\_ls.RecursiveLS.prepare\_data ============================================================== `RecursiveLS.prepare_data()` Prepare data for use in the state space representation statsmodels statsmodels.sandbox.distributions.transformed.TransfTwo_gen.stats statsmodels.sandbox.distributions.transformed.TransfTwo\_gen.stats ================================================================== `TransfTwo_gen.stats(*args, **kwds)` Some statistics of the given RV. | Parameters: | * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional* *(**continuous RVs only**)*) – scale parameter (default=1) * **moments** (*str**,* *optional*) – composed of letters [‘mvsk’] defining which moments to compute: ‘m’ = mean, ‘v’ = variance, ‘s’ = (Fisher’s) skew, ‘k’ = (Fisher’s) kurtosis. (default is ‘mv’) | | Returns: | **stats** – of requested moments. | | Return type: | sequence | statsmodels statsmodels.stats.multitest.local_fdr statsmodels.stats.multitest.local\_fdr ====================================== `statsmodels.stats.multitest.local_fdr(zscores, null_proportion=1.0, null_pdf=None, deg=7, nbins=30)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/multitest.html#local_fdr) Calculate local FDR values for a list of Z-scores. | Parameters: | * **zscores** (*array-like*) – A vector of Z-scores * **null\_proportion** (*float*) – The assumed proportion of true null hypotheses * **null\_pdf** (*function mapping reals to positive reals*) – The density of null Z-scores; if None, use standard normal * **deg** (*integer*) – The maximum exponent in the polynomial expansion of the density of non-null Z-scores * **nbins** (*integer*) – The number of bins for estimating the marginal density of Z-scores. | | Returns: | **fdr** – A vector of FDR values | | Return type: | array-like | #### References B Efron (2008). Microarrays, Empirical Bayes, and the Two-Groups Model. Statistical Science 23:1, 1-22. #### Examples Basic use (the null Z-scores are taken to be standard normal): ``` >>> from statsmodels.stats.multitest import local_fdr >>> import numpy as np >>> zscores = np.random.randn(30) >>> fdr = local_fdr(zscores) ``` Use a Gaussian null distribution estimated from the data: ``` >>> null = EmpiricalNull(zscores) >>> fdr = local_fdr(zscores, null_pdf=null.pdf) ``` statsmodels statsmodels.discrete.discrete_model.CountModel.initialize statsmodels.discrete.discrete\_model.CountModel.initialize ========================================================== `CountModel.initialize()` Initialize is called by statsmodels.model.LikelihoodModel.\_\_init\_\_ and should contain any preprocessing that needs to be done for a model. statsmodels statsmodels.iolib.foreign.StataReader.file_headers statsmodels.iolib.foreign.StataReader.file\_headers =================================================== `StataReader.file_headers()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/iolib/foreign.html#StataReader.file_headers) Returns all .dta file headers. out: dict Has keys typlist, data\_label, lbllist, varlist, nvar, filetype, ds\_format, nobs, fmtlist, vlblist, time\_stamp, srtlist, byteorder statsmodels statsmodels.tsa.vector_ar.var_model.VARResults.plotsim statsmodels.tsa.vector\_ar.var\_model.VARResults.plotsim ======================================================== `VARResults.plotsim(steps=None, offset=None, seed=None)` Plot a simulation from the VAR(p) process for the desired number of steps statsmodels statsmodels.stats.power.FTestAnovaPower.power statsmodels.stats.power.FTestAnovaPower.power ============================================= `FTestAnovaPower.power(effect_size, nobs, alpha, k_groups=2)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/power.html#FTestAnovaPower.power) Calculate the power of a F-test for one factor ANOVA. | Parameters: | * **effect\_size** (*float*) – standardized effect size, mean divided by the standard deviation. effect size has to be positive. * **nobs** (*int* *or* *float*) – sample size, number of observations. * **alpha** (*float in interval* *(**0**,**1**)*) – significance level, e.g. 0.05, is the probability of a type I error, that is wrong rejections if the Null Hypothesis is true. * **k\_groups** (*int* *or* *float*) – number of groups in the ANOVA or k-sample comparison. Default is 2. | | Returns: | **power** – Power of the test, e.g. 0.8, is one minus the probability of a type II error. Power is the probability that the test correctly rejects the Null Hypothesis if the Alternative Hypothesis is true. | | Return type: | float | statsmodels statsmodels.discrete.discrete_model.MNLogit.loglikeobs statsmodels.discrete.discrete\_model.MNLogit.loglikeobs ======================================================= `MNLogit.loglikeobs(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#MNLogit.loglikeobs) Log-likelihood of the multinomial logit model for each observation. | Parameters: | **params** (*array-like*) – The parameters of the multinomial logit model. | | Returns: | **loglike** – The log likelihood for each observation of the model evaluated at `params`. See Notes | | Return type: | array-like | #### Notes \[\ln L\_{i}=\sum\_{j=0}^{J}d\_{ij}\ln\left(\frac{\exp\left(\beta\_{j}^{\prime}x\_{i}\right)}{\sum\_{k=0}^{J}\exp\left(\beta\_{k}^{\prime}x\_{i}\right)}\right)\] for observations \(i=1,...,n\) where \(d\_{ij}=1\) if individual `i` chose alternative `j` and 0 if not. statsmodels statsmodels.stats.power.GofChisquarePower.power statsmodels.stats.power.GofChisquarePower.power =============================================== `GofChisquarePower.power(effect_size, nobs, alpha, n_bins, ddof=0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/power.html#GofChisquarePower.power) Calculate the power of a chisquare test for one sample Only two-sided alternative is implemented | Parameters: | * **effect\_size** (*float*) – standardized effect size, according to Cohen’s definition. see [`statsmodels.stats.gof.chisquare_effectsize`](statsmodels.stats.gof.chisquare_effectsize#statsmodels.stats.gof.chisquare_effectsize "statsmodels.stats.gof.chisquare_effectsize") * **nobs** (*int* *or* *float*) – sample size, number of observations. * **alpha** (*float in interval* *(**0**,**1**)*) – significance level, e.g. 0.05, is the probability of a type I error, that is wrong rejections if the Null Hypothesis is true. * **n\_bins** (*int*) – number of bins or cells in the distribution. | | Returns: | **power** – Power of the test, e.g. 0.8, is one minus the probability of a type II error. Power is the probability that the test correctly rejects the Null Hypothesis if the Alternative Hypothesis is true. | | Return type: | float | statsmodels statsmodels.stats.weightstats.CompareMeans.from_data statsmodels.stats.weightstats.CompareMeans.from\_data ===================================================== `classmethod CompareMeans.from_data(data1, data2, weights1=None, weights2=None, ddof1=0, ddof2=0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/weightstats.html#CompareMeans.from_data) construct a CompareMeans object from data | Parameters: | * **data2** (*data1**,*) – compared datasets * **weights2** (*weights1**,*) – weights for each observation of data1 and data2 respectively, with same length as zero axis of corresponding dataset. * **ddof2** (*ddof1**,*) – default ddof1=0, ddof2=0, degrees of freedom for data1, data2 respectively. | | Returns: | | | Return type: | A CompareMeans instance. | statsmodels statsmodels.discrete.discrete_model.ProbitResults.aic statsmodels.discrete.discrete\_model.ProbitResults.aic ====================================================== `ProbitResults.aic()` statsmodels statsmodels.sandbox.distributions.extras.SkewNorm2_gen.logsf statsmodels.sandbox.distributions.extras.SkewNorm2\_gen.logsf ============================================================= `SkewNorm2_gen.logsf(x, *args, **kwds)` Log of the survival function of the given RV. Returns the log of the “survival function,” defined as (1 - `cdf`), evaluated at `x`. | Parameters: | * **x** (*array\_like*) – quantiles * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **logsf** – Log of the survival function evaluated at `x`. | | Return type: | ndarray | statsmodels statsmodels.genmod.families.links.inverse_power.deriv2 statsmodels.genmod.families.links.inverse\_power.deriv2 ======================================================= `inverse_power.deriv2(p)` Second derivative of the power transform | Parameters: | **p** (*array-like*) – Mean parameters | | Returns: | **g’‘(p)** – Second derivative of the power transform of `p` | | Return type: | array | #### Notes g’‘(`p`) = `power` \* (`power` - 1) \* `p`**(`power` - 2) statsmodels statsmodels.sandbox.regression.try_ols_anova.data2groupcont statsmodels.sandbox.regression.try\_ols\_anova.data2groupcont ============================================================= `statsmodels.sandbox.regression.try_ols_anova.data2groupcont(x1, x2)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/try_ols_anova.html#data2groupcont) create dummy continuous variable | Parameters: | * **x1** (*1d array*) – label or group array * **x2** (*1d array* *(**float**)*) – continuous variable | #### Notes useful for group specific slope coefficients in regression statsmodels statsmodels.tsa.vector_ar.var_model.VARResults.resid_acov statsmodels.tsa.vector\_ar.var\_model.VARResults.resid\_acov ============================================================ `VARResults.resid_acov(nlags=1)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/var_model.html#VARResults.resid_acov) Compute centered sample autocovariance (including lag 0) | Parameters: | **nlags** (*int*) – | statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.prepare_data statsmodels.tsa.statespace.dynamic\_factor.DynamicFactor.prepare\_data ====================================================================== `DynamicFactor.prepare_data()` Prepare data for use in the state space representation statsmodels statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialResults.llr_pvalue statsmodels.discrete.count\_model.ZeroInflatedNegativeBinomialResults.llr\_pvalue ================================================================================= `ZeroInflatedNegativeBinomialResults.llr_pvalue()` statsmodels statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialResults.normalized_cov_params statsmodels.discrete.count\_model.ZeroInflatedNegativeBinomialResults.normalized\_cov\_params ============================================================================================= `ZeroInflatedNegativeBinomialResults.normalized_cov_params()` statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.llf statsmodels.sandbox.regression.gmm.IVRegressionResults.llf ========================================================== `IVRegressionResults.llf()` statsmodels statsmodels.tsa.vector_ar.var_model.VARProcess.intercept_longrun statsmodels.tsa.vector\_ar.var\_model.VARProcess.intercept\_longrun =================================================================== `VARProcess.intercept_longrun()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/var_model.html#VARProcess.intercept_longrun) Long run intercept of stable VAR process Lütkepohl eq. 2.1.23 \[\mu = (I - A\_1 - \dots - A\_p)^{-1} \alpha\] where alpha is the intercept (parameter of the constant) statsmodels statsmodels.regression.recursive_ls.RecursiveLSResults.cov_params_robust statsmodels.regression.recursive\_ls.RecursiveLSResults.cov\_params\_robust =========================================================================== `RecursiveLSResults.cov_params_robust()` (array) The QMLE variance / covariance matrix. Alias for `cov_params_robust_oim` statsmodels statsmodels.tsa.statespace.varmax.VARMAXResults.f_test statsmodels.tsa.statespace.varmax.VARMAXResults.f\_test ======================================================= `VARMAXResults.f_test(r_matrix, cov_p=None, scale=1.0, invcov=None)` Compute the F-test for a joint linear hypothesis. This is a special case of `wald_test` that always uses the F distribution. | Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) – + array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length k row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – Default is 1.0 for no scaling. * **invcov** (*array-like**,* *optional*) – A q x q array to specify an inverse covariance matrix based on a restrictions matrix. | | Returns: | **res** – The results for the test are attributes of this results instance. | | Return type: | ContrastResults instance | #### Examples ``` >>> import numpy as np >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> A = np.identity(len(results.params)) >>> A = A[1:,:] ``` This tests that each coefficient is jointly statistically significantly different from zero. ``` >>> print(results.f_test(A)) <F test: F=array([[ 330.28533923]]), p=4.984030528700946e-10, df_denom=9, df_num=6> ``` Compare this to ``` >>> results.fvalue 330.2853392346658 >>> results.f_pvalue 4.98403096572e-10 ``` ``` >>> B = np.array(([0,0,1,-1,0,0,0],[0,0,0,0,0,1,-1])) ``` This tests that the coefficient on the 2nd and 3rd regressors are equal and jointly that the coefficient on the 5th and 6th regressors are equal. ``` >>> print(results.f_test(B)) <F test: F=array([[ 9.74046187]]), p=0.005605288531708235, df_denom=9, df_num=2> ``` Alternatively, you can specify the hypothesis tests using a string ``` >>> from statsmodels.datasets import longley >>> from statsmodels.formula.api import ols >>> dta = longley.load_pandas().data >>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' >>> results = ols(formula, dta).fit() >>> hypotheses = '(GNPDEFL = GNP), (UNEMP = 2), (YEAR/1829 = 1)' >>> f_test = results.f_test(hypotheses) >>> print(f_test) <F test: F=array([[ 144.17976065]]), p=6.322026217355609e-08, df_denom=9, df_num=3> ``` See also [`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`wald_test`](statsmodels.tsa.statespace.varmax.varmaxresults.wald_test#statsmodels.tsa.statespace.varmax.VARMAXResults.wald_test "statsmodels.tsa.statespace.varmax.VARMAXResults.wald_test"), [`t_test`](statsmodels.tsa.statespace.varmax.varmaxresults.t_test#statsmodels.tsa.statespace.varmax.VARMAXResults.t_test "statsmodels.tsa.statespace.varmax.VARMAXResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") #### Notes The matrix `r_matrix` is assumed to be non-singular. More precisely, r\_matrix (pX pX.T) r\_matrix.T is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full. statsmodels statsmodels.regression.mixed_linear_model.MixedLMResults.profile_re statsmodels.regression.mixed\_linear\_model.MixedLMResults.profile\_re ====================================================================== `MixedLMResults.profile_re(re_ix, vtype, num_low=5, dist_low=1.0, num_high=5, dist_high=1.0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/mixed_linear_model.html#MixedLMResults.profile_re) Profile-likelihood inference for variance parameters. | Parameters: | * **re\_ix** (*integer*) – If vtype is `re`, this value is the index of the variance parameter for which to construct a profile likelihood. If `vtype` is ‘vc’ then `re_ix` is the name of the variance parameter to be profiled. * **vtype** (*string*) – Either ‘re’ or ‘vc’, depending on whether the profile analysis is for a random effect or a variance component. * **num\_low** (*integer*) – The number of points at which to calculate the likelihood below the MLE of the parameter of interest. * **dist\_low** (*float*) – The distance below the MLE of the parameter of interest to begin calculating points on the profile likelihood. * **num\_high** (*integer*) – The number of points at which to calculate the likelihood abov the MLE of the parameter of interest. * **dist\_high** (*float*) – The distance above the MLE of the parameter of interest to begin calculating points on the profile likelihood. | | Returns: | * *An array with two columns. The first column contains the* * *values to which the parameter of interest is constrained. The* * *second column contains the corresponding likelihood values.* | #### Notes Only variance parameters can be profiled.
programming_docs
statsmodels statsmodels.discrete.discrete_model.CountResults.t_test statsmodels.discrete.discrete\_model.CountResults.t\_test ========================================================= `CountResults.t_test(r_matrix, cov_p=None, scale=None, use_t=None)` Compute a t-test for a each linear hypothesis of the form Rb = q | Parameters: | * **r\_matrix** (*array-like**,* *str**,* *tuple*) – + array : If an array is given, a p x k 2d array or length k 1d array specifying the linear restrictions. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q). If q is given, can be either a scalar or a length p row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – An optional `scale` to use. Default is the scale specified by the model fit. * **use\_t** (*bool**,* *optional*) – If use\_t is None, then the default of the model is used. If use\_t is True, then the p-values are based on the t distribution. If use\_t is False, then the p-values are based on the normal distribution. | | Returns: | **res** – The results for the test are attributes of this results instance. The available results have the same elements as the parameter table in `summary()`. | | Return type: | ContrastResults instance | #### Examples ``` >>> import numpy as np >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> r = np.zeros_like(results.params) >>> r[5:] = [1,-1] >>> print(r) [ 0. 0. 0. 0. 0. 1. -1.] ``` r tests that the coefficients on the 5th and 6th independent variable are the same. ``` >>> T_test = results.t_test(r) >>> print(T_test) Test for Constraints ============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------ c0 -1829.2026 455.391 -4.017 0.003 -2859.368 -799.037 ============================================================================== >>> T_test.effect -1829.2025687192481 >>> T_test.sd 455.39079425193762 >>> T_test.tvalue -4.0167754636411717 >>> T_test.pvalue 0.0015163772380899498 ``` Alternatively, you can specify the hypothesis tests using a string ``` >>> from statsmodels.formula.api import ols >>> dta = sm.datasets.longley.load_pandas().data >>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' >>> results = ols(formula, dta).fit() >>> hypotheses = 'GNPDEFL = GNP, UNEMP = 2, YEAR/1829 = 1' >>> t_test = results.t_test(hypotheses) >>> print(t_test) Test for Constraints ============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------ c0 15.0977 84.937 0.178 0.863 -177.042 207.238 c1 -2.0202 0.488 -8.231 0.000 -3.125 -0.915 c2 1.0001 0.249 0.000 1.000 0.437 1.563 ============================================================================== ``` See also [`tvalues`](statsmodels.discrete.discrete_model.countresults.tvalues#statsmodels.discrete.discrete_model.CountResults.tvalues "statsmodels.discrete.discrete_model.CountResults.tvalues") individual t statistics [`f_test`](statsmodels.discrete.discrete_model.countresults.f_test#statsmodels.discrete.discrete_model.CountResults.f_test "statsmodels.discrete.discrete_model.CountResults.f_test") for F tests [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") statsmodels statsmodels.tsa.arima_model.ARMAResults.normalized_cov_params statsmodels.tsa.arima\_model.ARMAResults.normalized\_cov\_params ================================================================ `ARMAResults.normalized_cov_params()` statsmodels statsmodels.tsa.statespace.varmax.VARMAXResults.get_prediction statsmodels.tsa.statespace.varmax.VARMAXResults.get\_prediction =============================================================== `VARMAXResults.get_prediction(start=None, end=None, dynamic=False, index=None, exog=None, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/varmax.html#VARMAXResults.get_prediction) In-sample prediction and out-of-sample forecasting | Parameters: | * **start** (*int**,* *str**, or* *datetime**,* *optional*) – Zero-indexed observation number at which to start forecasting, ie., the first forecast is start. Can also be a date string to parse or a datetime type. Default is the the zeroth observation. * **end** (*int**,* *str**, or* *datetime**,* *optional*) – Zero-indexed observation number at which to end forecasting, ie., the first forecast is start. Can also be a date string to parse or a datetime type. However, if the dates index does not have a fixed frequency, end must be an integer index if you want out of sample prediction. Default is the last observation in the sample. * **exog** (*array\_like**,* *optional*) – If the model includes exogenous regressors, you must provide exactly enough out-of-sample values for the exogenous variables if end is beyond the last observation in the sample. * **dynamic** (*boolean**,* *int**,* *str**, or* *datetime**,* *optional*) – Integer offset relative to `start` at which to begin dynamic prediction. Can also be an absolute date string to parse or a datetime type (these are not interpreted as offsets). Prior to this observation, true endogenous values will be used for prediction; starting with this observation and continuing through the end of prediction, forecasted endogenous values will be used instead. * **kwargs** – Additional arguments may required for forecasting beyond the end of the sample. See `FilterResults.predict` for more details. | | Returns: | **forecast** – Array of out of sample forecasts. | | Return type: | array | statsmodels statsmodels.tsa.arima_model.ARIMAResults.predict statsmodels.tsa.arima\_model.ARIMAResults.predict ================================================= `ARIMAResults.predict(start=None, end=None, exog=None, typ='linear', dynamic=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_model.html#ARIMAResults.predict) ARIMA model in-sample and out-of-sample prediction | Parameters: | * **start** (*int**,* *str**, or* *datetime*) – Zero-indexed observation number at which to start forecasting, ie., the first forecast is start. Can also be a date string to parse or a datetime type. * **end** (*int**,* *str**, or* *datetime*) – Zero-indexed observation number at which to end forecasting, ie., the first forecast is start. Can also be a date string to parse or a datetime type. However, if the dates index does not have a fixed frequency, end must be an integer index if you want out of sample prediction. * **exog** (*array-like**,* *optional*) – If the model is an ARMAX and out-of-sample forecasting is requested, exog must be given. Note that you’ll need to pass `k_ar` additional lags for any exogenous variables. E.g., if you fit an ARMAX(2, q) model and want to predict 5 steps, you need 7 observations to do this. * **dynamic** (*bool**,* *optional*) – The `dynamic` keyword affects in-sample prediction. If dynamic is False, then the in-sample lagged values are used for prediction. If `dynamic` is True, then in-sample forecasts are used in place of lagged dependent variables. The first forecasted value is `start`. * **typ** (*str {'linear'**,* *'levels'}*) – + ‘linear’ : Linear prediction in terms of the differenced endogenous variables. + ’levels’ : Predict the levels of the original endogenous variables. | | Returns: | **predict** – The predicted values. | | Return type: | array | #### Notes It is recommended to use dates with the time-series models, as the below will probably make clear. However, if ARIMA is used without dates and/or `start` and `end` are given as indices, then these indices are in terms of the *original*, undifferenced series. Ie., given some undifferenced observations: ``` 1970Q1, 1 1970Q2, 1.5 1970Q3, 1.25 1970Q4, 2.25 1971Q1, 1.2 1971Q2, 4.1 ``` 1970Q1 is observation 0 in the original series. However, if we fit an ARIMA(p,1,q) model then we lose this first observation through differencing. Therefore, the first observation we can forecast (if using exact MLE) is index 1. In the differenced series this is index 0, but we refer to it as 1 from the original series. statsmodels statsmodels.tsa.statespace.sarimax.SARIMAX.untransform_params statsmodels.tsa.statespace.sarimax.SARIMAX.untransform\_params ============================================================== `SARIMAX.untransform_params(constrained)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/sarimax.html#SARIMAX.untransform_params) Transform constrained parameters used in likelihood evaluation to unconstrained parameters used by the optimizer Used primarily to reverse enforcement of stationarity of the autoregressive lag polynomial and invertibility of the moving average lag polynomial. | Parameters: | **constrained** (*array\_like*) – Constrained parameters used in likelihood evaluation. | | Returns: | **constrained** – Unconstrained parameters used by the optimizer. | | Return type: | array\_like | #### Notes If the lag polynomial has non-consecutive powers (so that the coefficient is zero on some element of the polynomial), then the constraint function is not onto the entire space of invertible polynomials, although it only excludes a very small portion very close to the invertibility boundary. statsmodels statsmodels.stats.power.FTestAnovaPower statsmodels.stats.power.FTestAnovaPower ======================================= `class statsmodels.stats.power.FTestAnovaPower(**kwds)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/power.html#FTestAnovaPower) Statistical Power calculations F-test for one factor balanced ANOVA #### Methods | | | | --- | --- | | [`plot_power`](statsmodels.stats.power.ftestanovapower.plot_power#statsmodels.stats.power.FTestAnovaPower.plot_power "statsmodels.stats.power.FTestAnovaPower.plot_power")([dep\_var, nobs, effect\_size, …]) | plot power with number of observations or effect size on x-axis | | [`power`](statsmodels.stats.power.ftestanovapower.power#statsmodels.stats.power.FTestAnovaPower.power "statsmodels.stats.power.FTestAnovaPower.power")(effect\_size, nobs, alpha[, k\_groups]) | Calculate the power of a F-test for one factor ANOVA. | | [`solve_power`](statsmodels.stats.power.ftestanovapower.solve_power#statsmodels.stats.power.FTestAnovaPower.solve_power "statsmodels.stats.power.FTestAnovaPower.solve_power")([effect\_size, nobs, alpha, …]) | solve for any one parameter of the power of a F-test | statsmodels statsmodels.discrete.discrete_model.DiscreteResults.llr statsmodels.discrete.discrete\_model.DiscreteResults.llr ======================================================== `DiscreteResults.llr()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#DiscreteResults.llr) statsmodels statsmodels.regression.mixed_linear_model.MixedLMResults.bse statsmodels.regression.mixed\_linear\_model.MixedLMResults.bse ============================================================== `MixedLMResults.bse()` statsmodels statsmodels.miscmodels.tmodel.TLinearModel.loglikeobs statsmodels.miscmodels.tmodel.TLinearModel.loglikeobs ===================================================== `TLinearModel.loglikeobs(params)` statsmodels statsmodels.tsa.arima_process.ar2arma statsmodels.tsa.arima\_process.ar2arma ====================================== `statsmodels.tsa.arima_process.ar2arma(ar_des, p, q, n=20, mse='ar', start=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_process.html#ar2arma) Find arma approximation to ar process This finds the ARMA(p,q) coefficients that minimize the integrated squared difference between the impulse\_response functions (MA representation) of the AR and the ARMA process. This does not check whether the MA lag polynomial of the ARMA process is invertible, neither does it check the roots of the AR lag polynomial. | Parameters: | * **ar\_des** (*array\_like*) – coefficients of original AR lag polynomial, including lag zero * **p** (*int*) – length of desired AR lag polynomials * **q** (*int*) – length of desired MA lag polynomials * **n** (*int*) – number of terms of the impulse\_response function to include in the objective function for the approximation * **mse** (*string**,* *'ar'*) – not used yet, | | Returns: | * **ar\_app, ma\_app** (*arrays*) – coefficients of the AR and MA lag polynomials of the approximation * **res** (*tuple*) – result of optimize.leastsq | #### Notes Extension is possible if we want to match autocovariance instead of impulse response function. statsmodels statsmodels.sandbox.distributions.transformed.Transf_gen.std statsmodels.sandbox.distributions.transformed.Transf\_gen.std ============================================================= `Transf_gen.std(*args, **kwds)` Standard deviation of the distribution. | Parameters: | * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **std** – standard deviation of the distribution | | Return type: | float | statsmodels statsmodels.stats.stattools.robust_kurtosis statsmodels.stats.stattools.robust\_kurtosis ============================================ `statsmodels.stats.stattools.robust_kurtosis(y, axis=0, ab=(5.0, 50.0), dg=(2.5, 25.0), excess=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/stattools.html#robust_kurtosis) Calculates the four kurtosis measures in Kim & White | Parameters: | * **y** (*array-like*) – * **axis** (*int* *or* *None**,* *optional*) – Axis along which the kurtoses are computed. If `None`, the entire array is used. * **ab** (*iterable**,* *optional*) – Contains 100\*(alpha, beta) in the kr3 measure where alpha is the tail quantile cut-off for measuring the extreme tail and beta is the central quantile cutoff for the standardization of the measure * **db** (*iterable**,* *optional*) – Contains 100\*(delta, gamma) in the kr4 measure where delta is the tail quantile for measuring extreme values and gamma is the central quantile used in the the standardization of the measure * **excess** (*bool**,* *optional*) – If true (default), computed values are excess of those for a standard normal distribution. | | Returns: | * **kr1** (*ndarray*) – The standard kurtosis estimator. * **kr2** (*ndarray*) – Kurtosis estimator based on octiles. * **kr3** (*ndarray*) – Kurtosis estimators based on exceedence expectations. * **kr4** (*ndarray*) – Kurtosis measure based on the spread between high and low quantiles. | #### Notes The robust kurtosis measures are defined \[KR\_{2}=\frac{\left(\hat{q}\_{.875}-\hat{q}\_{.625}\right) +\left(\hat{q}\_{.375}-\hat{q}\_{.125}\right)} {\hat{q}\_{.75}-\hat{q}\_{.25}}\] \[KR\_{3}=\frac{\hat{E}\left(y|y>\hat{q}\_{1-\alpha}\right) -\hat{E}\left(y|y<\hat{q}\_{\alpha}\right)} {\hat{E}\left(y|y>\hat{q}\_{1-\beta}\right) -\hat{E}\left(y|y<\hat{q}\_{\beta}\right)}\] \[KR\_{4}=\frac{\hat{q}\_{1-\delta}-\hat{q}\_{\delta}} {\hat{q}\_{1-\gamma}-\hat{q}\_{\gamma}}\] where \(\hat{q}\_{p}\) is the estimated quantile at \(p\). | | | | --- | --- | | [\*] | Tae-Hwan Kim and Halbert White, “On more robust estimation of skewness and kurtosis,” Finance Research Letters, vol. 1, pp. 56-73, March 2004. | statsmodels statsmodels.tsa.ar_model.ARResults.sigma2 statsmodels.tsa.ar\_model.ARResults.sigma2 ========================================== `ARResults.sigma2()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/ar_model.html#ARResults.sigma2) statsmodels statsmodels.genmod.families.family.Tweedie.fitted statsmodels.genmod.families.family.Tweedie.fitted ================================================= `Tweedie.fitted(lin_pred)` Fitted values based on linear predictors lin\_pred. | Parameters: | **lin\_pred** (*array*) – Values of the linear predictor of the model. \(X \cdot \beta\) in a classical linear model. | | Returns: | **mu** – The mean response variables given by the inverse of the link function. | | Return type: | array | statsmodels statsmodels.nonparametric.kernel_density.KDEMultivariateConditional.pdf statsmodels.nonparametric.kernel\_density.KDEMultivariateConditional.pdf ======================================================================== `KDEMultivariateConditional.pdf(endog_predict=None, exog_predict=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/nonparametric/kernel_density.html#KDEMultivariateConditional.pdf) Evaluate the probability density function. | Parameters: | * **endog\_predict** (*array\_like**,* *optional*) – Evaluation data for the dependent variables. If unspecified, the training data is used. * **exog\_predict** (*array\_like**,* *optional*) – Evaluation data for the independent variables. | | Returns: | **pdf** – The value of the probability density at `endog_predict` and `exog_predict`. | | Return type: | array\_like | #### Notes The formula for the conditional probability density is: \[f(y|x)=\frac{f(x,y)}{f(x)}\] with \[f(x)=\prod\_{s=1}^{q}h\_{s}^{-1}k \left(\frac{x\_{is}-x\_{js}}{h\_{s}}\right)\] where \(k\) is the appropriate kernel for each variable. statsmodels statsmodels.sandbox.regression.gmm.NonlinearIVGMM.jac_func statsmodels.sandbox.regression.gmm.NonlinearIVGMM.jac\_func =========================================================== `NonlinearIVGMM.jac_func(params, weights, args=None, centered=True, epsilon=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#NonlinearIVGMM.jac_func) statsmodels statsmodels.duration.hazard_regression.PHRegResults.t_test statsmodels.duration.hazard\_regression.PHRegResults.t\_test ============================================================ `PHRegResults.t_test(r_matrix, cov_p=None, scale=None, use_t=None)` Compute a t-test for a each linear hypothesis of the form Rb = q | Parameters: | * **r\_matrix** (*array-like**,* *str**,* *tuple*) – + array : If an array is given, a p x k 2d array or length k 1d array specifying the linear restrictions. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q). If q is given, can be either a scalar or a length p row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – An optional `scale` to use. Default is the scale specified by the model fit. * **use\_t** (*bool**,* *optional*) – If use\_t is None, then the default of the model is used. If use\_t is True, then the p-values are based on the t distribution. If use\_t is False, then the p-values are based on the normal distribution. | | Returns: | **res** – The results for the test are attributes of this results instance. The available results have the same elements as the parameter table in `summary()`. | | Return type: | ContrastResults instance | #### Examples ``` >>> import numpy as np >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> r = np.zeros_like(results.params) >>> r[5:] = [1,-1] >>> print(r) [ 0. 0. 0. 0. 0. 1. -1.] ``` r tests that the coefficients on the 5th and 6th independent variable are the same. ``` >>> T_test = results.t_test(r) >>> print(T_test) Test for Constraints ============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------ c0 -1829.2026 455.391 -4.017 0.003 -2859.368 -799.037 ============================================================================== >>> T_test.effect -1829.2025687192481 >>> T_test.sd 455.39079425193762 >>> T_test.tvalue -4.0167754636411717 >>> T_test.pvalue 0.0015163772380899498 ``` Alternatively, you can specify the hypothesis tests using a string ``` >>> from statsmodels.formula.api import ols >>> dta = sm.datasets.longley.load_pandas().data >>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' >>> results = ols(formula, dta).fit() >>> hypotheses = 'GNPDEFL = GNP, UNEMP = 2, YEAR/1829 = 1' >>> t_test = results.t_test(hypotheses) >>> print(t_test) Test for Constraints ============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------ c0 15.0977 84.937 0.178 0.863 -177.042 207.238 c1 -2.0202 0.488 -8.231 0.000 -3.125 -0.915 c2 1.0001 0.249 0.000 1.000 0.437 1.563 ============================================================================== ``` See also [`tvalues`](statsmodels.duration.hazard_regression.phregresults.tvalues#statsmodels.duration.hazard_regression.PHRegResults.tvalues "statsmodels.duration.hazard_regression.PHRegResults.tvalues") individual t statistics [`f_test`](statsmodels.duration.hazard_regression.phregresults.f_test#statsmodels.duration.hazard_regression.PHRegResults.f_test "statsmodels.duration.hazard_regression.PHRegResults.f_test") for F tests [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)")
programming_docs
statsmodels statsmodels.genmod.families.family.Family.loglike_obs statsmodels.genmod.families.family.Family.loglike\_obs ====================================================== `Family.loglike_obs(endog, mu, var_weights=1.0, scale=1.0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/family.html#Family.loglike_obs) The log-likelihood function for each observation in terms of the fitted mean response for the distribution. | Parameters: | * **endog** (*array*) – Usually the endogenous response variable. * **mu** (*array*) – Usually but not always the fitted mean response variable. * **var\_weights** (*array-like*) – 1d array of variance (analytic) weights. The default is 1. * **scale** (*float*) – The scale parameter. The default is 1. | | Returns: | **ll\_i** – The value of the loglikelihood evaluated at (endog, mu, var\_weights, scale) as defined below. | | Return type: | float | #### Notes This is defined for each family. endog and mu are not restricted to `endog` and `mu` respectively. For instance, you could call both `loglike(endog, endog)` and `loglike(endog, mu)` to get the log-likelihood ratio. statsmodels statsmodels.robust.robust_linear_model.RLMResults.pvalues statsmodels.robust.robust\_linear\_model.RLMResults.pvalues =========================================================== `RLMResults.pvalues()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/robust_linear_model.html#RLMResults.pvalues) statsmodels statsmodels.discrete.discrete_model.NegativeBinomialResults.set_null_options statsmodels.discrete.discrete\_model.NegativeBinomialResults.set\_null\_options =============================================================================== `NegativeBinomialResults.set_null_options(llnull=None, attach_results=True, **kwds)` set fit options for Null (constant-only) model This resets the cache for related attributes which is potentially fragile. This only sets the option, the null model is estimated when llnull is accessed, if llnull is not yet in cache. | Parameters: | * **llnull** (*None* *or* *float*) – If llnull is not None, then the value will be directly assigned to the cached attribute “llnull”. * **attach\_results** (*bool*) – Sets an internal flag whether the results instance of the null model should be attached. By default without calling this method, thenull model results are not attached and only the loglikelihood value llnull is stored. * **kwds** (*keyword arguments*) – `kwds` are directly used as fit keyword arguments for the null model, overriding any provided defaults. | | Returns: | | | Return type: | no returns, modifies attributes of this instance | statsmodels statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.t_test_pairwise statsmodels.discrete.count\_model.ZeroInflatedGeneralizedPoissonResults.t\_test\_pairwise ========================================================================================= `ZeroInflatedGeneralizedPoissonResults.t_test_pairwise(term_name, method='hs', alpha=0.05, factor_labels=None)` perform pairwise t\_test with multiple testing corrected p-values This uses the formula design\_info encoding contrast matrix and should work for all encodings of a main effect. | Parameters: | * **result** (*result instance*) – The results of an estimated model with a categorical main effect. * **term\_name** (*str*) – name of the term for which pairwise comparisons are computed. Term names for categorical effects are created by patsy and correspond to the main part of the exog names. * **method** (*str* *or* *list of strings*) – multiple testing p-value correction, default is ‘hs’, see stats.multipletesting * **alpha** (*float*) – significance level for multiple testing reject decision. * **factor\_labels** (*None**,* *list of str*) – Labels for the factor levels used for pairwise labels. If not provided, then the labels from the formula design\_info are used. | | Returns: | **results** – The results are stored as attributes, the main attributes are the following two. Other attributes are added for debugging purposes or as background information.* result\_frame : pandas DataFrame with t\_test results and multiple testing corrected p-values. * contrasts : matrix of constraints of the null hypothesis in the t\_test. | | Return type: | instance of a simple Results class | #### Notes Status: experimental. Currently only checked for treatment coding with and without specified reference level. Currently there are no multiple testing corrected confidence intervals available. #### Examples ``` >>> res = ols("np.log(Days+1) ~ C(Weight) + C(Duration)", data).fit() >>> pw = res.t_test_pairwise("C(Weight)") >>> pw.result_frame coef std err t P>|t| Conf. Int. Low 2-1 0.632315 0.230003 2.749157 8.028083e-03 0.171563 3-1 1.302555 0.230003 5.663201 5.331513e-07 0.841803 3-2 0.670240 0.230003 2.914044 5.119126e-03 0.209488 Conf. Int. Upp. pvalue-hs reject-hs 2-1 1.093067 0.010212 True 3-1 1.763307 0.000002 True 3-2 1.130992 0.010212 True ``` statsmodels statsmodels.tsa.statespace.mlemodel.MLEResults.test_serial_correlation statsmodels.tsa.statespace.mlemodel.MLEResults.test\_serial\_correlation ======================================================================== `MLEResults.test_serial_correlation(method, lags=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEResults.test_serial_correlation) Ljung-box test for no serial correlation of standardized residuals Null hypothesis is no serial correlation. | Parameters: | * **method** (*string {'ljungbox'**,**'boxpierece'}* *or* *None*) – The statistical test for serial correlation. If None, an attempt is made to select an appropriate test. * **lags** (*None**,* *int* *or* *array\_like*) – If lags is an integer then this is taken to be the largest lag that is included, the test result is reported for all smaller lag length. If lags is a list or array, then all lags are included up to the largest lag in the list, however only the tests for the lags in the list are reported. If lags is None, then the default maxlag is 12\*(nobs/100)^{1/4} | | Returns: | **output** – An array with `(test_statistic, pvalue)` for each endogenous variable and each lag. The array is then sized `(k_endog, 2, lags)`. If the method is called as `ljungbox = res.test_serial_correlation()`, then `ljungbox[i]` holds the results of the Ljung-Box test (as would be returned by `statsmodels.stats.diagnostic.acorr_ljungbox`) for the `i` th endogenous variable. | | Return type: | array | #### Notes If the first `d` loglikelihood values were burned (i.e. in the specified model, `loglikelihood_burn=d`), then this test is calculated ignoring the first `d` residuals. Output is nan for any endogenous variable which has missing values. See also [`statsmodels.stats.diagnostic.acorr_ljungbox`](statsmodels.stats.diagnostic.acorr_ljungbox#statsmodels.stats.diagnostic.acorr_ljungbox "statsmodels.stats.diagnostic.acorr_ljungbox") statsmodels statsmodels.stats.power.NormalIndPower.plot_power statsmodels.stats.power.NormalIndPower.plot\_power ================================================== `NormalIndPower.plot_power(dep_var='nobs', nobs=None, effect_size=None, alpha=0.05, ax=None, title=None, plt_kwds=None, **kwds)` plot power with number of observations or effect size on x-axis | Parameters: | * **dep\_var** (*string in* *[**'nobs'**,* *'effect\_size'**,* *'alpha'**]*) – This specifies which variable is used for the horizontal axis. If dep\_var=’nobs’ (default), then one curve is created for each value of `effect_size`. If dep\_var=’effect\_size’ or alpha, then one curve is created for each value of `nobs`. * **nobs** (*scalar* *or* *array\_like*) – specifies the values of the number of observations in the plot * **effect\_size** (*scalar* *or* *array\_like*) – specifies the values of the effect\_size in the plot * **alpha** (*float* *or* *array\_like*) – The significance level (type I error) used in the power calculation. Can only be more than a scalar, if `dep_var='alpha'` * **ax** (*None* *or* *axis instance*) – If ax is None, than a matplotlib figure is created. If ax is a matplotlib axis instance, then it is reused, and the plot elements are created with it. * **title** (*string*) – title for the axis. Use an empty string, `''`, to avoid a title. * **plt\_kwds** (*None* *or* [dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")) – not used yet * **kwds** (*optional keywords for power function*) – These remaining keyword arguments are used as arguments to the power function. Many power function support `alternative` as a keyword argument, two-sample test support `ratio`. | | Returns: | **fig** | | Return type: | matplotlib figure instance | #### Notes This works only for classes where the `power` method has `effect_size`, `nobs` and `alpha` as the first three arguments. If the second argument is `nobs1`, then the number of observations in the plot are those for the first sample. TODO: fix this for FTestPower and GofChisquarePower TODO: maybe add line variable, if we want more than nobs and effectsize statsmodels statsmodels.regression.linear_model.WLS.predict statsmodels.regression.linear\_model.WLS.predict ================================================ `WLS.predict(params, exog=None)` Return linear predicted values from a design matrix. | Parameters: | * **params** (*array-like*) – Parameters of a linear model * **exog** (*array-like**,* *optional.*) – Design / exogenous data. Model exog is used if None. | | Returns: | | | Return type: | An array of fitted values | #### Notes If the model has not yet been fit, params is not optional. statsmodels statsmodels.discrete.discrete_model.CountResults.summary statsmodels.discrete.discrete\_model.CountResults.summary ========================================================= `CountResults.summary(yname=None, xname=None, title=None, alpha=0.05, yname_list=None)` Summarize the Regression Results | Parameters: | * **yname** (*string**,* *optional*) – Default is `y` * **xname** (*list of strings**,* *optional*) – Default is `var_##` for ## in p the number of regressors * **title** (*string**,* *optional*) – Title for the top table. If not None, then this replaces the default title * **alpha** (*float*) – significance level for the confidence intervals | | Returns: | **smry** – this holds the summary tables and text, which can be printed or converted to various output formats. | | Return type: | Summary instance | See also [`statsmodels.iolib.summary.Summary`](statsmodels.iolib.summary.summary#statsmodels.iolib.summary.Summary "statsmodels.iolib.summary.Summary") class to hold summary results statsmodels statsmodels.stats.moment_helpers.mc2mnc statsmodels.stats.moment\_helpers.mc2mnc ======================================== `statsmodels.stats.moment_helpers.mc2mnc(mc)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/moment_helpers.html#mc2mnc) convert central to non-central moments, uses recursive formula optionally adjusts first moment to return mean statsmodels statsmodels.sandbox.distributions.transformed.TransfTwo_gen.ppf statsmodels.sandbox.distributions.transformed.TransfTwo\_gen.ppf ================================================================ `TransfTwo_gen.ppf(q, *args, **kwds)` Percent point function (inverse of `cdf`) at q of the given RV. | Parameters: | * **q** (*array\_like*) – lower tail probability * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **x** – quantile corresponding to the lower tail probability q. | | Return type: | array\_like | statsmodels statsmodels.tsa.holtwinters.Holt statsmodels.tsa.holtwinters.Holt ================================ `class statsmodels.tsa.holtwinters.Holt(endog, exponential=False, damped=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/holtwinters.html#Holt) Holt’s Exponential Smoothing wrapper(…) | Parameters: | * **endog** (*array-like*) – Time series * **expoential** (*bool**,* *optional*) – Type of trend component. * **damped** (*bool**,* *optional*) – Should the trend component be damped. | | Returns: | **results** | | Return type: | Holt class | #### Notes This is a full implementation of the holts exponential smoothing as per [1]. See also `Exponential`, `Simple` #### References [1] Hyndman, Rob J., and George Athanasopoulos. Forecasting: principles and practice. OTexts, 2014. #### Methods | | | | --- | --- | | [`fit`](statsmodels.tsa.holtwinters.holt.fit#statsmodels.tsa.holtwinters.Holt.fit "statsmodels.tsa.holtwinters.Holt.fit")([smoothing\_level, smoothing\_slope, …]) | fit Holt’s Exponential Smoothing wrapper(…) | | [`from_formula`](statsmodels.tsa.holtwinters.holt.from_formula#statsmodels.tsa.holtwinters.Holt.from_formula "statsmodels.tsa.holtwinters.Holt.from_formula")(formula, data[, subset, drop\_cols]) | Create a Model from a formula and dataframe. | | [`hessian`](statsmodels.tsa.holtwinters.holt.hessian#statsmodels.tsa.holtwinters.Holt.hessian "statsmodels.tsa.holtwinters.Holt.hessian")(params) | The Hessian matrix of the model | | [`information`](statsmodels.tsa.holtwinters.holt.information#statsmodels.tsa.holtwinters.Holt.information "statsmodels.tsa.holtwinters.Holt.information")(params) | Fisher information matrix of model | | [`initialize`](statsmodels.tsa.holtwinters.holt.initialize#statsmodels.tsa.holtwinters.Holt.initialize "statsmodels.tsa.holtwinters.Holt.initialize")() | Initialize (possibly re-initialize) a Model instance. | | [`loglike`](statsmodels.tsa.holtwinters.holt.loglike#statsmodels.tsa.holtwinters.Holt.loglike "statsmodels.tsa.holtwinters.Holt.loglike")(params) | Log-likelihood of model. | | [`predict`](statsmodels.tsa.holtwinters.holt.predict#statsmodels.tsa.holtwinters.Holt.predict "statsmodels.tsa.holtwinters.Holt.predict")(params[, start, end]) | Returns in-sample and out-of-sample prediction. | | [`score`](statsmodels.tsa.holtwinters.holt.score#statsmodels.tsa.holtwinters.Holt.score "statsmodels.tsa.holtwinters.Holt.score")(params) | Score vector of model. | #### Attributes | | | | --- | --- | | `endog_names` | Names of endogenous variables | | `exog_names` | | statsmodels statsmodels.tsa.vector_ar.vecm.VECMResults.ma_rep statsmodels.tsa.vector\_ar.vecm.VECMResults.ma\_rep =================================================== `VECMResults.ma_rep(maxn=10)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/vecm.html#VECMResults.ma_rep) statsmodels statsmodels.genmod.generalized_linear_model.GLMResults.aic statsmodels.genmod.generalized\_linear\_model.GLMResults.aic ============================================================ `GLMResults.aic()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_linear_model.html#GLMResults.aic) statsmodels statsmodels.stats.contingency_tables.StratifiedTable.oddsratio_pooled statsmodels.stats.contingency\_tables.StratifiedTable.oddsratio\_pooled ======================================================================= `StratifiedTable.oddsratio_pooled()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#StratifiedTable.oddsratio_pooled) statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.f_pvalue statsmodels.sandbox.regression.gmm.IVRegressionResults.f\_pvalue ================================================================ `IVRegressionResults.f_pvalue()` statsmodels statsmodels.discrete.discrete_model.MultinomialModel statsmodels.discrete.discrete\_model.MultinomialModel ===================================================== `class statsmodels.discrete.discrete_model.MultinomialModel(endog, exog, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#MultinomialModel) #### Methods | | | | --- | --- | | [`cdf`](statsmodels.discrete.discrete_model.multinomialmodel.cdf#statsmodels.discrete.discrete_model.MultinomialModel.cdf "statsmodels.discrete.discrete_model.MultinomialModel.cdf")(X) | The cumulative distribution function of the model. | | [`cov_params_func_l1`](statsmodels.discrete.discrete_model.multinomialmodel.cov_params_func_l1#statsmodels.discrete.discrete_model.MultinomialModel.cov_params_func_l1 "statsmodels.discrete.discrete_model.MultinomialModel.cov_params_func_l1")(likelihood\_model, xopt, …) | Computes cov\_params on a reduced parameter space corresponding to the nonzero parameters resulting from the l1 regularized fit. | | [`fit`](statsmodels.discrete.discrete_model.multinomialmodel.fit#statsmodels.discrete.discrete_model.MultinomialModel.fit "statsmodels.discrete.discrete_model.MultinomialModel.fit")([start\_params, method, maxiter, …]) | Fit the model using maximum likelihood. | | [`fit_regularized`](statsmodels.discrete.discrete_model.multinomialmodel.fit_regularized#statsmodels.discrete.discrete_model.MultinomialModel.fit_regularized "statsmodels.discrete.discrete_model.MultinomialModel.fit_regularized")([start\_params, method, …]) | Fit the model using a regularized maximum likelihood. | | [`from_formula`](statsmodels.discrete.discrete_model.multinomialmodel.from_formula#statsmodels.discrete.discrete_model.MultinomialModel.from_formula "statsmodels.discrete.discrete_model.MultinomialModel.from_formula")(formula, data[, subset, drop\_cols]) | Create a Model from a formula and dataframe. | | [`hessian`](statsmodels.discrete.discrete_model.multinomialmodel.hessian#statsmodels.discrete.discrete_model.MultinomialModel.hessian "statsmodels.discrete.discrete_model.MultinomialModel.hessian")(params) | The Hessian matrix of the model | | [`information`](statsmodels.discrete.discrete_model.multinomialmodel.information#statsmodels.discrete.discrete_model.MultinomialModel.information "statsmodels.discrete.discrete_model.MultinomialModel.information")(params) | Fisher information matrix of model | | [`initialize`](statsmodels.discrete.discrete_model.multinomialmodel.initialize#statsmodels.discrete.discrete_model.MultinomialModel.initialize "statsmodels.discrete.discrete_model.MultinomialModel.initialize")() | Preprocesses the data for MNLogit. | | [`loglike`](statsmodels.discrete.discrete_model.multinomialmodel.loglike#statsmodels.discrete.discrete_model.MultinomialModel.loglike "statsmodels.discrete.discrete_model.MultinomialModel.loglike")(params) | Log-likelihood of model. | | [`pdf`](statsmodels.discrete.discrete_model.multinomialmodel.pdf#statsmodels.discrete.discrete_model.MultinomialModel.pdf "statsmodels.discrete.discrete_model.MultinomialModel.pdf")(X) | The probability density (mass) function of the model. | | [`predict`](statsmodels.discrete.discrete_model.multinomialmodel.predict#statsmodels.discrete.discrete_model.MultinomialModel.predict "statsmodels.discrete.discrete_model.MultinomialModel.predict")(params[, exog, linear]) | Predict response variable of a model given exogenous variables. | | [`score`](statsmodels.discrete.discrete_model.multinomialmodel.score#statsmodels.discrete.discrete_model.MultinomialModel.score "statsmodels.discrete.discrete_model.MultinomialModel.score")(params) | Score vector of model. | #### Attributes | | | | --- | --- | | `endog_names` | Names of endogenous variables | | `exog_names` | Names of exogenous variables | statsmodels statsmodels.regression.quantile_regression.QuantRegResults.mse_resid statsmodels.regression.quantile\_regression.QuantRegResults.mse\_resid ====================================================================== `QuantRegResults.mse_resid()`
programming_docs
statsmodels statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth statsmodels.tsa.statespace.kalman\_smoother.KalmanSmoother.smooth ================================================================= `KalmanSmoother.smooth(smoother_output=None, smooth_method=None, results=None, run_filter=True, prefix=None, complex_step=False, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/kalman_smoother.html#KalmanSmoother.smooth) Apply the Kalman smoother to the statespace model. | Parameters: | * **smoother\_output** (*int**,* *optional*) – Determines which Kalman smoother output calculate. Default is all (including state, disturbances, and all covariances). * **results** (*class* *or* *object**,* *optional*) – If a class, then that class is instantiated and returned with the result of both filtering and smoothing. If an object, then that object is updated with the smoothing data. If None, then a SmootherResults object is returned with both filtering and smoothing results. * **run\_filter** (*bool**,* *optional*) – Whether or not to run the Kalman filter prior to smoothing. Default is True. * **prefix** (*string*) – The prefix of the datatype. Usually only used internally. | | Returns: | | | Return type: | SmootherResults object | statsmodels statsmodels.discrete.discrete_model.NegativeBinomialResults.tvalues statsmodels.discrete.discrete\_model.NegativeBinomialResults.tvalues ==================================================================== `NegativeBinomialResults.tvalues()` Return the t-statistic for a given parameter estimate. statsmodels statsmodels.tsa.statespace.structural.UnobservedComponentsResults.cov_params_opg statsmodels.tsa.statespace.structural.UnobservedComponentsResults.cov\_params\_opg ================================================================================== `UnobservedComponentsResults.cov_params_opg()` (array) The variance / covariance matrix. Computed using the outer product of gradients method. statsmodels statsmodels.genmod.generalized_linear_model.GLMResults.null statsmodels.genmod.generalized\_linear\_model.GLMResults.null ============================================================= `GLMResults.null()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_linear_model.html#GLMResults.null) statsmodels statsmodels.discrete.discrete_model.GeneralizedPoissonResults.resid statsmodels.discrete.discrete\_model.GeneralizedPoissonResults.resid ==================================================================== `GeneralizedPoissonResults.resid()` Residuals #### Notes The residuals for Count models are defined as \[y - p\] where \(p = \exp(X\beta)\). Any exposure and offset variables are also handled. statsmodels statsmodels.discrete.count_model.GenericZeroInflated.from_formula statsmodels.discrete.count\_model.GenericZeroInflated.from\_formula =================================================================== `classmethod GenericZeroInflated.from_formula(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** (*extra arguments*) – These are passed to the model * **kwargs** (*extra keyword arguments*) – These are passed to the model with one exception. The `eval_env` keyword is passed to patsy. It can be either a [`patsy.EvalEnvironment`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.EvalEnvironment "(in patsy v0.5.0+dev)") 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** | | Return type: | 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 statsmodels.tsa.arima_model.ARMA.information statsmodels.tsa.arima\_model.ARMA.information ============================================= `ARMA.information(params)` Fisher information matrix of model Returns -Hessian of loglike evaluated at params. statsmodels statsmodels.tsa.statespace.structural.UnobservedComponents.set_smoother_output statsmodels.tsa.statespace.structural.UnobservedComponents.set\_smoother\_output ================================================================================ `UnobservedComponents.set_smoother_output(smoother_output=None, **kwargs)` Set the smoother output The smoother can produce several types of results. The smoother output variable controls which are calculated and returned. | Parameters: | * **smoother\_output** (*integer**,* *optional*) – Bitmask value to set the smoother output to. See notes for details. * **\*\*kwargs** – Keyword arguments may be used to influence the smoother output by setting individual boolean flags. | #### Notes This method is rarely used. See the corresponding function in the `KalmanSmoother` class for details. statsmodels statsmodels.discrete.discrete_model.NegativeBinomial.cdf statsmodels.discrete.discrete\_model.NegativeBinomial.cdf ========================================================= `NegativeBinomial.cdf(X)` The cumulative distribution function of the model. statsmodels statsmodels.sandbox.tsa.fftarma.ArmaFft.pad statsmodels.sandbox.tsa.fftarma.ArmaFft.pad =========================================== `ArmaFft.pad(maxlag)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/tsa/fftarma.html#ArmaFft.pad) construct AR and MA polynomials that are zero-padded to a common length | Parameters: | **maxlag** (*int*) – new length of lag-polynomials | | Returns: | * **ar** (*ndarray*) – extended AR polynomial coefficients * **ma** (*ndarray*) – extended AR polynomial coefficients | statsmodels statsmodels.stats.contingency_tables.SquareTable.summary statsmodels.stats.contingency\_tables.SquareTable.summary ========================================================= `SquareTable.summary(alpha=0.05, float_format='%.3f')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#SquareTable.summary) Produce a summary of the analysis. | Parameters: | * **alpha** (*float*) – `1 - alpha` is the nominal coverage probability of the interval. * **float\_format** (*string*) – Used to format numeric values in the table. * **method** (*string*) – The method for producing the confidence interval. Currently must be ‘normal’ which uses the normal approximation. | statsmodels statsmodels.regression.quantile_regression.QuantRegResults.f_pvalue statsmodels.regression.quantile\_regression.QuantRegResults.f\_pvalue ===================================================================== `QuantRegResults.f_pvalue()` statsmodels statsmodels.tools.eval_measures.aicc statsmodels.tools.eval\_measures.aicc ===================================== `statsmodels.tools.eval_measures.aicc(llf, nobs, df_modelwc)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tools/eval_measures.html#aicc) Akaike information criterion (AIC) with small sample correction | Parameters: | * **llf** (*float*) – value of the loglikelihood * **nobs** (*int*) – number of observations * **df\_modelwc** (*int*) – number of parameters including constant | | Returns: | **aicc** – information criterion | | Return type: | float | #### References <http://en.wikipedia.org/wiki/Akaike_information_criterion#AICc> statsmodels statsmodels.discrete.discrete_model.BinaryModel.pdf statsmodels.discrete.discrete\_model.BinaryModel.pdf ==================================================== `BinaryModel.pdf(X)` The probability density (mass) function of the model. statsmodels statsmodels.genmod.families.links.CDFLink.inverse_deriv statsmodels.genmod.families.links.CDFLink.inverse\_deriv ======================================================== `CDFLink.inverse_deriv(z)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/links.html#CDFLink.inverse_deriv) Derivative of the inverse of the CDF transformation link function | Parameters: | **z** (*array*) – The inverse of the link function at `p` | | Returns: | **g^(-1)’(z)** – The value of the derivative of the inverse of the logit function | | Return type: | array | statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.transform_jacobian statsmodels.tsa.statespace.dynamic\_factor.DynamicFactor.transform\_jacobian ============================================================================ `DynamicFactor.transform_jacobian(unconstrained, approx_centered=False)` Jacobian matrix for the parameter transformation function | Parameters: | **unconstrained** (*array\_like*) – Array of unconstrained parameters used by the optimizer. | | Returns: | **jacobian** – Jacobian matrix of the transformation, evaluated at `unconstrained` | | Return type: | array | #### Notes This is a numerical approximation using finite differences. Note that in general complex step methods cannot be used because it is not guaranteed that the `transform_params` method is a real function (e.g. if Cholesky decomposition is used). See also [`transform_params`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactor.transform_params#statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.transform_params "statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.transform_params") statsmodels statsmodels.sandbox.tsa.fftarma.ArmaFft statsmodels.sandbox.tsa.fftarma.ArmaFft ======================================= `class statsmodels.sandbox.tsa.fftarma.ArmaFft(ar, ma, n)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/tsa/fftarma.html#ArmaFft) fft tools for arma processes This class contains several methods that are providing the same or similar returns to try out and test different implementations. #### Notes TODO: check whether we don’t want to fix maxlags, and create new instance if maxlag changes. usage for different lengths of timeseries ? or fix frequency and length for fft check default frequencies w, terminology norw n\_or\_w some ffts are currently done without padding with zeros returns for spectral density methods needs checking, is it always the power spectrum hw\*hw.conj() normalization of the power spectrum, spectral density: not checked yet, for example no variance of underlying process is used #### Methods | | | | --- | --- | | [`acf`](statsmodels.sandbox.tsa.fftarma.armafft.acf#statsmodels.sandbox.tsa.fftarma.ArmaFft.acf "statsmodels.sandbox.tsa.fftarma.ArmaFft.acf")([lags]) | Theoretical autocorrelation function of an ARMA process | | [`acf2spdfreq`](statsmodels.sandbox.tsa.fftarma.armafft.acf2spdfreq#statsmodels.sandbox.tsa.fftarma.ArmaFft.acf2spdfreq "statsmodels.sandbox.tsa.fftarma.ArmaFft.acf2spdfreq")(acovf[, nfreq, w]) | not really a method just for comparison, not efficient for large n or long acf | | [`acovf`](statsmodels.sandbox.tsa.fftarma.armafft.acovf#statsmodels.sandbox.tsa.fftarma.ArmaFft.acovf "statsmodels.sandbox.tsa.fftarma.ArmaFft.acovf")([nobs]) | Theoretical autocovariance function of ARMA process | | [`arma2ar`](statsmodels.sandbox.tsa.fftarma.armafft.arma2ar#statsmodels.sandbox.tsa.fftarma.ArmaFft.arma2ar "statsmodels.sandbox.tsa.fftarma.ArmaFft.arma2ar")([lags]) | | | [`arma2ma`](statsmodels.sandbox.tsa.fftarma.armafft.arma2ma#statsmodels.sandbox.tsa.fftarma.ArmaFft.arma2ma "statsmodels.sandbox.tsa.fftarma.ArmaFft.arma2ma")([lags]) | | | [`fftar`](statsmodels.sandbox.tsa.fftarma.armafft.fftar#statsmodels.sandbox.tsa.fftarma.ArmaFft.fftar "statsmodels.sandbox.tsa.fftarma.ArmaFft.fftar")([n]) | Fourier transform of AR polynomial, zero-padded at end to n | | [`fftarma`](statsmodels.sandbox.tsa.fftarma.armafft.fftarma#statsmodels.sandbox.tsa.fftarma.ArmaFft.fftarma "statsmodels.sandbox.tsa.fftarma.ArmaFft.fftarma")([n]) | Fourier transform of ARMA polynomial, zero-padded at end to n | | [`fftma`](statsmodels.sandbox.tsa.fftarma.armafft.fftma#statsmodels.sandbox.tsa.fftarma.ArmaFft.fftma "statsmodels.sandbox.tsa.fftarma.ArmaFft.fftma")(n) | Fourier transform of MA polynomial, zero-padded at end to n | | [`filter`](statsmodels.sandbox.tsa.fftarma.armafft.filter#statsmodels.sandbox.tsa.fftarma.ArmaFft.filter "statsmodels.sandbox.tsa.fftarma.ArmaFft.filter")(x) | filter a timeseries with the ARMA filter | | [`filter2`](statsmodels.sandbox.tsa.fftarma.armafft.filter2#statsmodels.sandbox.tsa.fftarma.ArmaFft.filter2 "statsmodels.sandbox.tsa.fftarma.ArmaFft.filter2")(x[, pad]) | filter a time series using fftconvolve3 with ARMA filter | | [`from_coeffs`](statsmodels.sandbox.tsa.fftarma.armafft.from_coeffs#statsmodels.sandbox.tsa.fftarma.ArmaFft.from_coeffs "statsmodels.sandbox.tsa.fftarma.ArmaFft.from_coeffs")([arcoefs, macoefs, nobs]) | Convenience function to create ArmaProcess from ARMA representation | | [`from_estimation`](statsmodels.sandbox.tsa.fftarma.armafft.from_estimation#statsmodels.sandbox.tsa.fftarma.ArmaFft.from_estimation "statsmodels.sandbox.tsa.fftarma.ArmaFft.from_estimation")(model\_results[, nobs]) | Convenience function to create an ArmaProcess from the results of an ARMA estimation | | [`generate_sample`](statsmodels.sandbox.tsa.fftarma.armafft.generate_sample#statsmodels.sandbox.tsa.fftarma.ArmaFft.generate_sample "statsmodels.sandbox.tsa.fftarma.ArmaFft.generate_sample")([nsample, scale, distrvs, …]) | Simulate an ARMA | | [`impulse_response`](statsmodels.sandbox.tsa.fftarma.armafft.impulse_response#statsmodels.sandbox.tsa.fftarma.ArmaFft.impulse_response "statsmodels.sandbox.tsa.fftarma.ArmaFft.impulse_response")([leads]) | Get the impulse response function (MA representation) for ARMA process | | [`invertroots`](statsmodels.sandbox.tsa.fftarma.armafft.invertroots#statsmodels.sandbox.tsa.fftarma.ArmaFft.invertroots "statsmodels.sandbox.tsa.fftarma.ArmaFft.invertroots")([retnew]) | Make MA polynomial invertible by inverting roots inside unit circle | | [`invpowerspd`](statsmodels.sandbox.tsa.fftarma.armafft.invpowerspd#statsmodels.sandbox.tsa.fftarma.ArmaFft.invpowerspd "statsmodels.sandbox.tsa.fftarma.ArmaFft.invpowerspd")(n) | autocovariance from spectral density | | [`pacf`](statsmodels.sandbox.tsa.fftarma.armafft.pacf#statsmodels.sandbox.tsa.fftarma.ArmaFft.pacf "statsmodels.sandbox.tsa.fftarma.ArmaFft.pacf")([lags]) | Partial autocorrelation function of an ARMA process | | [`pad`](statsmodels.sandbox.tsa.fftarma.armafft.pad#statsmodels.sandbox.tsa.fftarma.ArmaFft.pad "statsmodels.sandbox.tsa.fftarma.ArmaFft.pad")(maxlag) | construct AR and MA polynomials that are zero-padded to a common length | | [`padarr`](statsmodels.sandbox.tsa.fftarma.armafft.padarr#statsmodels.sandbox.tsa.fftarma.ArmaFft.padarr "statsmodels.sandbox.tsa.fftarma.ArmaFft.padarr")(arr, maxlag[, atend]) | pad 1d array with zeros at end to have length maxlag function that is a method, no self used | | [`periodogram`](statsmodels.sandbox.tsa.fftarma.armafft.periodogram#statsmodels.sandbox.tsa.fftarma.ArmaFft.periodogram "statsmodels.sandbox.tsa.fftarma.ArmaFft.periodogram")([nobs]) | Periodogram for ARMA process given by lag-polynomials ar and ma | | [`plot4`](statsmodels.sandbox.tsa.fftarma.armafft.plot4#statsmodels.sandbox.tsa.fftarma.ArmaFft.plot4 "statsmodels.sandbox.tsa.fftarma.ArmaFft.plot4")([fig, nobs, nacf, nfreq]) | | | [`spd`](statsmodels.sandbox.tsa.fftarma.armafft.spd#statsmodels.sandbox.tsa.fftarma.ArmaFft.spd "statsmodels.sandbox.tsa.fftarma.ArmaFft.spd")(npos) | raw spectral density, returns Fourier transform | | [`spddirect`](statsmodels.sandbox.tsa.fftarma.armafft.spddirect#statsmodels.sandbox.tsa.fftarma.ArmaFft.spddirect "statsmodels.sandbox.tsa.fftarma.ArmaFft.spddirect")(n) | power spectral density using padding to length n done by fft | | [`spdmapoly`](statsmodels.sandbox.tsa.fftarma.armafft.spdmapoly#statsmodels.sandbox.tsa.fftarma.ArmaFft.spdmapoly "statsmodels.sandbox.tsa.fftarma.ArmaFft.spdmapoly")(w[, twosided]) | ma only, need division for ar, use LagPolynomial | | [`spdpoly`](statsmodels.sandbox.tsa.fftarma.armafft.spdpoly#statsmodels.sandbox.tsa.fftarma.ArmaFft.spdpoly "statsmodels.sandbox.tsa.fftarma.ArmaFft.spdpoly")(w[, nma]) | spectral density from MA polynomial representation for ARMA process | | [`spdroots`](statsmodels.sandbox.tsa.fftarma.armafft.spdroots#statsmodels.sandbox.tsa.fftarma.ArmaFft.spdroots "statsmodels.sandbox.tsa.fftarma.ArmaFft.spdroots")(w) | spectral density for frequency using polynomial roots | | [`spdshift`](statsmodels.sandbox.tsa.fftarma.armafft.spdshift#statsmodels.sandbox.tsa.fftarma.ArmaFft.spdshift "statsmodels.sandbox.tsa.fftarma.ArmaFft.spdshift")(n) | power spectral density using fftshift | #### Attributes | | | | --- | --- | | `arroots` | Roots of autoregressive lag-polynomial | | `isinvertible` | Arma process is invertible if MA roots are outside unit circle | | `isstationary` | Arma process is stationary if AR roots are outside unit circle | | `maroots` | Roots of moving average lag-polynomial | statsmodels statsmodels.regression.linear_model.GLSAR.hessian_factor statsmodels.regression.linear\_model.GLSAR.hessian\_factor ========================================================== `GLSAR.hessian_factor(params, scale=None, observed=True)` Weights for calculating Hessian | Parameters: | * **params** (*ndarray*) – parameter at which Hessian is evaluated * **scale** (*None* *or* *float*) – If scale is None, then the default scale will be calculated. Default scale is defined by `self.scaletype` and set in fit. If scale is not None, then it is used as a fixed scale. * **observed** (*bool*) – If True, then the observed Hessian is returned. If false then the expected information matrix is returned. | | Returns: | **hessian\_factor** – A 1d weight vector used in the calculation of the Hessian. The hessian is obtained by `(exog.T * hessian_factor).dot(exog)` | | Return type: | ndarray, 1d | statsmodels statsmodels.tsa.vector_ar.vecm.coint_johansen statsmodels.tsa.vector\_ar.vecm.coint\_johansen =============================================== `statsmodels.tsa.vector_ar.vecm.coint_johansen(endog, det_order, k_ar_diff)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/vecm.html#coint_johansen) Perform the Johansen cointegration test for determining the cointegration rank of a VECM. | Parameters: | * **endog** (*array-like* *(**nobs\_tot x neqs**)*) – The data with presample. * **det\_order** (*int*) – + -1 - no deterministic terms + 0 - constant term + 1 - linear trend * **k\_ar\_diff** (*int**,* *nonnegative*) – Number of lagged differences in the model. | | Returns: | **result** – An object containing the results which can be accessed using dot-notation. The object’s attributes are* eig: (neqs) Eigenvalues. * evec: (neqs x neqs) Eigenvectors. * lr1: (neqs) Trace statistic. * lr2: (neqs) Maximum eigenvalue statistic. * cvt: (neqs x 3) Critical values (90%, 95%, 99%) for trace statistic. * cvm: (neqs x 3) Critical values (90%, 95%, 99%) for maximum eigenvalue statistic. * method: str “johansen” * r0t: (nobs x neqs) Residuals for \(\Delta Y\). See p. 292 in [[1]](#id3). * rkt: (nobs x neqs) Residuals for \(Y\_{-1}\). See p. 292 in [[1]](#id3). * ind: (neqs) Order of eigenvalues. | | Return type: | Holder | #### Notes The implementation might change to make more use of the existing VECM framework. #### References | | | | --- | --- | | [1] | *([1](#id1), [2](#id2))* Lütkepohl, H. 2005. *New Introduction to Multiple Time Series Analysis*. Springer. |
programming_docs
statsmodels statsmodels.genmod.families.links.NegativeBinomial.inverse_deriv statsmodels.genmod.families.links.NegativeBinomial.inverse\_deriv ================================================================= `NegativeBinomial.inverse_deriv(z)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/links.html#NegativeBinomial.inverse_deriv) Derivative of the inverse of the negative binomial transform | Parameters: | **z** (*array-like*) – Usually the linear predictor for a GLM or GEE model | | Returns: | **g^(-1)’(z)** – The value of the derivative of the inverse of the negative binomial link | | Return type: | array | statsmodels statsmodels.genmod.generalized_linear_model.PredictionResults.summary_frame statsmodels.genmod.generalized\_linear\_model.PredictionResults.summary\_frame ============================================================================== `PredictionResults.summary_frame(what='all', alpha=0.05)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/_prediction.html#PredictionResults.summary_frame) statsmodels statsmodels.tsa.holtwinters.SimpleExpSmoothing.information statsmodels.tsa.holtwinters.SimpleExpSmoothing.information ========================================================== `SimpleExpSmoothing.information(params)` Fisher information matrix of model Returns -Hessian of loglike evaluated at params. statsmodels statsmodels.sandbox.distributions.transformed.ExpTransf_gen.logpdf statsmodels.sandbox.distributions.transformed.ExpTransf\_gen.logpdf =================================================================== `ExpTransf_gen.logpdf(x, *args, **kwds)` Log of the probability density function at x of the given RV. This uses a more numerically accurate calculation if available. | Parameters: | * **x** (*array\_like*) – quantiles * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **logpdf** – Log of the probability density function evaluated at x | | Return type: | array\_like | statsmodels statsmodels.genmod.generalized_estimating_equations.GEEResults.plot_isotropic_dependence statsmodels.genmod.generalized\_estimating\_equations.GEEResults.plot\_isotropic\_dependence ============================================================================================ `GEEResults.plot_isotropic_dependence(ax=None, xpoints=10, min_n=50)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_estimating_equations.html#GEEResults.plot_isotropic_dependence) Create a plot of the pairwise products of within-group residuals against the corresponding time differences. This plot can be used to assess the possible form of an isotropic covariance structure. | Parameters: | * **ax** (*Matplotlib axes instance*) – An axes on which to draw the graph. If None, new figure and axes objects are created * **xpoints** (*scalar* *or* *array-like*) – If scalar, the number of points equally spaced points on the time difference axis used to define bins for calculating local means. If an array, the specific points that define the bins. * **min\_n** (*integer*) – The minimum sample size in a bin for the mean residual product to be included on the plot. | statsmodels statsmodels.tsa.statespace.kalman_filter.KalmanFilter.initialize_known statsmodels.tsa.statespace.kalman\_filter.KalmanFilter.initialize\_known ======================================================================== `KalmanFilter.initialize_known(initial_state, initial_state_cov)` Initialize the statespace model with known distribution for initial state. These values are assumed to be known with certainty or else filled with parameters during, for example, maximum likelihood estimation. | Parameters: | * **initial\_state** (*array\_like*) – Known mean of the initial state vector. * **initial\_state\_cov** (*array\_like*) – Known covariance matrix of the initial state vector. | statsmodels statsmodels.tsa.statespace.structural.UnobservedComponentsResults.load statsmodels.tsa.statespace.structural.UnobservedComponentsResults.load ====================================================================== `classmethod UnobservedComponentsResults.load(fname)` load a pickle, (class method) | Parameters: | **fname** (*string* *or* *filehandle*) – fname can be a string to a file path or filename, or a filehandle. | | Returns: | | | Return type: | unpickled instance | statsmodels statsmodels.graphics.gofplots.qqplot_2samples statsmodels.graphics.gofplots.qqplot\_2samples ============================================== `statsmodels.graphics.gofplots.qqplot_2samples(data1, data2, xlabel=None, ylabel=None, line=None, ax=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/graphics/gofplots.html#qqplot_2samples) Q-Q Plot of two samples’ quantiles. Can take either two `ProbPlot` instances or two array-like objects. In the case of the latter, both inputs will be converted to `ProbPlot` instances using only the default values - so use `ProbPlot` instances if finer-grained control of the quantile computations is required. | Parameters: | * **data2** (*data1**,*) – * **ylabel** (*xlabel**,*) – User-provided labels for the x-axis and y-axis. If None (default), other values are used. * **line** (*str {'45'**,* *'s'**,* *'r'**,* *q'}* *or* *None*) – Options for the reference line to which the data is compared: + ‘45’ - 45-degree line + ’s‘ - standardized line, the expected order statistics are scaled by the standard deviation of the given sample and have the mean added to them + ’r’ - A regression line is fit + ’q’ - A line is fit through the quartiles. + None - by default no reference line is added to the plot. * **ax** (*Matplotlib AxesSubplot instance**,* *optional*) – If given, this subplot is used to plot in instead of a new figure being created. | | Returns: | **fig** – If `ax` is None, the created figure. Otherwise the figure to which `ax` is connected. | | Return type: | Matplotlib figure instance | See also `scipy.stats.probplot` #### Examples ``` >>> x = np.random.normal(loc=8.5, scale=2.5, size=37) >>> y = np.random.normal(loc=8.0, scale=3.0, size=37) >>> pp_x = sm.ProbPlot(x) >>> pp_y = sm.ProbPlot(y) >>> qqplot_2samples(pp_x, pp_y) ``` #### Notes 1. Depends on matplotlib. 2. If `data1` and `data2` are not `ProbPlot` instances, instances will be created using the default parameters. Therefore, it is recommended to use `ProbPlot` instance if fine-grained control is needed in the computation of the quantiles. statsmodels statsmodels.robust.norms.TukeyBiweight.psi_deriv statsmodels.robust.norms.TukeyBiweight.psi\_deriv ================================================= `TukeyBiweight.psi_deriv(z)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/norms.html#TukeyBiweight.psi_deriv) The derivative of Tukey’s biweight psi function #### Notes Used to estimate the robust covariance matrix. statsmodels statsmodels.tsa.statespace.sarimax.SARIMAX.initialize_statespace statsmodels.tsa.statespace.sarimax.SARIMAX.initialize\_statespace ================================================================= `SARIMAX.initialize_statespace(**kwargs)` Initialize the state space representation | Parameters: | **\*\*kwargs** – Additional keyword arguments to pass to the state space class constructor. | statsmodels statsmodels.sandbox.regression.gmm.IVGMM.gmmobjective_cu statsmodels.sandbox.regression.gmm.IVGMM.gmmobjective\_cu ========================================================= `IVGMM.gmmobjective_cu(params, weights_method='cov', wargs=())` objective function for continuously updating GMM minimization | Parameters: | **params** (*array*) – parameter values at which objective is evaluated | | Returns: | **jval** – value of objective function | | Return type: | float | statsmodels statsmodels.tsa.statespace.kalman_filter.KalmanFilter.set_filter_method statsmodels.tsa.statespace.kalman\_filter.KalmanFilter.set\_filter\_method ========================================================================== `KalmanFilter.set_filter_method(filter_method=None, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/kalman_filter.html#KalmanFilter.set_filter_method) Set the filtering method The filtering method controls aspects of which Kalman filtering approach will be used. | Parameters: | * **filter\_method** (*integer**,* *optional*) – Bitmask value to set the filter method to. See notes for details. * **\*\*kwargs** – Keyword arguments may be used to influence the filter method by setting individual boolean flags. See notes for details. | #### Notes The filtering method is defined by a collection of boolean flags, and is internally stored as a bitmask. The methods available are: FILTER\_CONVENTIONAL = 0x01 Conventional Kalman filter. FILTER\_UNIVARIATE = 0x10 Univariate approach to Kalman filtering. Overrides conventional method if both are specified. FILTER\_COLLAPSED = 0x20 Collapsed approach to Kalman filtering. Will be used *in addition* to conventional or univariate filtering. Note that only the first method is available if using a Scipy version older than 0.16. If the bitmask is set directly via the `filter_method` argument, then the full method must be provided. If keyword arguments are used to set individual boolean flags, then the lowercase of the method must be used as an argument name, and the value is the desired value of the boolean flag (True or False). Note that the filter method may also be specified by directly modifying the class attributes which are defined similarly to the keyword arguments. The default filtering method is FILTER\_CONVENTIONAL. #### Examples ``` >>> mod = sm.tsa.statespace.SARIMAX(range(10)) >>> mod.ssm.filter_method 1 >>> mod.ssm.filter_conventional True >>> mod.ssm.filter_univariate = True >>> mod.ssm.filter_method 17 >>> mod.ssm.set_filter_method(filter_univariate=False, ... filter_collapsed=True) >>> mod.ssm.filter_method 33 >>> mod.ssm.set_filter_method(filter_method=1) >>> mod.ssm.filter_conventional True >>> mod.ssm.filter_univariate False >>> mod.ssm.filter_collapsed False >>> mod.ssm.filter_univariate = True >>> mod.ssm.filter_method 17 ``` statsmodels statsmodels.discrete.discrete_model.NegativeBinomial.fit_regularized statsmodels.discrete.discrete\_model.NegativeBinomial.fit\_regularized ====================================================================== `NegativeBinomial.fit_regularized(start_params=None, method='l1', maxiter='defined_by_method', full_output=1, disp=1, callback=None, alpha=0, trim_mode='auto', auto_trim_tol=0.01, size_trim_tol=0.0001, qc_tol=0.03, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#NegativeBinomial.fit_regularized) Fit the model using a regularized maximum likelihood. The regularization method AND the solver used is determined by the argument method. | Parameters: | * **start\_params** (*array-like**,* *optional*) – Initial guess of the solution for the loglikelihood maximization. The default is an array of zeros. * **method** (*'l1'* *or* *'l1\_cvxopt\_cp'*) – See notes for details. * **maxiter** (*Integer* *or* *'defined\_by\_method'*) – Maximum number of iterations to perform. If ‘defined\_by\_method’, then use method defaults (see notes). * **full\_output** (*bool*) – Set to True to have all available output in the Results object’s mle\_retvals attribute. The output is dependent on the solver. See LikelihoodModelResults notes section for more information. * **disp** (*bool*) – Set to True to print convergence messages. * **fargs** (*tuple*) – Extra arguments passed to the likelihood function, i.e., loglike(x,\*args) * **callback** (*callable callback**(**xk**)*) – Called after each iteration, as callback(xk), where xk is the current parameter vector. * **retall** (*bool*) – Set to True to return list of solutions at each iteration. Available in Results object’s mle\_retvals attribute. * **alpha** (*non-negative scalar* *or* *numpy array* *(**same size as parameters**)*) – The weight multiplying the l1 penalty term * **trim\_mode** (*'auto**,* *'size'**, or* *'off'*) – If not ‘off’, trim (set to zero) parameters that would have been zero if the solver reached the theoretical minimum. If ‘auto’, trim params using the Theory above. If ‘size’, trim params if they have very small absolute value * **size\_trim\_tol** (*float* *or* *'auto'* *(**default = 'auto'**)*) – For use when trim\_mode == ‘size’ * **auto\_trim\_tol** (*float*) – For sue when trim\_mode == ‘auto’. Use * **qc\_tol** (*float*) – Print warning and don’t allow auto trim when (ii) (above) is violated by this much. * **qc\_verbose** (*Boolean*) – If true, print out a full QC report upon failure | #### Notes Extra parameters are not penalized if alpha is given as a scalar. An example is the shape parameter in NegativeBinomial `nb1` and `nb2`. Optional arguments for the solvers (available in Results.mle\_settings): ``` 'l1' acc : float (default 1e-6) Requested accuracy as used by slsqp 'l1_cvxopt_cp' abstol : float absolute accuracy (default: 1e-7). reltol : float relative accuracy (default: 1e-6). feastol : float tolerance for feasibility conditions (default: 1e-7). refinement : int number of iterative refinement steps when solving KKT equations (default: 1). ``` Optimization methodology With \(L\) the negative log likelihood, we solve the convex but non-smooth problem \[\min\_\beta L(\beta) + \sum\_k\alpha\_k |\beta\_k|\] via the transformation to the smooth, convex, constrained problem in twice as many variables (adding the “added variables” \(u\_k\)) \[\min\_{\beta,u} L(\beta) + \sum\_k\alpha\_k u\_k,\] subject to \[-u\_k \leq \beta\_k \leq u\_k.\] With \(\partial\_k L\) the derivative of \(L\) in the \(k^{th}\) parameter direction, theory dictates that, at the minimum, exactly one of two conditions holds: 1. \(|\partial\_k L| = \alpha\_k\) and \(\beta\_k \neq 0\) 2. \(|\partial\_k L| \leq \alpha\_k\) and \(\beta\_k = 0\) statsmodels statsmodels.discrete.discrete_model.Poisson.predict statsmodels.discrete.discrete\_model.Poisson.predict ==================================================== `Poisson.predict(params, exog=None, exposure=None, offset=None, linear=False)` Predict response variable of a count model given exogenous variables. #### Notes If exposure is specified, then it will be logged by the method. The user does not need to log it first. statsmodels statsmodels.tsa.statespace.varmax.VARMAXResults.test_serial_correlation statsmodels.tsa.statespace.varmax.VARMAXResults.test\_serial\_correlation ========================================================================= `VARMAXResults.test_serial_correlation(method, lags=None)` Ljung-box test for no serial correlation of standardized residuals Null hypothesis is no serial correlation. | Parameters: | * **method** (*string {'ljungbox'**,**'boxpierece'}* *or* *None*) – The statistical test for serial correlation. If None, an attempt is made to select an appropriate test. * **lags** (*None**,* *int* *or* *array\_like*) – If lags is an integer then this is taken to be the largest lag that is included, the test result is reported for all smaller lag length. If lags is a list or array, then all lags are included up to the largest lag in the list, however only the tests for the lags in the list are reported. If lags is None, then the default maxlag is 12\*(nobs/100)^{1/4} | | Returns: | **output** – An array with `(test_statistic, pvalue)` for each endogenous variable and each lag. The array is then sized `(k_endog, 2, lags)`. If the method is called as `ljungbox = res.test_serial_correlation()`, then `ljungbox[i]` holds the results of the Ljung-Box test (as would be returned by `statsmodels.stats.diagnostic.acorr_ljungbox`) for the `i` th endogenous variable. | | Return type: | array | #### Notes If the first `d` loglikelihood values were burned (i.e. in the specified model, `loglikelihood_burn=d`), then this test is calculated ignoring the first `d` residuals. Output is nan for any endogenous variable which has missing values. See also [`statsmodels.stats.diagnostic.acorr_ljungbox`](statsmodels.stats.diagnostic.acorr_ljungbox#statsmodels.stats.diagnostic.acorr_ljungbox "statsmodels.stats.diagnostic.acorr_ljungbox") statsmodels statsmodels.stats.outliers_influence.OLSInfluence.hat_diag_factor statsmodels.stats.outliers\_influence.OLSInfluence.hat\_diag\_factor ==================================================================== `OLSInfluence.hat_diag_factor()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/outliers_influence.html#OLSInfluence.hat_diag_factor) (cached attribute) factor of diagonal of hat\_matrix used in influence this might be useful for internal reuse h / (1 - h) statsmodels statsmodels.tsa.tsatools.add_trend statsmodels.tsa.tsatools.add\_trend =================================== `statsmodels.tsa.tsatools.add_trend(x, trend='c', prepend=False, has_constant='skip')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/tsatools.html#add_trend) Adds a trend and/or constant to an array. | Parameters: | * **X** (*array-like*) – Original array of data. * **trend** (*str {"c"**,**"t"**,**"ct"**,**"ctt"}*) – “c” add constant only “t” add trend only “ct” add constant and linear trend “ctt” add constant and linear and quadratic trend. * **prepend** (*bool*) – If True, prepends the new data to the columns of X. * **has\_constant** (*str {'raise'**,* *'add'**,* *'skip'}*) – Controls what happens when trend is ‘c’ and a constant already exists in X. ‘raise’ will raise an error. ‘add’ will duplicate a constant. ‘skip’ will return the data without change. ‘skip’ is the default. | | Returns: | **y** – The original data with the additional trend columns. If x is a recarray or pandas Series or DataFrame, then the trend column names are ‘const’, ‘trend’ and ‘trend\_squared’. | | Return type: | array, recarray or DataFrame | #### Notes Returns columns as [“ctt”,”ct”,”c”] whenever applicable. There is currently no checking for an existing trend. See also [`statsmodels.tools.tools.add_constant`](statsmodels.tools.tools.add_constant#statsmodels.tools.tools.add_constant "statsmodels.tools.tools.add_constant") statsmodels statsmodels.sandbox.stats.multicomp.GroupsStats statsmodels.sandbox.stats.multicomp.GroupsStats =============================================== `class statsmodels.sandbox.stats.multicomp.GroupsStats(x, useranks=False, uni=None, intlab=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/multicomp.html#GroupsStats) statistics by groups (another version) groupstats as a class with lazy evaluation (not yet - decorators are still missing) written this time as equivalent of scipy.stats.rankdata gs = GroupsStats(X, useranks=True) assert\_almost\_equal(gs.groupmeanfilter, stats.rankdata(X[:,0]), 15) TODO: incomplete doc strings #### Methods | | | | --- | --- | | [`groupdemean`](statsmodels.sandbox.stats.multicomp.groupsstats.groupdemean#statsmodels.sandbox.stats.multicomp.GroupsStats.groupdemean "statsmodels.sandbox.stats.multicomp.GroupsStats.groupdemean")() | | | [`groupsswithin`](statsmodels.sandbox.stats.multicomp.groupsstats.groupsswithin#statsmodels.sandbox.stats.multicomp.GroupsStats.groupsswithin "statsmodels.sandbox.stats.multicomp.GroupsStats.groupsswithin")() | | | [`groupvarwithin`](statsmodels.sandbox.stats.multicomp.groupsstats.groupvarwithin#statsmodels.sandbox.stats.multicomp.GroupsStats.groupvarwithin "statsmodels.sandbox.stats.multicomp.GroupsStats.groupvarwithin")() | | | [`runbasic`](statsmodels.sandbox.stats.multicomp.groupsstats.runbasic#statsmodels.sandbox.stats.multicomp.GroupsStats.runbasic "statsmodels.sandbox.stats.multicomp.GroupsStats.runbasic")([useranks]) | | | [`runbasic_old`](statsmodels.sandbox.stats.multicomp.groupsstats.runbasic_old#statsmodels.sandbox.stats.multicomp.GroupsStats.runbasic_old "statsmodels.sandbox.stats.multicomp.GroupsStats.runbasic_old")([useranks]) | |
programming_docs
statsmodels statsmodels.genmod.generalized_estimating_equations.GEEResults.wald_test_terms statsmodels.genmod.generalized\_estimating\_equations.GEEResults.wald\_test\_terms ================================================================================== `GEEResults.wald_test_terms(skip_single=False, extra_constraints=None, combine_terms=None)` Compute a sequence of Wald tests for terms over multiple columns This computes joined Wald tests for the hypothesis that all coefficients corresponding to a `term` are zero. `Terms` are defined by the underlying formula or by string matching. | Parameters: | * **skip\_single** (*boolean*) – If true, then terms that consist only of a single column and, therefore, refers only to a single parameter is skipped. If false, then all terms are included. * **extra\_constraints** (*ndarray*) – not tested yet * **combine\_terms** (*None* *or* *list of strings*) – Each string in this list is matched to the name of the terms or the name of the exogenous variables. All columns whose name includes that string are combined in one joint test. | | Returns: | **test\_result** – The result instance contains `table` which is a pandas DataFrame with the test results: test statistic, degrees of freedom and pvalues. | | Return type: | result instance | #### Examples ``` >>> res_ols = ols("np.log(Days+1) ~ C(Duration, Sum)*C(Weight, Sum)", data).fit() >>> res_ols.wald_test_terms() <class 'statsmodels.stats.contrast.WaldTestResults'> F P>F df constraint df denom Intercept 279.754525 2.37985521351e-22 1 51 C(Duration, Sum) 5.367071 0.0245738436636 1 51 C(Weight, Sum) 12.432445 3.99943118767e-05 2 51 C(Duration, Sum):C(Weight, Sum) 0.176002 0.83912310946 2 51 ``` ``` >>> res_poi = Poisson.from_formula("Days ~ C(Weight) * C(Duration)", data).fit(cov_type='HC0') >>> wt = res_poi.wald_test_terms(skip_single=False, combine_terms=['Duration', 'Weight']) >>> print(wt) chi2 P>chi2 df constraint Intercept 15.695625 7.43960374424e-05 1 C(Weight) 16.132616 0.000313940174705 2 C(Duration) 1.009147 0.315107378931 1 C(Weight):C(Duration) 0.216694 0.897315972824 2 Duration 11.187849 0.010752286833 3 Weight 30.263368 4.32586407145e-06 4 ``` statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.t_test_pairwise statsmodels.sandbox.regression.gmm.IVRegressionResults.t\_test\_pairwise ======================================================================== `IVRegressionResults.t_test_pairwise(term_name, method='hs', alpha=0.05, factor_labels=None)` perform pairwise t\_test with multiple testing corrected p-values This uses the formula design\_info encoding contrast matrix and should work for all encodings of a main effect. | Parameters: | * **result** (*result instance*) – The results of an estimated model with a categorical main effect. * **term\_name** (*str*) – name of the term for which pairwise comparisons are computed. Term names for categorical effects are created by patsy and correspond to the main part of the exog names. * **method** (*str* *or* *list of strings*) – multiple testing p-value correction, default is ‘hs’, see stats.multipletesting * **alpha** (*float*) – significance level for multiple testing reject decision. * **factor\_labels** (*None**,* *list of str*) – Labels for the factor levels used for pairwise labels. If not provided, then the labels from the formula design\_info are used. | | Returns: | **results** – The results are stored as attributes, the main attributes are the following two. Other attributes are added for debugging purposes or as background information.* result\_frame : pandas DataFrame with t\_test results and multiple testing corrected p-values. * contrasts : matrix of constraints of the null hypothesis in the t\_test. | | Return type: | instance of a simple Results class | #### Notes Status: experimental. Currently only checked for treatment coding with and without specified reference level. Currently there are no multiple testing corrected confidence intervals available. #### Examples ``` >>> res = ols("np.log(Days+1) ~ C(Weight) + C(Duration)", data).fit() >>> pw = res.t_test_pairwise("C(Weight)") >>> pw.result_frame coef std err t P>|t| Conf. Int. Low 2-1 0.632315 0.230003 2.749157 8.028083e-03 0.171563 3-1 1.302555 0.230003 5.663201 5.331513e-07 0.841803 3-2 0.670240 0.230003 2.914044 5.119126e-03 0.209488 Conf. Int. Upp. pvalue-hs reject-hs 2-1 1.093067 0.010212 True 3-1 1.763307 0.000002 True 3-2 1.130992 0.010212 True ``` statsmodels statsmodels.tsa.vector_ar.hypothesis_test_results.CausalityTestResults statsmodels.tsa.vector\_ar.hypothesis\_test\_results.CausalityTestResults ========================================================================= `class statsmodels.tsa.vector_ar.hypothesis_test_results.CausalityTestResults(causing, caused, test_statistic, crit_value, pvalue, df, signif, test='granger', method=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/hypothesis_test_results.html#CausalityTestResults) Results class for Granger-causality and instantaneous causality. | Parameters: | * **causing** (*list of str*) – This list contains the potentially causing variables. * **caused** (*list of str*) – This list contains the potentially caused variables. * **test\_statistic** (*float*) – * **crit\_value** (*float*) – * **pvalue** (*float*) – * **df** (*int*) – Degrees of freedom. * **signif** (*float*) – Significance level. * **test** (str {`"granger"`, `"inst"`}, default: `"granger"`) – If `"granger"`, Granger-causality has been tested. If `"inst"`, instantaneous causality has been tested. * **method** (str {`"f"`, `"wald"`}) – The kind of test. `"f"` indicates an F-test, `"wald"` indicates a Wald-test. | #### Methods | | | | --- | --- | | [`summary`](statsmodels.tsa.vector_ar.hypothesis_test_results.causalitytestresults.summary#statsmodels.tsa.vector_ar.hypothesis_test_results.CausalityTestResults.summary "statsmodels.tsa.vector_ar.hypothesis_test_results.CausalityTestResults.summary")() | | statsmodels statsmodels.tsa.vector_ar.var_model.VAR statsmodels.tsa.vector\_ar.var\_model.VAR ========================================= `class statsmodels.tsa.vector_ar.var_model.VAR(endog, exog=None, dates=None, freq=None, missing='none')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/var_model.html#VAR) Fit VAR(p) process and do lag order selection \[y\_t = A\_1 y\_{t-1} + \ldots + A\_p y\_{t-p} + u\_t\] | Parameters: | * **endog** (*array-like*) – 2-d endogenous response variable. The independent variable. * **exog** (*array-like*) – 2-d exogenous variable. * **dates** (*array-like*) – must match number of rows of endog | #### References Lütkepohl (2005) New Introduction to Multiple Time Series Analysis #### Methods | | | | --- | --- | | [`fit`](statsmodels.tsa.vector_ar.var_model.var.fit#statsmodels.tsa.vector_ar.var_model.VAR.fit "statsmodels.tsa.vector_ar.var_model.VAR.fit")([maxlags, method, ic, trend, verbose]) | Fit the VAR model | | [`from_formula`](statsmodels.tsa.vector_ar.var_model.var.from_formula#statsmodels.tsa.vector_ar.var_model.VAR.from_formula "statsmodels.tsa.vector_ar.var_model.VAR.from_formula")(formula, data[, subset, drop\_cols]) | Create a Model from a formula and dataframe. | | [`hessian`](statsmodels.tsa.vector_ar.var_model.var.hessian#statsmodels.tsa.vector_ar.var_model.VAR.hessian "statsmodels.tsa.vector_ar.var_model.VAR.hessian")(params) | The Hessian matrix of the model | | [`information`](statsmodels.tsa.vector_ar.var_model.var.information#statsmodels.tsa.vector_ar.var_model.VAR.information "statsmodels.tsa.vector_ar.var_model.VAR.information")(params) | Fisher information matrix of model | | [`initialize`](statsmodels.tsa.vector_ar.var_model.var.initialize#statsmodels.tsa.vector_ar.var_model.VAR.initialize "statsmodels.tsa.vector_ar.var_model.VAR.initialize")() | Initialize (possibly re-initialize) a Model instance. | | [`loglike`](statsmodels.tsa.vector_ar.var_model.var.loglike#statsmodels.tsa.vector_ar.var_model.VAR.loglike "statsmodels.tsa.vector_ar.var_model.VAR.loglike")(params) | Log-likelihood of model. | | [`predict`](statsmodels.tsa.vector_ar.var_model.var.predict#statsmodels.tsa.vector_ar.var_model.VAR.predict "statsmodels.tsa.vector_ar.var_model.VAR.predict")(params[, start, end, lags, trend]) | Returns in-sample predictions or forecasts | | [`score`](statsmodels.tsa.vector_ar.var_model.var.score#statsmodels.tsa.vector_ar.var_model.VAR.score "statsmodels.tsa.vector_ar.var_model.VAR.score")(params) | Score vector of model. | | [`select_order`](statsmodels.tsa.vector_ar.var_model.var.select_order#statsmodels.tsa.vector_ar.var_model.VAR.select_order "statsmodels.tsa.vector_ar.var_model.VAR.select_order")([maxlags, trend]) | Compute lag order selections based on each of the available information criteria | #### Attributes | | | | --- | --- | | `endog_names` | Names of endogenous variables | | `exog_names` | | statsmodels statsmodels.regression.linear_model.GLS statsmodels.regression.linear\_model.GLS ======================================== `class statsmodels.regression.linear_model.GLS(endog, exog, sigma=None, missing='none', hasconst=None, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#GLS) Generalized least squares model with a general covariance structure. | Parameters: | * **endog** (*array-like*) – 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 `statsmodels.tools.add_constant`. * **sigma** (*scalar* *or* *array*) – `sigma` is the weighting matrix of the covariance. The default is None for no scaling. If `sigma` is a scalar, it is assumed that `sigma` is an n x n diagonal matrix with the given scalar, `sigma` as the value of each diagonal element. If `sigma` is an n-length vector, then `sigma` is assumed to be a diagonal matrix with the given `sigma` on the diagonal. This should be the same as WLS. * **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. | **Attributes** `pinv_wexog : array` `pinv_wexog` is the p x n Moore-Penrose pseudoinverse of `wexog`. `cholsimgainv : array` The transpose of the Cholesky decomposition of the pseudoinverse. `df_model : float` p - 1, where p is the number of regressors including the intercept. of freedom. `df_resid : float` Number of observations n less the number of parameters p. `llf : float` The value of the likelihood function of the fitted model. `nobs : float` The number of observations n. `normalized_cov_params : array` p x p array \((X^{T}\Sigma^{-1}X)^{-1}\) `results : RegressionResults instance` A property that returns the RegressionResults class if fit. `sigma : array` `sigma` is the n x n covariance structure of the error terms. `wexog : array` Design matrix whitened by `cholsigmainv` `wendog : array` Response variable whitened by `cholsigmainv` #### Notes If sigma is a function of the data making one of the regressors a constant, then the current postestimation statistics will not be correct. #### Examples ``` >>> import numpy as np >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> ols_resid = sm.OLS(data.endog, data.exog).fit().resid >>> res_fit = sm.OLS(ols_resid[1:], ols_resid[:-1]).fit() >>> rho = res_fit.params ``` `rho` is a consistent estimator of the correlation of the residuals from an OLS fit of the longley data. It is assumed that this is the true rho of the AR process data. ``` >>> from scipy.linalg import toeplitz >>> order = toeplitz(np.arange(16)) >>> sigma = rho**order ``` `sigma` is an n x n matrix of the autocorrelation structure of the data. ``` >>> gls_model = sm.GLS(data.endog, data.exog, sigma=sigma) >>> gls_results = gls_model.fit() >>> print(gls_results.summary()) ``` #### Methods | | | | --- | --- | | [`fit`](statsmodels.regression.linear_model.gls.fit#statsmodels.regression.linear_model.GLS.fit "statsmodels.regression.linear_model.GLS.fit")([method, cov\_type, cov\_kwds, use\_t]) | Full fit of the model. | | [`fit_regularized`](statsmodels.regression.linear_model.gls.fit_regularized#statsmodels.regression.linear_model.GLS.fit_regularized "statsmodels.regression.linear_model.GLS.fit_regularized")([method, alpha, L1\_wt, …]) | Return a regularized fit to a linear regression model. | | [`from_formula`](statsmodels.regression.linear_model.gls.from_formula#statsmodels.regression.linear_model.GLS.from_formula "statsmodels.regression.linear_model.GLS.from_formula")(formula, data[, subset, drop\_cols]) | Create a Model from a formula and dataframe. | | [`get_distribution`](statsmodels.regression.linear_model.gls.get_distribution#statsmodels.regression.linear_model.GLS.get_distribution "statsmodels.regression.linear_model.GLS.get_distribution")(params, scale[, exog, …]) | Returns a random number generator for the predictive distribution. | | [`hessian`](statsmodels.regression.linear_model.gls.hessian#statsmodels.regression.linear_model.GLS.hessian "statsmodels.regression.linear_model.GLS.hessian")(params) | The Hessian matrix of the model | | [`hessian_factor`](statsmodels.regression.linear_model.gls.hessian_factor#statsmodels.regression.linear_model.GLS.hessian_factor "statsmodels.regression.linear_model.GLS.hessian_factor")(params[, scale, observed]) | Weights for calculating Hessian | | [`information`](statsmodels.regression.linear_model.gls.information#statsmodels.regression.linear_model.GLS.information "statsmodels.regression.linear_model.GLS.information")(params) | Fisher information matrix of model | | [`initialize`](statsmodels.regression.linear_model.gls.initialize#statsmodels.regression.linear_model.GLS.initialize "statsmodels.regression.linear_model.GLS.initialize")() | Initialize (possibly re-initialize) a Model instance. | | [`loglike`](statsmodels.regression.linear_model.gls.loglike#statsmodels.regression.linear_model.GLS.loglike "statsmodels.regression.linear_model.GLS.loglike")(params) | Returns the value of the Gaussian log-likelihood function at params. | | [`predict`](statsmodels.regression.linear_model.gls.predict#statsmodels.regression.linear_model.GLS.predict "statsmodels.regression.linear_model.GLS.predict")(params[, exog]) | Return linear predicted values from a design matrix. | | [`score`](statsmodels.regression.linear_model.gls.score#statsmodels.regression.linear_model.GLS.score "statsmodels.regression.linear_model.GLS.score")(params) | Score vector of model. | | [`whiten`](statsmodels.regression.linear_model.gls.whiten#statsmodels.regression.linear_model.GLS.whiten "statsmodels.regression.linear_model.GLS.whiten")(X) | GLS whiten method. | #### Attributes | | | | --- | --- | | `df_model` | The model degree of freedom, defined as the rank of the regressor matrix minus 1 if a constant is included. | | `df_resid` | The residual degree of freedom, defined as the number of observations minus the rank of the regressor matrix. | | `endog_names` | Names of endogenous variables | | `exog_names` | Names of exogenous variables | statsmodels statsmodels.stats.proportion.proportion_confint statsmodels.stats.proportion.proportion\_confint ================================================ `statsmodels.stats.proportion.proportion_confint(count, nobs, alpha=0.05, method='normal')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/proportion.html#proportion_confint) confidence interval for a binomial proportion | Parameters: | * **count** (*int* *or* *array\_array\_like*) – number of successes, can be pandas Series or DataFrame * **nobs** (*int*) – total number of trials * **alpha** (*float in* *(**0**,* *1**)*) – significance level, default 0.05 * **method** (*string in* *[**'normal'**]*) – method to use for confidence interval, currently available methods : + `normal` : asymptotic normal approximation + `agresti_coull` : Agresti-Coull interval + `beta` : Clopper-Pearson interval based on Beta distribution + `wilson` : Wilson Score interval + `jeffreys` : Jeffreys Bayesian Interval + `binom_test` : experimental, inversion of binom\_test | | Returns: | **ci\_low, ci\_upp** – lower and upper confidence level with coverage (approximately) 1-alpha. When a pandas object is returned, then the index is taken from the `count`. | | Return type: | float, ndarray, or pandas Series or DataFrame | #### Notes Beta, the Clopper-Pearson exact interval has coverage at least 1-alpha, but is in general conservative. Most of the other methods have average coverage equal to 1-alpha, but will have smaller coverage in some cases. The ‘beta’ and ‘jeffreys’ interval are central, they use alpha/2 in each tail, and alpha is not adjusted at the boundaries. In the extreme case when `count` is zero or equal to `nobs`, then the coverage will be only 1 - alpha/2 in the case of ‘beta’. The confidence intervals are clipped to be in the [0, 1] interval in the case of ‘normal’ and ‘agresti\_coull’. Method “binom\_test” directly inverts the binomial test in scipy.stats. which has discrete steps. TODO: binom\_test intervals raise an exception in small samples if one interval bound is close to zero or one. #### References <http://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval> Brown, Lawrence D.; Cai, T. Tony; DasGupta, Anirban (2001). “Interval Estimation for a Binomial Proportion”, Statistical Science 16 (2): 101–133. doi:10.1214/ss/1009213286. TODO: Is this the correct one ? statsmodels statsmodels.regression.mixed_linear_model.MixedLMResults.bic statsmodels.regression.mixed\_linear\_model.MixedLMResults.bic ============================================================== `MixedLMResults.bic()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/mixed_linear_model.html#MixedLMResults.bic) statsmodels statsmodels.iolib.table.SimpleTable.insert statsmodels.iolib.table.SimpleTable.insert ========================================== `SimpleTable.insert(idx, row, datatype=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/iolib/table.html#SimpleTable.insert) Return None. Insert a row into a table. statsmodels statsmodels.regression.recursive_ls.RecursiveLSResults.plot_cusum_squares statsmodels.regression.recursive\_ls.RecursiveLSResults.plot\_cusum\_squares ============================================================================ `RecursiveLSResults.plot_cusum_squares(alpha=0.05, legend_loc='upper left', fig=None, figsize=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/recursive_ls.html#RecursiveLSResults.plot_cusum_squares) Plot the CUSUM of squares statistic and significance bounds. | Parameters: | * **alpha** (*float**,* *optional*) – The plotted significance bounds are alpha %. * **legend\_loc** (*string**,* *optional*) – The location of the legend in the plot. Default is upper left. * **fig** (*Matplotlib Figure instance**,* *optional*) – If given, subplots are created in this figure instead of in a new figure. Note that the grid will be created in the provided figure using `fig.add_subplot()`. * **figsize** (*tuple**,* *optional*) – If a figure is created, this argument allows specifying a size. The tuple is (width, height). | #### Notes Evidence of parameter instability may be found if the CUSUM of squares statistic moves out of the significance bounds. Critical values used in creating the significance bounds are computed using the approximate formula of [[1]](#id3). #### References | | | | --- | --- | | [\*] | Brown, R. L., J. Durbin, and J. M. Evans. 1975. “Techniques for Testing the Constancy of Regression Relationships over Time.” Journal of the Royal Statistical Society. Series B (Methodological) 37 (2): 149-92. | | | | | --- | --- | | [[1]](#id1) | Edgerton, David, and Curt Wells. 1994. “Critical Values for the Cusumsq Statistic in Medium and Large Sized Samples.” Oxford Bulletin of Economics and Statistics 56 (3): 355-65. |
programming_docs
statsmodels statsmodels.tsa.statespace.sarimax.SARIMAXResults.arparams statsmodels.tsa.statespace.sarimax.SARIMAXResults.arparams ========================================================== `SARIMAXResults.arparams()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/sarimax.html#SARIMAXResults.arparams) (array) Autoregressive parameters actually estimated in the model. Does not include seasonal autoregressive parameters (see `seasonalarparams`) or parameters whose values are constrained to be zero. statsmodels statsmodels.tsa.statespace.sarimax.SARIMAX.set_smoother_output statsmodels.tsa.statespace.sarimax.SARIMAX.set\_smoother\_output ================================================================ `SARIMAX.set_smoother_output(smoother_output=None, **kwargs)` Set the smoother output The smoother can produce several types of results. The smoother output variable controls which are calculated and returned. | Parameters: | * **smoother\_output** (*integer**,* *optional*) – Bitmask value to set the smoother output to. See notes for details. * **\*\*kwargs** – Keyword arguments may be used to influence the smoother output by setting individual boolean flags. | #### Notes This method is rarely used. See the corresponding function in the `KalmanSmoother` class for details. statsmodels statsmodels.tsa.statespace.mlemodel.MLEResults.load statsmodels.tsa.statespace.mlemodel.MLEResults.load =================================================== `classmethod MLEResults.load(fname)` load a pickle, (class method) | Parameters: | **fname** (*string* *or* *filehandle*) – fname can be a string to a file path or filename, or a filehandle. | | Returns: | | | Return type: | unpickled instance | statsmodels statsmodels.stats.diagnostic.acorr_ljungbox statsmodels.stats.diagnostic.acorr\_ljungbox ============================================ `statsmodels.stats.diagnostic.acorr_ljungbox(x, lags=None, boxpierce=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/diagnostic.html#acorr_ljungbox) Ljung-Box test for no autocorrelation | Parameters: | * **x** (*array\_like**,* *1d*) – data series, regression residuals when used as diagnostic test * **lags** (*None**,* *int* *or* *array\_like*) – If lags is an integer then this is taken to be the largest lag that is included, the test result is reported for all smaller lag length. If lags is a list or array, then all lags are included up to the largest lag in the list, however only the tests for the lags in the list are reported. If lags is None, then the default maxlag is ‘min((nobs // 2 - 2), 40)’ * **boxpierce** (*{False**,* *True}*) – If true, then additional to the results of the Ljung-Box test also the Box-Pierce test results are returned | | Returns: | * **lbvalue** (*float or array*) – test statistic * **pvalue** (*float or array*) – p-value based on chi-square distribution * **bpvalue** (*(optionsal), float or array*) – test statistic for Box-Pierce test * **bppvalue** (*(optional), float or array*) – p-value based for Box-Pierce test on chi-square distribution | #### Notes Ljung-Box and Box-Pierce statistic differ in their scaling of the autocorrelation function. Ljung-Box test is reported to have better small sample properties. TODO: could be extended to work with more than one series 1d or nd ? axis ? ravel ? needs more testing *Verification* Looks correctly sized in Monte Carlo studies. not yet compared to verified values #### Examples see example script #### References Greene Wikipedia statsmodels statsmodels.sandbox.tsa.fftarma.ArmaFft.plot4 statsmodels.sandbox.tsa.fftarma.ArmaFft.plot4 ============================================= `ArmaFft.plot4(fig=None, nobs=100, nacf=20, nfreq=100)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/tsa/fftarma.html#ArmaFft.plot4) statsmodels statsmodels.tsa.statespace.kalman_smoother.SmootherResults.update_filter statsmodels.tsa.statespace.kalman\_smoother.SmootherResults.update\_filter ========================================================================== `SmootherResults.update_filter(kalman_filter)` Update the filter results | Parameters: | **kalman\_filter** ([statespace.kalman\_filter.KalmanFilter](statsmodels.tsa.statespace.kalman_filter.kalmanfilter#statsmodels.tsa.statespace.kalman_filter.KalmanFilter "statsmodels.tsa.statespace.kalman_filter.KalmanFilter")) – The model object from which to take the updated values. | #### Notes This method is rarely required except for internal usage. statsmodels statsmodels.genmod.families.links.NegativeBinomial.deriv2 statsmodels.genmod.families.links.NegativeBinomial.deriv2 ========================================================= `NegativeBinomial.deriv2(p)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/links.html#NegativeBinomial.deriv2) Second derivative of the negative binomial link function. | Parameters: | **p** (*array-like*) – Mean parameters | | Returns: | **g’‘(p)** – The second derivative of the negative binomial transform link function | | Return type: | array | #### Notes g’‘(x) = -(1+2\*alpha\*x)/(x+alpha\*x^2)^2 statsmodels statsmodels.sandbox.distributions.extras.NormExpan_gen.logpdf statsmodels.sandbox.distributions.extras.NormExpan\_gen.logpdf ============================================================== `NormExpan_gen.logpdf(x, *args, **kwds)` Log of the probability density function at x of the given RV. This uses a more numerically accurate calculation if available. | Parameters: | * **x** (*array\_like*) – quantiles * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **logpdf** – Log of the probability density function evaluated at x | | Return type: | array\_like | statsmodels statsmodels.tsa.statespace.mlemodel.MLEResults.wald_test statsmodels.tsa.statespace.mlemodel.MLEResults.wald\_test ========================================================= `MLEResults.wald_test(r_matrix, cov_p=None, scale=1.0, invcov=None, use_f=None)` Compute a Wald-test for a joint linear hypothesis. | Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) – + array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length p row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – Default is 1.0 for no scaling. * **invcov** (*array-like**,* *optional*) – A q x q array to specify an inverse covariance matrix based on a restrictions matrix. * **use\_f** (*bool*) – If True, then the F-distribution is used. If False, then the asymptotic distribution, chisquare is used. If use\_f is None, then the F distribution is used if the model specifies that use\_t is True. The test statistic is proportionally adjusted for the distribution by the number of constraints in the hypothesis. | | Returns: | **res** – The results for the test are attributes of this results instance. | | Return type: | ContrastResults instance | See also [`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`f_test`](statsmodels.tsa.statespace.mlemodel.mleresults.f_test#statsmodels.tsa.statespace.mlemodel.MLEResults.f_test "statsmodels.tsa.statespace.mlemodel.MLEResults.f_test"), [`t_test`](statsmodels.tsa.statespace.mlemodel.mleresults.t_test#statsmodels.tsa.statespace.mlemodel.MLEResults.t_test "statsmodels.tsa.statespace.mlemodel.MLEResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") #### Notes The matrix `r_matrix` is assumed to be non-singular. More precisely, r\_matrix (pX pX.T) r\_matrix.T is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full. statsmodels statsmodels.tsa.statespace.structural.UnobservedComponentsResults.forecast statsmodels.tsa.statespace.structural.UnobservedComponentsResults.forecast ========================================================================== `UnobservedComponentsResults.forecast(steps=1, **kwargs)` Out-of-sample forecasts | Parameters: | * **steps** (*int**,* *str**, or* *datetime**,* *optional*) – If an integer, the number of steps to forecast from the end of the sample. Can also be a date string to parse or a datetime type. However, if the dates index does not have a fixed frequency, steps must be an integer. Default * **\*\*kwargs** – Additional arguments may required for forecasting beyond the end of the sample. See `FilterResults.predict` for more details. | | Returns: | **forecast** – Array of out of sample forecasts. A (steps x k\_endog) array. | | Return type: | array | statsmodels statsmodels.regression.recursive_ls.RecursiveLSResults.info_criteria statsmodels.regression.recursive\_ls.RecursiveLSResults.info\_criteria ====================================================================== `RecursiveLSResults.info_criteria(criteria, method='standard')` Information criteria | Parameters: | * **criteria** (*{'aic'**,* *'bic'**,* *'hqic'}*) – The information criteria to compute. * **method** (*{'standard'**,* *'lutkepohl'}*) – The method for information criteria computation. Default is ‘standard’ method; ‘lutkepohl’ computes the information criteria as in Lütkepohl (2007). See Notes for formulas. | #### Notes The `‘standard’` formulas are: \[\begin{split}AIC & = -2 \log L(Y\_n | \hat \psi) + 2 k \\ BIC & = -2 \log L(Y\_n | \hat \psi) + k \log n \\ HQIC & = -2 \log L(Y\_n | \hat \psi) + 2 k \log \log n \\\end{split}\] where \(\hat \psi\) are the maximum likelihood estimates of the parameters, \(n\) is the number of observations, and `k` is the number of estimated parameters. Note that the `‘standard’` formulas are returned from the `aic`, `bic`, and `hqic` results attributes. The `‘lutkepohl’` formuals are (Lütkepohl, 2010): \[\begin{split}AIC\_L & = \log | Q | + \frac{2 k}{n} \\ BIC\_L & = \log | Q | + \frac{k \log n}{n} \\ HQIC\_L & = \log | Q | + \frac{2 k \log \log n}{n} \\\end{split}\] where \(Q\) is the state covariance matrix. Note that the Lütkepohl definitions do not apply to all state space models, and should be used with care outside of SARIMAX and VARMAX models. #### References | | | | --- | --- | | [\*] | Lütkepohl, Helmut. 2007. *New Introduction to Multiple Time* *Series Analysis.* Berlin: Springer. | statsmodels statsmodels.discrete.discrete_model.CountResults.bic statsmodels.discrete.discrete\_model.CountResults.bic ===================================================== `CountResults.bic()` statsmodels statsmodels.discrete.discrete_model.LogitResults.resid_dev statsmodels.discrete.discrete\_model.LogitResults.resid\_dev ============================================================ `LogitResults.resid_dev()` Deviance residuals #### Notes Deviance residuals are defined \[d\_j = \pm\left(2\left[Y\_j\ln\left(\frac{Y\_j}{M\_jp\_j}\right) + (M\_j - Y\_j\ln\left(\frac{M\_j-Y\_j}{M\_j(1-p\_j)} \right) \right] \right)^{1/2}\] where \(p\_j = cdf(X\beta)\) and \(M\_j\) is the total number of observations sharing the covariate pattern \(j\). For now \(M\_j\) is always set to 1. statsmodels statsmodels.sandbox.stats.multicomp.rejectionline statsmodels.sandbox.stats.multicomp.rejectionline ================================================= `statsmodels.sandbox.stats.multicomp.rejectionline(n, alpha=0.5)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/multicomp.html#rejectionline) reference line for rejection in multiple tests Not used anymore from: section 3.2, page 60 statsmodels statsmodels.discrete.discrete_model.MNLogit.fit statsmodels.discrete.discrete\_model.MNLogit.fit ================================================ `MNLogit.fit(start_params=None, method='newton', maxiter=35, full_output=1, disp=1, callback=None, **kwargs)` Fit the model using maximum likelihood. The rest of the docstring is from statsmodels.base.model.LikelihoodModel.fit Fit method for likelihood based models | Parameters: | * **start\_params** (*array-like**,* *optional*) – Initial guess of the solution for the loglikelihood maximization. The default is an array of zeros. * **method** (*str**,* *optional*) – The `method` determines which solver from `scipy.optimize` is used, and it can be chosen from among the following strings: + ’newton’ for Newton-Raphson, ‘nm’ for Nelder-Mead + ’bfgs’ for Broyden-Fletcher-Goldfarb-Shanno (BFGS) + ’lbfgs’ for limited-memory BFGS with optional box constraints + ’powell’ for modified Powell’s method + ’cg’ for conjugate gradient + ’ncg’ for Newton-conjugate gradient + ’basinhopping’ for global basin-hopping solver + ’minimize’ for generic wrapper of scipy minimize (BFGS by default)The explicit arguments in `fit` are passed to the solver, with the exception of the basin-hopping solver. Each solver has several optional arguments that are not the same across solvers. See the notes section below (or scipy.optimize) for the available arguments and for the list of explicit arguments that the basin-hopping solver supports. * **maxiter** (*int**,* *optional*) – The maximum number of iterations to perform. * **full\_output** (*bool**,* *optional*) – Set to True to have all available output in the Results object’s mle\_retvals attribute. The output is dependent on the solver. See LikelihoodModelResults notes section for more information. * **disp** (*bool**,* *optional*) – Set to True to print convergence messages. * **fargs** (*tuple**,* *optional*) – Extra arguments passed to the likelihood function, i.e., loglike(x,\*args) * **callback** (*callable callback**(**xk**)**,* *optional*) – Called after each iteration, as callback(xk), where xk is the current parameter vector. * **retall** (*bool**,* *optional*) – Set to True to return list of solutions at each iteration. Available in Results object’s mle\_retvals attribute. * **skip\_hessian** (*bool**,* *optional*) – If False (default), then the negative inverse hessian is calculated after the optimization. If True, then the hessian will not be calculated. However, it will be available in methods that use the hessian in the optimization (currently only with `“newton”`). * **kwargs** (*keywords*) – All kwargs are passed to the chosen solver with one exception. The following keyword controls what happens after the fit: ``` warn_convergence : bool, optional If True, checks the model for the converged flag. If the converged flag is False, a ConvergenceWarning is issued. ``` | #### Notes The ‘basinhopping’ solver ignores `maxiter`, `retall`, `full_output` explicit arguments. Optional arguments for solvers (see returned Results.mle\_settings): ``` 'newton' tol : float Relative error in params acceptable for convergence. 'nm' -- Nelder Mead xtol : float Relative error in params acceptable for convergence ftol : float Relative error in loglike(params) acceptable for convergence maxfun : int Maximum number of function evaluations to make. 'bfgs' gtol : float Stop when norm of gradient is less than gtol. norm : float Order of norm (np.Inf is max, -np.Inf is min) epsilon If fprime is approximated, use this value for the step size. Only relevant if LikelihoodModel.score is None. 'lbfgs' m : int This many terms are used for the Hessian approximation. factr : float A stop condition that is a variant of relative error. pgtol : float A stop condition that uses the projected gradient. epsilon If fprime is approximated, use this value for the step size. Only relevant if LikelihoodModel.score is None. maxfun : int Maximum number of function evaluations to make. bounds : sequence (min, max) pairs for each element in x, defining the bounds on that parameter. Use None for one of min or max when there is no bound in that direction. 'cg' gtol : float Stop when norm of gradient is less than gtol. norm : float Order of norm (np.Inf is max, -np.Inf is min) epsilon : float If fprime is approximated, use this value for the step size. Can be scalar or vector. Only relevant if Likelihoodmodel.score is None. 'ncg' fhess_p : callable f'(x,*args) Function which computes the Hessian of f times an arbitrary vector, p. Should only be supplied if LikelihoodModel.hessian is None. avextol : float Stop when the average relative error in the minimizer falls below this amount. epsilon : float or ndarray If fhess is approximated, use this value for the step size. Only relevant if Likelihoodmodel.hessian is None. 'powell' xtol : float Line-search error tolerance ftol : float Relative error in loglike(params) for acceptable for convergence. maxfun : int Maximum number of function evaluations to make. start_direc : ndarray Initial direction set. 'basinhopping' niter : integer The number of basin hopping iterations. niter_success : integer Stop the run if the global minimum candidate remains the same for this number of iterations. T : float The "temperature" parameter for the accept or reject criterion. Higher "temperatures" mean that larger jumps in function value will be accepted. For best results `T` should be comparable to the separation (in function value) between local minima. stepsize : float Initial step size for use in the random displacement. interval : integer The interval for how often to update the `stepsize`. minimizer : dict Extra keyword arguments to be passed to the minimizer `scipy.optimize.minimize()`, for example 'method' - the minimization method (e.g. 'L-BFGS-B'), or 'tol' - the tolerance for termination. Other arguments are mapped from explicit argument of `fit`: - `args` <- `fargs` - `jac` <- `score` - `hess` <- `hess` 'minimize' min_method : str, optional Name of minimization method to use. Any method specific arguments can be passed directly. For a list of methods and their arguments, see documentation of `scipy.optimize.minimize`. If no method is specified, then BFGS is used. ``` statsmodels statsmodels.tsa.vector_ar.vecm.VECMResults.conf_int_det_coef_coint statsmodels.tsa.vector\_ar.vecm.VECMResults.conf\_int\_det\_coef\_coint ======================================================================= `VECMResults.conf_int_det_coef_coint(alpha=0.05)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/vecm.html#VECMResults.conf_int_det_coef_coint) statsmodels statsmodels.robust.norms.RamsayE statsmodels.robust.norms.RamsayE ================================ `class statsmodels.robust.norms.RamsayE(a=0.3)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/norms.html#RamsayE) Ramsay’s Ea for M estimation. | Parameters: | **a** (*float**,* *optional*) – The tuning constant for Ramsay’s Ea function. The default value is 0.3. | See also [`statsmodels.robust.norms.RobustNorm`](statsmodels.robust.norms.robustnorm#statsmodels.robust.norms.RobustNorm "statsmodels.robust.norms.RobustNorm") #### Methods | | | | --- | --- | | [`psi`](statsmodels.robust.norms.ramsaye.psi#statsmodels.robust.norms.RamsayE.psi "statsmodels.robust.norms.RamsayE.psi")(z) | The psi function for Ramsay’s Ea estimator | | [`psi_deriv`](statsmodels.robust.norms.ramsaye.psi_deriv#statsmodels.robust.norms.RamsayE.psi_deriv "statsmodels.robust.norms.RamsayE.psi_deriv")(z) | The derivative of Ramsay’s Ea psi function. | | [`rho`](statsmodels.robust.norms.ramsaye.rho#statsmodels.robust.norms.RamsayE.rho "statsmodels.robust.norms.RamsayE.rho")(z) | The robust criterion function for Ramsay’s Ea. | | [`weights`](statsmodels.robust.norms.ramsaye.weights#statsmodels.robust.norms.RamsayE.weights "statsmodels.robust.norms.RamsayE.weights")(z) | Ramsay’s Ea weighting function for the IRLS algorithm |
programming_docs
statsmodels statsmodels.tsa.statespace.sarimax.SARIMAXResults statsmodels.tsa.statespace.sarimax.SARIMAXResults ================================================= `class statsmodels.tsa.statespace.sarimax.SARIMAXResults(model, params, filter_results, cov_type='opg', **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/sarimax.html#SARIMAXResults) Class to hold results from fitting an SARIMAX model. | Parameters: | **model** (*SARIMAX instance*) – The fitted model instance | `specification` *dictionary* – Dictionary including all attributes from the SARIMAX model instance. `polynomial_ar` *array* – Array containing autoregressive lag polynomial coefficients, ordered from lowest degree to highest. Initialized with ones, unless a coefficient is constrained to be zero (in which case it is zero). `polynomial_ma` *array* – Array containing moving average lag polynomial coefficients, ordered from lowest degree to highest. Initialized with ones, unless a coefficient is constrained to be zero (in which case it is zero). `polynomial_seasonal_ar` *array* – Array containing seasonal autoregressive lag polynomial coefficients, ordered from lowest degree to highest. Initialized with ones, unless a coefficient is constrained to be zero (in which case it is zero). `polynomial_seasonal_ma` *array* – Array containing seasonal moving average lag polynomial coefficients, ordered from lowest degree to highest. Initialized with ones, unless a coefficient is constrained to be zero (in which case it is zero). `polynomial_trend` *array* – Array containing trend polynomial coefficients, ordered from lowest degree to highest. Initialized with ones, unless a coefficient is constrained to be zero (in which case it is zero). `model_orders` *list of int* – The orders of each of the polynomials in the model. `param_terms` *list of str* – List of parameters actually included in the model, in sorted order. See also [`statsmodels.tsa.statespace.kalman_filter.FilterResults`](statsmodels.tsa.statespace.kalman_filter.filterresults#statsmodels.tsa.statespace.kalman_filter.FilterResults "statsmodels.tsa.statespace.kalman_filter.FilterResults"), [`statsmodels.tsa.statespace.mlemodel.MLEResults`](statsmodels.tsa.statespace.mlemodel.mleresults#statsmodels.tsa.statespace.mlemodel.MLEResults "statsmodels.tsa.statespace.mlemodel.MLEResults") #### Methods | | | | --- | --- | | [`aic`](statsmodels.tsa.statespace.sarimax.sarimaxresults.aic#statsmodels.tsa.statespace.sarimax.SARIMAXResults.aic "statsmodels.tsa.statespace.sarimax.SARIMAXResults.aic")() | (float) Akaike Information Criterion | | [`arfreq`](statsmodels.tsa.statespace.sarimax.sarimaxresults.arfreq#statsmodels.tsa.statespace.sarimax.SARIMAXResults.arfreq "statsmodels.tsa.statespace.sarimax.SARIMAXResults.arfreq")() | (array) Frequency of the roots of the reduced form autoregressive lag polynomial | | [`arparams`](statsmodels.tsa.statespace.sarimax.sarimaxresults.arparams#statsmodels.tsa.statespace.sarimax.SARIMAXResults.arparams "statsmodels.tsa.statespace.sarimax.SARIMAXResults.arparams")() | (array) Autoregressive parameters actually estimated in the model. | | [`arroots`](statsmodels.tsa.statespace.sarimax.sarimaxresults.arroots#statsmodels.tsa.statespace.sarimax.SARIMAXResults.arroots "statsmodels.tsa.statespace.sarimax.SARIMAXResults.arroots")() | (array) Roots of the reduced form autoregressive lag polynomial | | [`bic`](statsmodels.tsa.statespace.sarimax.sarimaxresults.bic#statsmodels.tsa.statespace.sarimax.SARIMAXResults.bic "statsmodels.tsa.statespace.sarimax.SARIMAXResults.bic")() | (float) Bayes Information Criterion | | [`bse`](statsmodels.tsa.statespace.sarimax.sarimaxresults.bse#statsmodels.tsa.statespace.sarimax.SARIMAXResults.bse "statsmodels.tsa.statespace.sarimax.SARIMAXResults.bse")() | | | [`conf_int`](statsmodels.tsa.statespace.sarimax.sarimaxresults.conf_int#statsmodels.tsa.statespace.sarimax.SARIMAXResults.conf_int "statsmodels.tsa.statespace.sarimax.SARIMAXResults.conf_int")([alpha, cols, method]) | Returns the confidence interval of the fitted parameters. | | [`cov_params`](statsmodels.tsa.statespace.sarimax.sarimaxresults.cov_params#statsmodels.tsa.statespace.sarimax.SARIMAXResults.cov_params "statsmodels.tsa.statespace.sarimax.SARIMAXResults.cov_params")([r\_matrix, column, scale, cov\_p, …]) | Returns the variance/covariance matrix. | | [`cov_params_approx`](statsmodels.tsa.statespace.sarimax.sarimaxresults.cov_params_approx#statsmodels.tsa.statespace.sarimax.SARIMAXResults.cov_params_approx "statsmodels.tsa.statespace.sarimax.SARIMAXResults.cov_params_approx")() | (array) The variance / covariance matrix. | | [`cov_params_oim`](statsmodels.tsa.statespace.sarimax.sarimaxresults.cov_params_oim#statsmodels.tsa.statespace.sarimax.SARIMAXResults.cov_params_oim "statsmodels.tsa.statespace.sarimax.SARIMAXResults.cov_params_oim")() | (array) The variance / covariance matrix. | | [`cov_params_opg`](statsmodels.tsa.statespace.sarimax.sarimaxresults.cov_params_opg#statsmodels.tsa.statespace.sarimax.SARIMAXResults.cov_params_opg "statsmodels.tsa.statespace.sarimax.SARIMAXResults.cov_params_opg")() | (array) The variance / covariance matrix. | | [`cov_params_robust`](statsmodels.tsa.statespace.sarimax.sarimaxresults.cov_params_robust#statsmodels.tsa.statespace.sarimax.SARIMAXResults.cov_params_robust "statsmodels.tsa.statespace.sarimax.SARIMAXResults.cov_params_robust")() | (array) The QMLE variance / covariance matrix. | | [`cov_params_robust_approx`](statsmodels.tsa.statespace.sarimax.sarimaxresults.cov_params_robust_approx#statsmodels.tsa.statespace.sarimax.SARIMAXResults.cov_params_robust_approx "statsmodels.tsa.statespace.sarimax.SARIMAXResults.cov_params_robust_approx")() | (array) The QMLE variance / covariance matrix. | | [`cov_params_robust_oim`](statsmodels.tsa.statespace.sarimax.sarimaxresults.cov_params_robust_oim#statsmodels.tsa.statespace.sarimax.SARIMAXResults.cov_params_robust_oim "statsmodels.tsa.statespace.sarimax.SARIMAXResults.cov_params_robust_oim")() | (array) The QMLE variance / covariance matrix. | | [`f_test`](statsmodels.tsa.statespace.sarimax.sarimaxresults.f_test#statsmodels.tsa.statespace.sarimax.SARIMAXResults.f_test "statsmodels.tsa.statespace.sarimax.SARIMAXResults.f_test")(r\_matrix[, cov\_p, scale, invcov]) | Compute the F-test for a joint linear hypothesis. | | [`fittedvalues`](statsmodels.tsa.statespace.sarimax.sarimaxresults.fittedvalues#statsmodels.tsa.statespace.sarimax.SARIMAXResults.fittedvalues "statsmodels.tsa.statespace.sarimax.SARIMAXResults.fittedvalues")() | (array) The predicted values of the model. | | [`forecast`](statsmodels.tsa.statespace.sarimax.sarimaxresults.forecast#statsmodels.tsa.statespace.sarimax.SARIMAXResults.forecast "statsmodels.tsa.statespace.sarimax.SARIMAXResults.forecast")([steps]) | Out-of-sample forecasts | | [`get_forecast`](statsmodels.tsa.statespace.sarimax.sarimaxresults.get_forecast#statsmodels.tsa.statespace.sarimax.SARIMAXResults.get_forecast "statsmodels.tsa.statespace.sarimax.SARIMAXResults.get_forecast")([steps]) | Out-of-sample forecasts | | [`get_prediction`](statsmodels.tsa.statespace.sarimax.sarimaxresults.get_prediction#statsmodels.tsa.statespace.sarimax.SARIMAXResults.get_prediction "statsmodels.tsa.statespace.sarimax.SARIMAXResults.get_prediction")([start, end, dynamic, index, …]) | In-sample prediction and out-of-sample forecasting | | [`hqic`](statsmodels.tsa.statespace.sarimax.sarimaxresults.hqic#statsmodels.tsa.statespace.sarimax.SARIMAXResults.hqic "statsmodels.tsa.statespace.sarimax.SARIMAXResults.hqic")() | (float) Hannan-Quinn Information Criterion | | [`impulse_responses`](statsmodels.tsa.statespace.sarimax.sarimaxresults.impulse_responses#statsmodels.tsa.statespace.sarimax.SARIMAXResults.impulse_responses "statsmodels.tsa.statespace.sarimax.SARIMAXResults.impulse_responses")([steps, impulse, …]) | Impulse response function | | [`info_criteria`](statsmodels.tsa.statespace.sarimax.sarimaxresults.info_criteria#statsmodels.tsa.statespace.sarimax.SARIMAXResults.info_criteria "statsmodels.tsa.statespace.sarimax.SARIMAXResults.info_criteria")(criteria[, method]) | Information criteria | | [`initialize`](statsmodels.tsa.statespace.sarimax.sarimaxresults.initialize#statsmodels.tsa.statespace.sarimax.SARIMAXResults.initialize "statsmodels.tsa.statespace.sarimax.SARIMAXResults.initialize")(model, params, \*\*kwd) | | | [`llf`](statsmodels.tsa.statespace.sarimax.sarimaxresults.llf#statsmodels.tsa.statespace.sarimax.SARIMAXResults.llf "statsmodels.tsa.statespace.sarimax.SARIMAXResults.llf")() | (float) The value of the log-likelihood function evaluated at `params`. | | [`llf_obs`](statsmodels.tsa.statespace.sarimax.sarimaxresults.llf_obs#statsmodels.tsa.statespace.sarimax.SARIMAXResults.llf_obs "statsmodels.tsa.statespace.sarimax.SARIMAXResults.llf_obs")() | (float) The value of the log-likelihood function evaluated at `params`. | | [`load`](statsmodels.tsa.statespace.sarimax.sarimaxresults.load#statsmodels.tsa.statespace.sarimax.SARIMAXResults.load "statsmodels.tsa.statespace.sarimax.SARIMAXResults.load")(fname) | load a pickle, (class method) | | [`loglikelihood_burn`](statsmodels.tsa.statespace.sarimax.sarimaxresults.loglikelihood_burn#statsmodels.tsa.statespace.sarimax.SARIMAXResults.loglikelihood_burn "statsmodels.tsa.statespace.sarimax.SARIMAXResults.loglikelihood_burn")() | (float) The number of observations during which the likelihood is not evaluated. | | [`mafreq`](statsmodels.tsa.statespace.sarimax.sarimaxresults.mafreq#statsmodels.tsa.statespace.sarimax.SARIMAXResults.mafreq "statsmodels.tsa.statespace.sarimax.SARIMAXResults.mafreq")() | (array) Frequency of the roots of the reduced form moving average lag polynomial | | [`maparams`](statsmodels.tsa.statespace.sarimax.sarimaxresults.maparams#statsmodels.tsa.statespace.sarimax.SARIMAXResults.maparams "statsmodels.tsa.statespace.sarimax.SARIMAXResults.maparams")() | (array) Moving average parameters actually estimated in the model. | | [`maroots`](statsmodels.tsa.statespace.sarimax.sarimaxresults.maroots#statsmodels.tsa.statespace.sarimax.SARIMAXResults.maroots "statsmodels.tsa.statespace.sarimax.SARIMAXResults.maroots")() | (array) Roots of the reduced form moving average lag polynomial | | [`normalized_cov_params`](statsmodels.tsa.statespace.sarimax.sarimaxresults.normalized_cov_params#statsmodels.tsa.statespace.sarimax.SARIMAXResults.normalized_cov_params "statsmodels.tsa.statespace.sarimax.SARIMAXResults.normalized_cov_params")() | | | [`plot_diagnostics`](statsmodels.tsa.statespace.sarimax.sarimaxresults.plot_diagnostics#statsmodels.tsa.statespace.sarimax.SARIMAXResults.plot_diagnostics "statsmodels.tsa.statespace.sarimax.SARIMAXResults.plot_diagnostics")([variable, lags, fig, figsize]) | Diagnostic plots for standardized residuals of one endogenous variable | | [`predict`](statsmodels.tsa.statespace.sarimax.sarimaxresults.predict#statsmodels.tsa.statespace.sarimax.SARIMAXResults.predict "statsmodels.tsa.statespace.sarimax.SARIMAXResults.predict")([start, end, dynamic]) | In-sample prediction and out-of-sample forecasting | | [`pvalues`](statsmodels.tsa.statespace.sarimax.sarimaxresults.pvalues#statsmodels.tsa.statespace.sarimax.SARIMAXResults.pvalues "statsmodels.tsa.statespace.sarimax.SARIMAXResults.pvalues")() | (array) The p-values associated with the z-statistics of the coefficients. | | [`remove_data`](statsmodels.tsa.statespace.sarimax.sarimaxresults.remove_data#statsmodels.tsa.statespace.sarimax.SARIMAXResults.remove_data "statsmodels.tsa.statespace.sarimax.SARIMAXResults.remove_data")() | remove data arrays, all nobs arrays from result and model | | [`resid`](statsmodels.tsa.statespace.sarimax.sarimaxresults.resid#statsmodels.tsa.statespace.sarimax.SARIMAXResults.resid "statsmodels.tsa.statespace.sarimax.SARIMAXResults.resid")() | (array) The model residuals. | | [`save`](statsmodels.tsa.statespace.sarimax.sarimaxresults.save#statsmodels.tsa.statespace.sarimax.SARIMAXResults.save "statsmodels.tsa.statespace.sarimax.SARIMAXResults.save")(fname[, remove\_data]) | save a pickle of this instance | | [`seasonalarparams`](statsmodels.tsa.statespace.sarimax.sarimaxresults.seasonalarparams#statsmodels.tsa.statespace.sarimax.SARIMAXResults.seasonalarparams "statsmodels.tsa.statespace.sarimax.SARIMAXResults.seasonalarparams")() | (array) Seasonal autoregressive parameters actually estimated in the model. | | [`seasonalmaparams`](statsmodels.tsa.statespace.sarimax.sarimaxresults.seasonalmaparams#statsmodels.tsa.statespace.sarimax.SARIMAXResults.seasonalmaparams "statsmodels.tsa.statespace.sarimax.SARIMAXResults.seasonalmaparams")() | (array) Seasonal moving average parameters actually estimated in the model. | | [`simulate`](statsmodels.tsa.statespace.sarimax.sarimaxresults.simulate#statsmodels.tsa.statespace.sarimax.SARIMAXResults.simulate "statsmodels.tsa.statespace.sarimax.SARIMAXResults.simulate")(nsimulations[, measurement\_shocks, …]) | Simulate a new time series following the state space model | | [`summary`](statsmodels.tsa.statespace.sarimax.sarimaxresults.summary#statsmodels.tsa.statespace.sarimax.SARIMAXResults.summary "statsmodels.tsa.statespace.sarimax.SARIMAXResults.summary")([alpha, start]) | Summarize the Model | | [`t_test`](statsmodels.tsa.statespace.sarimax.sarimaxresults.t_test#statsmodels.tsa.statespace.sarimax.SARIMAXResults.t_test "statsmodels.tsa.statespace.sarimax.SARIMAXResults.t_test")(r\_matrix[, cov\_p, scale, use\_t]) | Compute a t-test for a each linear hypothesis of the form Rb = q | | [`t_test_pairwise`](statsmodels.tsa.statespace.sarimax.sarimaxresults.t_test_pairwise#statsmodels.tsa.statespace.sarimax.SARIMAXResults.t_test_pairwise "statsmodels.tsa.statespace.sarimax.SARIMAXResults.t_test_pairwise")(term\_name[, method, alpha, …]) | perform pairwise t\_test with multiple testing corrected p-values | | [`test_heteroskedasticity`](statsmodels.tsa.statespace.sarimax.sarimaxresults.test_heteroskedasticity#statsmodels.tsa.statespace.sarimax.SARIMAXResults.test_heteroskedasticity "statsmodels.tsa.statespace.sarimax.SARIMAXResults.test_heteroskedasticity")(method[, …]) | Test for heteroskedasticity of standardized residuals | | [`test_normality`](statsmodels.tsa.statespace.sarimax.sarimaxresults.test_normality#statsmodels.tsa.statespace.sarimax.SARIMAXResults.test_normality "statsmodels.tsa.statespace.sarimax.SARIMAXResults.test_normality")(method) | Test for normality of standardized residuals. | | [`test_serial_correlation`](statsmodels.tsa.statespace.sarimax.sarimaxresults.test_serial_correlation#statsmodels.tsa.statespace.sarimax.SARIMAXResults.test_serial_correlation "statsmodels.tsa.statespace.sarimax.SARIMAXResults.test_serial_correlation")(method[, lags]) | Ljung-box test for no serial correlation of standardized residuals | | [`tvalues`](statsmodels.tsa.statespace.sarimax.sarimaxresults.tvalues#statsmodels.tsa.statespace.sarimax.SARIMAXResults.tvalues "statsmodels.tsa.statespace.sarimax.SARIMAXResults.tvalues")() | Return the t-statistic for a given parameter estimate. | | [`wald_test`](statsmodels.tsa.statespace.sarimax.sarimaxresults.wald_test#statsmodels.tsa.statespace.sarimax.SARIMAXResults.wald_test "statsmodels.tsa.statespace.sarimax.SARIMAXResults.wald_test")(r\_matrix[, cov\_p, scale, invcov, …]) | Compute a Wald-test for a joint linear hypothesis. | | [`wald_test_terms`](statsmodels.tsa.statespace.sarimax.sarimaxresults.wald_test_terms#statsmodels.tsa.statespace.sarimax.SARIMAXResults.wald_test_terms "statsmodels.tsa.statespace.sarimax.SARIMAXResults.wald_test_terms")([skip\_single, …]) | Compute a sequence of Wald tests for terms over multiple columns | | [`zvalues`](statsmodels.tsa.statespace.sarimax.sarimaxresults.zvalues#statsmodels.tsa.statespace.sarimax.SARIMAXResults.zvalues "statsmodels.tsa.statespace.sarimax.SARIMAXResults.zvalues")() | (array) The z-statistics for the coefficients. | #### Attributes | | | | --- | --- | | `use_t` | | statsmodels statsmodels.discrete.discrete_model.GeneralizedPoissonResults.normalized_cov_params statsmodels.discrete.discrete\_model.GeneralizedPoissonResults.normalized\_cov\_params ====================================================================================== `GeneralizedPoissonResults.normalized_cov_params()` statsmodels statsmodels.discrete.discrete_model.Logit.loglikeobs statsmodels.discrete.discrete\_model.Logit.loglikeobs ===================================================== `Logit.loglikeobs(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#Logit.loglikeobs) Log-likelihood of logit model for each observation. | Parameters: | **params** (*array-like*) – The parameters of the logit model. | | Returns: | **loglike** – The log likelihood for each observation of the model evaluated at `params`. See Notes | | Return type: | ndarray | #### Notes \[\ln L=\sum\_{i}\ln\Lambda\left(q\_{i}x\_{i}^{\prime}\beta\right)\] for observations \(i=1,...,n\) where \(q=2y-1\). This simplification comes from the fact that the logistic distribution is symmetric. statsmodels statsmodels.tsa.statespace.sarimax.SARIMAX.initialize_known statsmodels.tsa.statespace.sarimax.SARIMAX.initialize\_known ============================================================ `SARIMAX.initialize_known(initial_state, initial_state_cov)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/sarimax.html#SARIMAX.initialize_known) Initialize the statespace model with known distribution for initial state. These values are assumed to be known with certainty or else filled with parameters during, for example, maximum likelihood estimation. | Parameters: | * **initial\_state** (*array\_like*) – Known mean of the initial state vector. * **initial\_state\_cov** (*array\_like*) – Known covariance matrix of the initial state vector. | statsmodels statsmodels.multivariate.factor.FactorResults.summary statsmodels.multivariate.factor.FactorResults.summary ===================================================== `FactorResults.summary()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/multivariate/factor.html#FactorResults.summary) statsmodels statsmodels.discrete.discrete_model.ProbitResults.resid_generalized statsmodels.discrete.discrete\_model.ProbitResults.resid\_generalized ===================================================================== `ProbitResults.resid_generalized()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#ProbitResults.resid_generalized) Generalized residuals #### Notes The generalized residuals for the Probit model are defined \[y\frac{\phi(X\beta)}{\Phi(X\beta)}-(1-y)\frac{\phi(X\beta)}{1-\Phi(X\beta)}\] statsmodels statsmodels.tsa.statespace.structural.UnobservedComponentsResults.info_criteria statsmodels.tsa.statespace.structural.UnobservedComponentsResults.info\_criteria ================================================================================ `UnobservedComponentsResults.info_criteria(criteria, method='standard')` Information criteria | Parameters: | * **criteria** (*{'aic'**,* *'bic'**,* *'hqic'}*) – The information criteria to compute. * **method** (*{'standard'**,* *'lutkepohl'}*) – The method for information criteria computation. Default is ‘standard’ method; ‘lutkepohl’ computes the information criteria as in Lütkepohl (2007). See Notes for formulas. | #### Notes The `‘standard’` formulas are: \[\begin{split}AIC & = -2 \log L(Y\_n | \hat \psi) + 2 k \\ BIC & = -2 \log L(Y\_n | \hat \psi) + k \log n \\ HQIC & = -2 \log L(Y\_n | \hat \psi) + 2 k \log \log n \\\end{split}\] where \(\hat \psi\) are the maximum likelihood estimates of the parameters, \(n\) is the number of observations, and `k` is the number of estimated parameters. Note that the `‘standard’` formulas are returned from the `aic`, `bic`, and `hqic` results attributes. The `‘lutkepohl’` formuals are (Lütkepohl, 2010): \[\begin{split}AIC\_L & = \log | Q | + \frac{2 k}{n} \\ BIC\_L & = \log | Q | + \frac{k \log n}{n} \\ HQIC\_L & = \log | Q | + \frac{2 k \log \log n}{n} \\\end{split}\] where \(Q\) is the state covariance matrix. Note that the Lütkepohl definitions do not apply to all state space models, and should be used with care outside of SARIMAX and VARMAX models. #### References | | | | --- | --- | | [\*] | Lütkepohl, Helmut. 2007. *New Introduction to Multiple Time* *Series Analysis.* Berlin: Springer. |
programming_docs
statsmodels statsmodels.miscmodels.count.PoissonZiGMLE.hessian_factor statsmodels.miscmodels.count.PoissonZiGMLE.hessian\_factor ========================================================== `PoissonZiGMLE.hessian_factor(params, scale=None, observed=True)` Weights for calculating Hessian | Parameters: | * **params** (*ndarray*) – parameter at which Hessian is evaluated * **scale** (*None* *or* *float*) – If scale is None, then the default scale will be calculated. Default scale is defined by `self.scaletype` and set in fit. If scale is not None, then it is used as a fixed scale. * **observed** (*bool*) – If True, then the observed Hessian is returned. If false then the expected information matrix is returned. | | Returns: | **hessian\_factor** – A 1d weight vector used in the calculation of the Hessian. The hessian is obtained by `(exog.T * hessian_factor).dot(exog)` | | Return type: | ndarray, 1d | statsmodels statsmodels.stats.diagnostic.HetGoldfeldQuandt.run statsmodels.stats.diagnostic.HetGoldfeldQuandt.run ================================================== `HetGoldfeldQuandt.run(y, x, idx=None, split=None, drop=None, alternative='increasing', attach=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/diagnostic.html#HetGoldfeldQuandt.run) see class docstring statsmodels statsmodels.sandbox.regression.gmm.NonlinearIVGMM.jac_error statsmodels.sandbox.regression.gmm.NonlinearIVGMM.jac\_error ============================================================ `NonlinearIVGMM.jac_error(params, weights, args=None, centered=True, epsilon=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#NonlinearIVGMM.jac_error) statsmodels statsmodels.discrete.discrete_model.MNLogit.hessian statsmodels.discrete.discrete\_model.MNLogit.hessian ==================================================== `MNLogit.hessian(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#MNLogit.hessian) Multinomial logit Hessian matrix of the log-likelihood | Parameters: | **params** (*array-like*) – The parameters of the model | | Returns: | **hess** – The Hessian, second derivative of loglikelihood function with respect to the flattened parameters, evaluated at `params` | | Return type: | ndarray, (J\*K, J\*K) | #### Notes \[\frac{\partial^{2}\ln L}{\partial\beta\_{j}\partial\beta\_{l}}=-\sum\_{i=1}^{n}\frac{\exp\left(\beta\_{j}^{\prime}x\_{i}\right)}{\sum\_{k=0}^{J}\exp\left(\beta\_{k}^{\prime}x\_{i}\right)}\left[\boldsymbol{1}\left(j=l\right)-\frac{\exp\left(\beta\_{l}^{\prime}x\_{i}\right)}{\sum\_{k=0}^{J}\exp\left(\beta\_{k}^{\prime}x\_{i}\right)}\right]x\_{i}x\_{l}^{\prime}\] where \(\boldsymbol{1}\left(j=l\right)\) equals 1 if `j` = `l` and 0 otherwise. The actual Hessian matrix has J\*\*2 \* K x K elements. Our Hessian is reshaped to be square (J\*K, J\*K) so that the solvers can use it. This implementation does not take advantage of the symmetry of the Hessian and could probably be refactored for speed. statsmodels statsmodels.genmod.bayes_mixed_glm.BayesMixedGLMResults.random_effects statsmodels.genmod.bayes\_mixed\_glm.BayesMixedGLMResults.random\_effects ========================================================================= `BayesMixedGLMResults.random_effects(term=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/bayes_mixed_glm.html#BayesMixedGLMResults.random_effects) Posterior mean and standard deviation of random effects. | Parameters: | **term** (*int* *or* *None*) – If None, results for all random effects are returned. If an integer, returns results for a given set of random effects. The value of `term` refers to an element of the `ident` vector, or to a position in the `vc_formulas` list. | | Returns: | * *Data frame of posterior means and posterior standard* * *deviations of random effects.* | statsmodels statsmodels.tsa.filters.hp_filter.hpfilter statsmodels.tsa.filters.hp\_filter.hpfilter =========================================== `statsmodels.tsa.filters.hp_filter.hpfilter(X, lamb=1600)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/filters/hp_filter.html#hpfilter) Hodrick-Prescott filter | Parameters: | * **X** (*array-like*) – The 1d ndarray timeseries to filter of length (nobs,) or (nobs,1) * **lamb** (*float*) – The Hodrick-Prescott smoothing parameter. A value of 1600 is suggested for quarterly data. Ravn and Uhlig suggest using a value of 6.25 (1600/4\*\*4) for annual data and 129600 (1600\*3\*\*4) for monthly data. | | Returns: | * **cycle** (*array*) – The estimated cycle in the data given lamb. * **trend** (*array*) – The estimated trend in the data given lamb. | #### Examples ``` >>> import statsmodels.api as sm >>> import pandas as pd >>> dta = sm.datasets.macrodata.load_pandas().data >>> index = pd.DatetimeIndex(start='1959Q1', end='2009Q4', freq='Q') >>> dta.set_index(index, inplace=True) ``` ``` >>> cycle, trend = sm.tsa.filters.hpfilter(dta.realgdp, 1600) >>> gdp_decomp = dta[['realgdp']] >>> gdp_decomp["cycle"] = cycle >>> gdp_decomp["trend"] = trend ``` ``` >>> import matplotlib.pyplot as plt >>> fig, ax = plt.subplots() >>> gdp_decomp[["realgdp", "trend"]]["2000-03-31":].plot(ax=ax, ... fontsize=16); >>> plt.show() ``` ([Source code](../plots/hpf_plot.py), [png](../plots/hpf_plot.png), [hires.png](../plots/hpf_plot.hires.png), [pdf](../plots/hpf_plot.pdf)) #### Notes The HP filter removes a smooth trend, `T`, from the data `X`. by solving min sum((X[t] - T[t])\*\*2 + lamb\*((T[t+1] - T[t]) - (T[t] - T[t-1]))\*\*2) T t Here we implemented the HP filter as a ridge-regression rule using scipy.sparse. In this sense, the solution can be written as T = inv(I - lamb\*K’K)X where I is a nobs x nobs identity matrix, and K is a (nobs-2) x nobs matrix such that K[i,j] = 1 if i == j or i == j + 2 K[i,j] = -2 if i == j + 1 K[i,j] = 0 otherwise See also [`statsmodels.tsa.filters.bk_filter.bkfilter`](statsmodels.tsa.filters.bk_filter.bkfilter#statsmodels.tsa.filters.bk_filter.bkfilter "statsmodels.tsa.filters.bk_filter.bkfilter"), [`statsmodels.tsa.filters.cf_filter.cffilter`](statsmodels.tsa.filters.cf_filter.cffilter#statsmodels.tsa.filters.cf_filter.cffilter "statsmodels.tsa.filters.cf_filter.cffilter"), [`statsmodels.tsa.seasonal.seasonal_decompose`](statsmodels.tsa.seasonal.seasonal_decompose#statsmodels.tsa.seasonal.seasonal_decompose "statsmodels.tsa.seasonal.seasonal_decompose") #### References Hodrick, R.J, and E. C. Prescott. 1980. “Postwar U.S. Business Cycles: An Empricial Investigation.” `Carnegie Mellon University discussion paper no. 451`. Ravn, M.O and H. Uhlig. 2002. “Notes On Adjusted the Hodrick-Prescott Filter for the Frequency of Observations.” `The Review of Economics and Statistics`, 84(2), 371-80. statsmodels statsmodels.tsa.vector_ar.var_model.VARProcess.acorr statsmodels.tsa.vector\_ar.var\_model.VARProcess.acorr ====================================================== `VARProcess.acorr(nlags=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/var_model.html#VARProcess.acorr) Compute theoretical autocorrelation function | Returns: | **acorr** | | Return type: | ndarray (p x k x k) | statsmodels statsmodels.genmod.families.links.identity.inverse statsmodels.genmod.families.links.identity.inverse ================================================== `identity.inverse(z)` Inverse of the power transform link function | Parameters: | **z** (*array-like*) – Value of the transformed mean parameters at `p` | | Returns: | **`p`** – Mean parameters | | Return type: | array | #### Notes g^(-1)(z`) = `z`**(1/`power`) statsmodels statsmodels.regression.mixed_linear_model.MixedLM.score_full statsmodels.regression.mixed\_linear\_model.MixedLM.score\_full =============================================================== `MixedLM.score_full(params, calc_fe)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/mixed_linear_model.html#MixedLM.score_full) Returns the score with respect to untransformed parameters. Calculates the score vector for the profiled log-likelihood of the mixed effects model with respect to the parameterization in which the random effects covariance matrix is represented in its full form (not using the Cholesky factor). | Parameters: | * **params** (*MixedLMParams* *or* *array-like*) – The parameter at which the score function is evaluated. If array-like, must contain the packed random effects parameters (cov\_re and vcomp) without fe\_params. * **calc\_fe** (*boolean*) – If True, calculate the score vector for the fixed effects parameters. If False, this vector is not calculated, and a vector of zeros is returned in its place. | | Returns: | * **score\_fe** (*array-like*) – The score vector with respect to the fixed effects parameters. * **score\_re** (*array-like*) – The score vector with respect to the random effects parameters (excluding variance components parameters). * **score\_vc** (*array-like*) – The score vector with respect to variance components parameters. | #### Notes `score_re` is taken with respect to the parameterization in which `cov_re` is represented through its lower triangle (without taking the Cholesky square root). statsmodels statsmodels.genmod.families.links.Log statsmodels.genmod.families.links.Log ===================================== `class statsmodels.genmod.families.links.Log` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/links.html#Log) The log transform #### Notes call and derivative call a private method \_clean to trim the data by machine epsilon so that p is in (0,1). log is an alias of Log. #### Methods | | | | --- | --- | | [`deriv`](statsmodels.genmod.families.links.log.deriv#statsmodels.genmod.families.links.Log.deriv "statsmodels.genmod.families.links.Log.deriv")(p) | Derivative of log transform link function | | [`deriv2`](statsmodels.genmod.families.links.log.deriv2#statsmodels.genmod.families.links.Log.deriv2 "statsmodels.genmod.families.links.Log.deriv2")(p) | Second derivative of the log transform link function | | [`inverse`](statsmodels.genmod.families.links.log.inverse#statsmodels.genmod.families.links.Log.inverse "statsmodels.genmod.families.links.Log.inverse")(z) | Inverse of log transform link function | | [`inverse_deriv`](statsmodels.genmod.families.links.log.inverse_deriv#statsmodels.genmod.families.links.Log.inverse_deriv "statsmodels.genmod.families.links.Log.inverse_deriv")(z) | Derivative of the inverse of the log transform link function | statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.spec_hausman statsmodels.sandbox.regression.gmm.IVRegressionResults.spec\_hausman ==================================================================== `IVRegressionResults.spec_hausman(dof=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#IVRegressionResults.spec_hausman) Hausman’s specification test See also [`spec_hausman`](#statsmodels.sandbox.regression.gmm.IVRegressionResults.spec_hausman "statsmodels.sandbox.regression.gmm.IVRegressionResults.spec_hausman") generic function for Hausman’s specification test statsmodels statsmodels.sandbox.regression.gmm.IVGMMResults.load statsmodels.sandbox.regression.gmm.IVGMMResults.load ==================================================== `classmethod IVGMMResults.load(fname)` load a pickle, (class method) | Parameters: | **fname** (*string* *or* *filehandle*) – fname can be a string to a file path or filename, or a filehandle. | | Returns: | | | Return type: | unpickled instance | statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.plot_diagnostics statsmodels.tsa.statespace.dynamic\_factor.DynamicFactorResults.plot\_diagnostics ================================================================================= `DynamicFactorResults.plot_diagnostics(variable=0, lags=10, fig=None, figsize=None)` Diagnostic plots for standardized residuals of one endogenous variable | Parameters: | * **variable** (*integer**,* *optional*) – Index of the endogenous variable for which the diagnostic plots should be created. Default is 0. * **lags** (*integer**,* *optional*) – Number of lags to include in the correlogram. Default is 10. * **fig** (*Matplotlib Figure instance**,* *optional*) – If given, subplots are created in this figure instead of in a new figure. Note that the 2x2 grid will be created in the provided figure using `fig.add_subplot()`. * **figsize** (*tuple**,* *optional*) – If a figure is created, this argument allows specifying a size. The tuple is (width, height). | #### Notes Produces a 2x2 plot grid with the following plots (ordered clockwise from top left): 1. Standardized residuals over time 2. Histogram plus estimated density of standardized residulas, along with a Normal(0,1) density plotted for reference. 3. Normal Q-Q plot, with Normal reference line. 4. Correlogram See also [`statsmodels.graphics.gofplots.qqplot`](statsmodels.graphics.gofplots.qqplot#statsmodels.graphics.gofplots.qqplot "statsmodels.graphics.gofplots.qqplot"), [`statsmodels.graphics.tsaplots.plot_acf`](statsmodels.graphics.tsaplots.plot_acf#statsmodels.graphics.tsaplots.plot_acf "statsmodels.graphics.tsaplots.plot_acf") statsmodels statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression.filter statsmodels.tsa.regime\_switching.markov\_autoregression.MarkovAutoregression.filter ==================================================================================== `MarkovAutoregression.filter(params, transformed=True, cov_type=None, cov_kwds=None, return_raw=False, results_class=None, results_wrapper_class=None)` Apply the Hamilton filter | Parameters: | * **params** (*array\_like*) – Array of parameters at which to perform filtering. * **transformed** (*boolean**,* *optional*) – Whether or not `params` is already transformed. Default is True. * **cov\_type** (*str**,* *optional*) – See `fit` for a description of covariance matrix types for results object. * **cov\_kwds** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)") *or* *None**,* *optional*) – See `fit` for a description of required keywords for alternative covariance estimators * **return\_raw** (*boolean**,**optional*) – Whether or not to return only the raw Hamilton filter output or a full results object. Default is to return a full results object. * **results\_class** (*type**,* *optional*) – A results class to instantiate rather than `MarkovSwitchingResults`. Usually only used internally by subclasses. * **results\_wrapper\_class** (*type**,* *optional*) – A results wrapper class to instantiate rather than `MarkovSwitchingResults`. Usually only used internally by subclasses. | | Returns: | | | Return type: | MarkovSwitchingResults | statsmodels statsmodels.tsa.statespace.varmax.VARMAX.initialize_stationary statsmodels.tsa.statespace.varmax.VARMAX.initialize\_stationary =============================================================== `VARMAX.initialize_stationary()` statsmodels statsmodels.tsa.arima_process.ArmaProcess.arma2ar statsmodels.tsa.arima\_process.ArmaProcess.arma2ar ================================================== `ArmaProcess.arma2ar(lags=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_process.html#ArmaProcess.arma2ar) statsmodels statsmodels.stats.multicomp.pairwise_tukeyhsd statsmodels.stats.multicomp.pairwise\_tukeyhsd ============================================== `statsmodels.stats.multicomp.pairwise_tukeyhsd(endog, groups, alpha=0.05)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/multicomp.html#pairwise_tukeyhsd) calculate all pairwise comparisons with TukeyHSD confidence intervals this is just a wrapper around tukeyhsd method of MultiComparison | Parameters: | * **endog** (*ndarray**,* *float**,* *1d*) – response variable * **groups** (*ndarray**,* *1d*) – array with groups, can be string or integers * **alpha** (*float*) – significance level for the test | | Returns: | **results** – A results class containing relevant data and some post-hoc calculations | | Return type: | TukeyHSDResults instance | See also `MultiComparison`, `tukeyhsd`, [`statsmodels.sandbox.stats.multicomp.TukeyHSDResults`](statsmodels.sandbox.stats.multicomp.tukeyhsdresults#statsmodels.sandbox.stats.multicomp.TukeyHSDResults "statsmodels.sandbox.stats.multicomp.TukeyHSDResults") statsmodels statsmodels.tsa.vector_ar.irf.IRAnalysis.cum_effect_cov statsmodels.tsa.vector\_ar.irf.IRAnalysis.cum\_effect\_cov ========================================================== `IRAnalysis.cum_effect_cov(orth=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/irf.html#IRAnalysis.cum_effect_cov) Compute asymptotic standard errors for cumulative impulse response coefficients | Parameters: | **orth** (*boolean*) – | #### Notes eq. 3.7.7 (non-orth), 3.7.10 (orth) statsmodels statsmodels.tsa.statespace.structural.UnobservedComponentsResults.wald_test statsmodels.tsa.statespace.structural.UnobservedComponentsResults.wald\_test ============================================================================ `UnobservedComponentsResults.wald_test(r_matrix, cov_p=None, scale=1.0, invcov=None, use_f=None)` Compute a Wald-test for a joint linear hypothesis. | Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) – + array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length p row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – Default is 1.0 for no scaling. * **invcov** (*array-like**,* *optional*) – A q x q array to specify an inverse covariance matrix based on a restrictions matrix. * **use\_f** (*bool*) – If True, then the F-distribution is used. If False, then the asymptotic distribution, chisquare is used. If use\_f is None, then the F distribution is used if the model specifies that use\_t is True. The test statistic is proportionally adjusted for the distribution by the number of constraints in the hypothesis. | | Returns: | **res** – The results for the test are attributes of this results instance. | | Return type: | ContrastResults instance | See also [`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`f_test`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.f_test#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.f_test "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.f_test"), [`t_test`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.t_test#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.t_test "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") #### Notes The matrix `r_matrix` is assumed to be non-singular. More precisely, r\_matrix (pX pX.T) r\_matrix.T is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full.
programming_docs
statsmodels statsmodels.stats.stattools.omni_normtest statsmodels.stats.stattools.omni\_normtest ========================================== `statsmodels.stats.stattools.omni_normtest(resids, axis=0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/stattools.html#omni_normtest) Omnibus test for normality | Parameters: | * **resid** (*array-like*) – * **axis** (*int**,* *optional*) – Default is 0 | | Returns: | | | Return type: | Chi^2 score, two-tail probability | statsmodels statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialResults.summary2 statsmodels.discrete.count\_model.ZeroInflatedNegativeBinomialResults.summary2 ============================================================================== `ZeroInflatedNegativeBinomialResults.summary2(yname=None, xname=None, title=None, alpha=0.05, float_format='%.4f')` Experimental function to summarize regression results | Parameters: | * **xname** (*List of strings of length equal to the number of parameters*) – Names of the independent variables (optional) * **yname** (*string*) – Name of the dependent variable (optional) * **title** (*string**,* *optional*) – Title for the top table. If not None, then this replaces the default title * **alpha** (*float*) – significance level for the confidence intervals * **float\_format** (*string*) – print format for floats in parameters summary | | Returns: | **smry** – this holds the summary tables and text, which can be printed or converted to various output formats. | | Return type: | Summary instance | See also [`statsmodels.iolib.summary.Summary`](statsmodels.iolib.summary.summary#statsmodels.iolib.summary.Summary "statsmodels.iolib.summary.Summary") class to hold summary results statsmodels statsmodels.graphics.regressionplots.influence_plot statsmodels.graphics.regressionplots.influence\_plot ==================================================== `statsmodels.graphics.regressionplots.influence_plot(results, external=True, alpha=0.05, criterion='cooks', size=48, plot_alpha=0.75, ax=None, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/graphics/regressionplots.html#influence_plot) Plot of influence in regression. Plots studentized resids vs. leverage. | Parameters: | * **results** (*results instance*) – A fitted model. * **external** (*bool*) – Whether to use externally or internally studentized residuals. It is recommended to leave external as True. * **alpha** (*float*) – The alpha value to identify large studentized residuals. Large means abs(resid\_studentized) > t.ppf(1-alpha/2, dof=results.df\_resid) * **criterion** (*str {'DFFITS'**,* *'Cooks'}*) – Which criterion to base the size of the points on. Options are DFFITS or Cook’s D. * **size** (*float*) – The range of `criterion` is mapped to 10\*\*2 - size\*\*2 in points. * **plot\_alpha** (*float*) – The `alpha` of the plotted points. * **ax** (*matplotlib Axes instance*) – An instance of a matplotlib Axes. | | Returns: | **fig** – The matplotlib figure that contains the Axes. | | Return type: | matplotlib figure | #### Notes Row labels for the observations in which the leverage, measured by the diagonal of the hat matrix, is high or the residuals are large, as the combination of large residuals and a high influence value indicates an influence point. The value of large residuals can be controlled using the `alpha` parameter. Large leverage points are identified as hat\_i > 2 \* (df\_model + 1)/nobs. statsmodels statsmodels.genmod.generalized_estimating_equations.GEEResults.normalized_cov_params statsmodels.genmod.generalized\_estimating\_equations.GEEResults.normalized\_cov\_params ======================================================================================== `GEEResults.normalized_cov_params()` statsmodels statsmodels.discrete.count_model.ZeroInflatedPoisson.cdf statsmodels.discrete.count\_model.ZeroInflatedPoisson.cdf ========================================================= `ZeroInflatedPoisson.cdf(X)` The cumulative distribution function of the model. statsmodels statsmodels.tsa.arima_model.ARMA statsmodels.tsa.arima\_model.ARMA ================================= `class statsmodels.tsa.arima_model.ARMA(endog, order, exog=None, dates=None, freq=None, missing='none')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_model.html#ARMA) Autoregressive Moving Average ARMA(p,q) Model | Parameters: | * **endog** (*array-like*) – The endogenous variable. * **order** (*iterable*) – The (p,q) order of the model for the number of AR parameters, differences, and MA parameters to use. * **exog** (*array-like**,* *optional*) – An optional array of exogenous variables. This should *not* include a constant or trend. You can specify this in the `fit` method. * **dates** (*array-like of datetime**,* *optional*) – An array-like object of datetime objects. If a pandas object is given for endog or exog, it is assumed to have a DateIndex. * **freq** (*str**,* *optional*) – The frequency of the time-series. A Pandas offset or ‘B’, ‘D’, ‘W’, ‘M’, ‘A’, or ‘Q’. This is optional if dates are given. | #### Notes If exogenous variables are given, then the model that is fit is \[\phi(L)(y\_t - X\_t\beta) = \theta(L)\epsilon\_t\] where \(\phi\) and \(\theta\) are polynomials in the lag operator, \(L\). This is the regression model with ARMA errors, or ARMAX model. This specification is used, whether or not the model is fit using conditional sum of square or maximum-likelihood, using the `method` argument in [`statsmodels.tsa.arima_model.ARMA.fit`](statsmodels.tsa.arima_model.arma.fit#statsmodels.tsa.arima_model.ARMA.fit "statsmodels.tsa.arima_model.ARMA.fit"). Therefore, for now, `css` and `mle` refer to estimation methods only. This may change for the case of the `css` model in future versions. #### Methods | | | | --- | --- | | [`fit`](statsmodels.tsa.arima_model.arma.fit#statsmodels.tsa.arima_model.ARMA.fit "statsmodels.tsa.arima_model.ARMA.fit")([start\_params, trend, method, …]) | Fits ARMA(p,q) model using exact maximum likelihood via Kalman filter. | | [`from_formula`](statsmodels.tsa.arima_model.arma.from_formula#statsmodels.tsa.arima_model.ARMA.from_formula "statsmodels.tsa.arima_model.ARMA.from_formula")(formula, data[, subset, drop\_cols]) | Create a Model from a formula and dataframe. | | [`geterrors`](statsmodels.tsa.arima_model.arma.geterrors#statsmodels.tsa.arima_model.ARMA.geterrors "statsmodels.tsa.arima_model.ARMA.geterrors")(params) | Get the errors of the ARMA process. | | [`hessian`](statsmodels.tsa.arima_model.arma.hessian#statsmodels.tsa.arima_model.ARMA.hessian "statsmodels.tsa.arima_model.ARMA.hessian")(params) | Compute the Hessian at params, | | [`information`](statsmodels.tsa.arima_model.arma.information#statsmodels.tsa.arima_model.ARMA.information "statsmodels.tsa.arima_model.ARMA.information")(params) | Fisher information matrix of model | | [`initialize`](statsmodels.tsa.arima_model.arma.initialize#statsmodels.tsa.arima_model.ARMA.initialize "statsmodels.tsa.arima_model.ARMA.initialize")() | Initialize (possibly re-initialize) a Model instance. | | [`loglike`](statsmodels.tsa.arima_model.arma.loglike#statsmodels.tsa.arima_model.ARMA.loglike "statsmodels.tsa.arima_model.ARMA.loglike")(params[, set\_sigma2]) | Compute the log-likelihood for ARMA(p,q) model | | [`loglike_css`](statsmodels.tsa.arima_model.arma.loglike_css#statsmodels.tsa.arima_model.ARMA.loglike_css "statsmodels.tsa.arima_model.ARMA.loglike_css")(params[, set\_sigma2]) | Conditional Sum of Squares likelihood function. | | [`loglike_kalman`](statsmodels.tsa.arima_model.arma.loglike_kalman#statsmodels.tsa.arima_model.ARMA.loglike_kalman "statsmodels.tsa.arima_model.ARMA.loglike_kalman")(params[, set\_sigma2]) | Compute exact loglikelihood for ARMA(p,q) model by the Kalman Filter. | | [`predict`](statsmodels.tsa.arima_model.arma.predict#statsmodels.tsa.arima_model.ARMA.predict "statsmodels.tsa.arima_model.ARMA.predict")(params[, start, end, exog, dynamic]) | ARMA model in-sample and out-of-sample prediction | | [`score`](statsmodels.tsa.arima_model.arma.score#statsmodels.tsa.arima_model.ARMA.score "statsmodels.tsa.arima_model.ARMA.score")(params) | Compute the score function at params. | #### Attributes | | | | --- | --- | | `endog_names` | Names of endogenous variables | | `exog_names` | | statsmodels statsmodels.discrete.discrete_model.LogitResults.wald_test statsmodels.discrete.discrete\_model.LogitResults.wald\_test ============================================================ `LogitResults.wald_test(r_matrix, cov_p=None, scale=1.0, invcov=None, use_f=None)` Compute a Wald-test for a joint linear hypothesis. | Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) – + array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length p row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – Default is 1.0 for no scaling. * **invcov** (*array-like**,* *optional*) – A q x q array to specify an inverse covariance matrix based on a restrictions matrix. * **use\_f** (*bool*) – If True, then the F-distribution is used. If False, then the asymptotic distribution, chisquare is used. If use\_f is None, then the F distribution is used if the model specifies that use\_t is True. The test statistic is proportionally adjusted for the distribution by the number of constraints in the hypothesis. | | Returns: | **res** – The results for the test are attributes of this results instance. | | Return type: | ContrastResults instance | See also [`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`f_test`](statsmodels.discrete.discrete_model.logitresults.f_test#statsmodels.discrete.discrete_model.LogitResults.f_test "statsmodels.discrete.discrete_model.LogitResults.f_test"), [`t_test`](statsmodels.discrete.discrete_model.logitresults.t_test#statsmodels.discrete.discrete_model.LogitResults.t_test "statsmodels.discrete.discrete_model.LogitResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") #### Notes The matrix `r_matrix` is assumed to be non-singular. More precisely, r\_matrix (pX pX.T) r\_matrix.T is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full. statsmodels statsmodels.tsa.arima_process.lpol_fiar statsmodels.tsa.arima\_process.lpol\_fiar ========================================= `statsmodels.tsa.arima_process.lpol_fiar(d, n=20)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_process.html#lpol_fiar) AR representation of fractional integration \[(1-L)^{d} for |d|<0.5 or |d|<1 (?)\] | Parameters: | * **d** (*float*) – fractional power * **n** (*int*) – number of terms to calculate, including lag zero | | Returns: | * **ar** (*array*) – coefficients of lag polynomial * *Notes* * *first coefficient is 1, negative signs except for first term,* * *ar(L)\*x\_t* | statsmodels statsmodels.genmod.families.links.NegativeBinomial.inverse statsmodels.genmod.families.links.NegativeBinomial.inverse ========================================================== `NegativeBinomial.inverse(z)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/links.html#NegativeBinomial.inverse) Inverse of the negative binomial transform | Parameters: | **z** (*array-like*) – The value of the inverse of the negative binomial link at `p`. | | Returns: | **p** – Mean parameters | | Return type: | array | #### Notes g^(-1)(z) = exp(z)/(alpha\*(1-exp(z))) statsmodels statsmodels.sandbox.regression.gmm.IVGMM statsmodels.sandbox.regression.gmm.IVGMM ======================================== `class statsmodels.sandbox.regression.gmm.IVGMM(endog, exog, instrument, k_moms=None, k_params=None, missing='none', **kwds)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#IVGMM) Basic class for instrumental variables estimation using GMM A linear function for the conditional mean is defined as default but the methods should be overwritten by subclasses, currently `LinearIVGMM` and `NonlinearIVGMM` are implemented as subclasses. See also [`LinearIVGMM`](statsmodels.sandbox.regression.gmm.linearivgmm#statsmodels.sandbox.regression.gmm.LinearIVGMM "statsmodels.sandbox.regression.gmm.LinearIVGMM"), [`NonlinearIVGMM`](statsmodels.sandbox.regression.gmm.nonlinearivgmm#statsmodels.sandbox.regression.gmm.NonlinearIVGMM "statsmodels.sandbox.regression.gmm.NonlinearIVGMM") #### Methods | | | | --- | --- | | [`calc_weightmatrix`](statsmodels.sandbox.regression.gmm.ivgmm.calc_weightmatrix#statsmodels.sandbox.regression.gmm.IVGMM.calc_weightmatrix "statsmodels.sandbox.regression.gmm.IVGMM.calc_weightmatrix")(moms[, weights\_method, …]) | calculate omega or the weighting matrix | | [`fit`](statsmodels.sandbox.regression.gmm.ivgmm.fit#statsmodels.sandbox.regression.gmm.IVGMM.fit "statsmodels.sandbox.regression.gmm.IVGMM.fit")([start\_params, maxiter, inv\_weights, …]) | Estimate parameters using GMM and return GMMResults | | [`fitgmm`](statsmodels.sandbox.regression.gmm.ivgmm.fitgmm#statsmodels.sandbox.regression.gmm.IVGMM.fitgmm "statsmodels.sandbox.regression.gmm.IVGMM.fitgmm")(start[, weights, optim\_method, …]) | estimate parameters using GMM | | [`fitgmm_cu`](statsmodels.sandbox.regression.gmm.ivgmm.fitgmm_cu#statsmodels.sandbox.regression.gmm.IVGMM.fitgmm_cu "statsmodels.sandbox.regression.gmm.IVGMM.fitgmm_cu")(start[, optim\_method, optim\_args]) | estimate parameters using continuously updating GMM | | [`fititer`](statsmodels.sandbox.regression.gmm.ivgmm.fititer#statsmodels.sandbox.regression.gmm.IVGMM.fititer "statsmodels.sandbox.regression.gmm.IVGMM.fititer")(start[, maxiter, start\_invweights, …]) | iterative estimation with updating of optimal weighting matrix | | [`fitstart`](statsmodels.sandbox.regression.gmm.ivgmm.fitstart#statsmodels.sandbox.regression.gmm.IVGMM.fitstart "statsmodels.sandbox.regression.gmm.IVGMM.fitstart")() | | | [`from_formula`](statsmodels.sandbox.regression.gmm.ivgmm.from_formula#statsmodels.sandbox.regression.gmm.IVGMM.from_formula "statsmodels.sandbox.regression.gmm.IVGMM.from_formula")(formula, data[, subset, drop\_cols]) | Create a Model from a formula and dataframe. | | [`get_error`](statsmodels.sandbox.regression.gmm.ivgmm.get_error#statsmodels.sandbox.regression.gmm.IVGMM.get_error "statsmodels.sandbox.regression.gmm.IVGMM.get_error")(params) | | | [`gmmobjective`](statsmodels.sandbox.regression.gmm.ivgmm.gmmobjective#statsmodels.sandbox.regression.gmm.IVGMM.gmmobjective "statsmodels.sandbox.regression.gmm.IVGMM.gmmobjective")(params, weights) | objective function for GMM minimization | | [`gmmobjective_cu`](statsmodels.sandbox.regression.gmm.ivgmm.gmmobjective_cu#statsmodels.sandbox.regression.gmm.IVGMM.gmmobjective_cu "statsmodels.sandbox.regression.gmm.IVGMM.gmmobjective_cu")(params[, weights\_method, wargs]) | objective function for continuously updating GMM minimization | | [`gradient_momcond`](statsmodels.sandbox.regression.gmm.ivgmm.gradient_momcond#statsmodels.sandbox.regression.gmm.IVGMM.gradient_momcond "statsmodels.sandbox.regression.gmm.IVGMM.gradient_momcond")(params[, epsilon, centered]) | gradient of moment conditions | | [`momcond`](statsmodels.sandbox.regression.gmm.ivgmm.momcond#statsmodels.sandbox.regression.gmm.IVGMM.momcond "statsmodels.sandbox.regression.gmm.IVGMM.momcond")(params) | | | [`momcond_mean`](statsmodels.sandbox.regression.gmm.ivgmm.momcond_mean#statsmodels.sandbox.regression.gmm.IVGMM.momcond_mean "statsmodels.sandbox.regression.gmm.IVGMM.momcond_mean")(params) | mean of moment conditions, | | [`predict`](statsmodels.sandbox.regression.gmm.ivgmm.predict#statsmodels.sandbox.regression.gmm.IVGMM.predict "statsmodels.sandbox.regression.gmm.IVGMM.predict")(params[, exog]) | After a model has been fit predict returns the fitted values. | | [`score`](statsmodels.sandbox.regression.gmm.ivgmm.score#statsmodels.sandbox.regression.gmm.IVGMM.score "statsmodels.sandbox.regression.gmm.IVGMM.score")(params, weights[, epsilon, centered]) | | | [`score_cu`](statsmodels.sandbox.regression.gmm.ivgmm.score_cu#statsmodels.sandbox.regression.gmm.IVGMM.score_cu "statsmodels.sandbox.regression.gmm.IVGMM.score_cu")(params[, epsilon, centered]) | | | [`set_param_names`](statsmodels.sandbox.regression.gmm.ivgmm.set_param_names#statsmodels.sandbox.regression.gmm.IVGMM.set_param_names "statsmodels.sandbox.regression.gmm.IVGMM.set_param_names")(param\_names[, k\_params]) | set the parameter names in the model | | [`start_weights`](statsmodels.sandbox.regression.gmm.ivgmm.start_weights#statsmodels.sandbox.regression.gmm.IVGMM.start_weights "statsmodels.sandbox.regression.gmm.IVGMM.start_weights")([inv]) | | #### Attributes | | | | --- | --- | | `endog_names` | Names of endogenous variables | | `exog_names` | Names of exogenous variables | | `results_class` | | statsmodels statsmodels.miscmodels.count.PoissonZiGMLE.predict statsmodels.miscmodels.count.PoissonZiGMLE.predict ================================================== `PoissonZiGMLE.predict(params, exog=None, *args, **kwargs)` After a model has been fit predict returns the fitted values. This is a placeholder intended to be overwritten by individual models. statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.loglike statsmodels.tsa.statespace.dynamic\_factor.DynamicFactor.loglike ================================================================ `DynamicFactor.loglike(params, *args, **kwargs)` Loglikelihood evaluation | Parameters: | * **params** (*array\_like*) – Array of parameters at which to evaluate the loglikelihood function. * **transformed** (*boolean**,* *optional*) – Whether or not `params` is already transformed. Default is True. * **kwargs** – Additional keyword arguments to pass to the Kalman filter. See `KalmanFilter.filter` for more details. | #### Notes [[1]](#id2) recommend maximizing the average likelihood to avoid scale issues; this is done automatically by the base Model fit method. #### References | | | | --- | --- | | [[1]](#id1) | Koopman, Siem Jan, Neil Shephard, and Jurgen A. Doornik. 1999. Statistical Algorithms for Models in State Space Using SsfPack 2.2. Econometrics Journal 2 (1): 107-60. doi:10.1111/1368-423X.00023. | See also [`update`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactor.update#statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.update "statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.update") modifies the internal state of the state space model to reflect new params statsmodels statsmodels.sandbox.distributions.extras.SkewNorm_gen.fit_loc_scale statsmodels.sandbox.distributions.extras.SkewNorm\_gen.fit\_loc\_scale ====================================================================== `SkewNorm_gen.fit_loc_scale(data, *args)` Estimate loc and scale parameters from data using 1st and 2nd moments. | Parameters: | * **data** (*array\_like*) – Data to fit. * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information). | | Returns: | * **Lhat** (*float*) – Estimated location parameter for the data. * **Shat** (*float*) – Estimated scale parameter for the data. |
programming_docs
statsmodels statsmodels.sandbox.stats.multicomp.StepDown.run statsmodels.sandbox.stats.multicomp.StepDown.run ================================================ `StepDown.run(alpha)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/multicomp.html#StepDown.run) main function to run the test, could be done in \_\_call\_\_ instead this could have all the initialization code statsmodels statsmodels.stats.contingency_tables.Table2x2.oddsratio_confint statsmodels.stats.contingency\_tables.Table2x2.oddsratio\_confint ================================================================= `Table2x2.oddsratio_confint(alpha=0.05, method='normal')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table2x2.oddsratio_confint) A confidence interval for the odds ratio. | Parameters: | * **alpha** (*float*) – `1 - alpha` is the nominal coverage probability of the confidence interval. * **method** (*string*) – The method for producing the confidence interval. Currently must be ‘normal’ which uses the normal approximation. | statsmodels statsmodels.sandbox.stats.multicomp.ccols statsmodels.sandbox.stats.multicomp.ccols ========================================= `statsmodels.sandbox.stats.multicomp.ccols = array([ 2, 3, 4, 5, 6, 7, 8, 9, 10])` statsmodels statsmodels.tsa.statespace.varmax.VARMAXResults statsmodels.tsa.statespace.varmax.VARMAXResults =============================================== `class statsmodels.tsa.statespace.varmax.VARMAXResults(model, params, filter_results, cov_type='opg', **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/varmax.html#VARMAXResults) Class to hold results from fitting an VARMAX model. | Parameters: | **model** (*VARMAX instance*) – The fitted model instance | `specification` *dictionary* – Dictionary including all attributes from the VARMAX model instance. `coefficient_matrices_var` *array* – Array containing autoregressive lag polynomial coefficient matrices, ordered from lowest degree to highest. `coefficient_matrices_vma` *array* – Array containing moving average lag polynomial coefficients, ordered from lowest degree to highest. See also [`statsmodels.tsa.statespace.kalman_filter.FilterResults`](statsmodels.tsa.statespace.kalman_filter.filterresults#statsmodels.tsa.statespace.kalman_filter.FilterResults "statsmodels.tsa.statespace.kalman_filter.FilterResults"), [`statsmodels.tsa.statespace.mlemodel.MLEResults`](statsmodels.tsa.statespace.mlemodel.mleresults#statsmodels.tsa.statespace.mlemodel.MLEResults "statsmodels.tsa.statespace.mlemodel.MLEResults") #### Methods | | | | --- | --- | | [`aic`](statsmodels.tsa.statespace.varmax.varmaxresults.aic#statsmodels.tsa.statespace.varmax.VARMAXResults.aic "statsmodels.tsa.statespace.varmax.VARMAXResults.aic")() | (float) Akaike Information Criterion | | [`bic`](statsmodels.tsa.statespace.varmax.varmaxresults.bic#statsmodels.tsa.statespace.varmax.VARMAXResults.bic "statsmodels.tsa.statespace.varmax.VARMAXResults.bic")() | (float) Bayes Information Criterion | | [`bse`](statsmodels.tsa.statespace.varmax.varmaxresults.bse#statsmodels.tsa.statespace.varmax.VARMAXResults.bse "statsmodels.tsa.statespace.varmax.VARMAXResults.bse")() | | | [`conf_int`](statsmodels.tsa.statespace.varmax.varmaxresults.conf_int#statsmodels.tsa.statespace.varmax.VARMAXResults.conf_int "statsmodels.tsa.statespace.varmax.VARMAXResults.conf_int")([alpha, cols, method]) | Returns the confidence interval of the fitted parameters. | | [`cov_params`](statsmodels.tsa.statespace.varmax.varmaxresults.cov_params#statsmodels.tsa.statespace.varmax.VARMAXResults.cov_params "statsmodels.tsa.statespace.varmax.VARMAXResults.cov_params")([r\_matrix, column, scale, cov\_p, …]) | Returns the variance/covariance matrix. | | [`cov_params_approx`](statsmodels.tsa.statespace.varmax.varmaxresults.cov_params_approx#statsmodels.tsa.statespace.varmax.VARMAXResults.cov_params_approx "statsmodels.tsa.statespace.varmax.VARMAXResults.cov_params_approx")() | (array) The variance / covariance matrix. | | [`cov_params_oim`](statsmodels.tsa.statespace.varmax.varmaxresults.cov_params_oim#statsmodels.tsa.statespace.varmax.VARMAXResults.cov_params_oim "statsmodels.tsa.statespace.varmax.VARMAXResults.cov_params_oim")() | (array) The variance / covariance matrix. | | [`cov_params_opg`](statsmodels.tsa.statespace.varmax.varmaxresults.cov_params_opg#statsmodels.tsa.statespace.varmax.VARMAXResults.cov_params_opg "statsmodels.tsa.statespace.varmax.VARMAXResults.cov_params_opg")() | (array) The variance / covariance matrix. | | [`cov_params_robust`](statsmodels.tsa.statespace.varmax.varmaxresults.cov_params_robust#statsmodels.tsa.statespace.varmax.VARMAXResults.cov_params_robust "statsmodels.tsa.statespace.varmax.VARMAXResults.cov_params_robust")() | (array) The QMLE variance / covariance matrix. | | [`cov_params_robust_approx`](statsmodels.tsa.statespace.varmax.varmaxresults.cov_params_robust_approx#statsmodels.tsa.statespace.varmax.VARMAXResults.cov_params_robust_approx "statsmodels.tsa.statespace.varmax.VARMAXResults.cov_params_robust_approx")() | (array) The QMLE variance / covariance matrix. | | [`cov_params_robust_oim`](statsmodels.tsa.statespace.varmax.varmaxresults.cov_params_robust_oim#statsmodels.tsa.statespace.varmax.VARMAXResults.cov_params_robust_oim "statsmodels.tsa.statespace.varmax.VARMAXResults.cov_params_robust_oim")() | (array) The QMLE variance / covariance matrix. | | [`f_test`](statsmodels.tsa.statespace.varmax.varmaxresults.f_test#statsmodels.tsa.statespace.varmax.VARMAXResults.f_test "statsmodels.tsa.statespace.varmax.VARMAXResults.f_test")(r\_matrix[, cov\_p, scale, invcov]) | Compute the F-test for a joint linear hypothesis. | | [`fittedvalues`](statsmodels.tsa.statespace.varmax.varmaxresults.fittedvalues#statsmodels.tsa.statespace.varmax.VARMAXResults.fittedvalues "statsmodels.tsa.statespace.varmax.VARMAXResults.fittedvalues")() | (array) The predicted values of the model. | | [`forecast`](statsmodels.tsa.statespace.varmax.varmaxresults.forecast#statsmodels.tsa.statespace.varmax.VARMAXResults.forecast "statsmodels.tsa.statespace.varmax.VARMAXResults.forecast")([steps]) | Out-of-sample forecasts | | [`get_forecast`](statsmodels.tsa.statespace.varmax.varmaxresults.get_forecast#statsmodels.tsa.statespace.varmax.VARMAXResults.get_forecast "statsmodels.tsa.statespace.varmax.VARMAXResults.get_forecast")([steps]) | Out-of-sample forecasts | | [`get_prediction`](statsmodels.tsa.statespace.varmax.varmaxresults.get_prediction#statsmodels.tsa.statespace.varmax.VARMAXResults.get_prediction "statsmodels.tsa.statespace.varmax.VARMAXResults.get_prediction")([start, end, dynamic, index, …]) | In-sample prediction and out-of-sample forecasting | | [`hqic`](statsmodels.tsa.statespace.varmax.varmaxresults.hqic#statsmodels.tsa.statespace.varmax.VARMAXResults.hqic "statsmodels.tsa.statespace.varmax.VARMAXResults.hqic")() | (float) Hannan-Quinn Information Criterion | | [`impulse_responses`](statsmodels.tsa.statespace.varmax.varmaxresults.impulse_responses#statsmodels.tsa.statespace.varmax.VARMAXResults.impulse_responses "statsmodels.tsa.statespace.varmax.VARMAXResults.impulse_responses")([steps, impulse, …]) | Impulse response function | | [`info_criteria`](statsmodels.tsa.statespace.varmax.varmaxresults.info_criteria#statsmodels.tsa.statespace.varmax.VARMAXResults.info_criteria "statsmodels.tsa.statespace.varmax.VARMAXResults.info_criteria")(criteria[, method]) | Information criteria | | [`initialize`](statsmodels.tsa.statespace.varmax.varmaxresults.initialize#statsmodels.tsa.statespace.varmax.VARMAXResults.initialize "statsmodels.tsa.statespace.varmax.VARMAXResults.initialize")(model, params, \*\*kwd) | | | [`llf`](statsmodels.tsa.statespace.varmax.varmaxresults.llf#statsmodels.tsa.statespace.varmax.VARMAXResults.llf "statsmodels.tsa.statespace.varmax.VARMAXResults.llf")() | (float) The value of the log-likelihood function evaluated at `params`. | | [`llf_obs`](statsmodels.tsa.statespace.varmax.varmaxresults.llf_obs#statsmodels.tsa.statespace.varmax.VARMAXResults.llf_obs "statsmodels.tsa.statespace.varmax.VARMAXResults.llf_obs")() | (float) The value of the log-likelihood function evaluated at `params`. | | [`load`](statsmodels.tsa.statespace.varmax.varmaxresults.load#statsmodels.tsa.statespace.varmax.VARMAXResults.load "statsmodels.tsa.statespace.varmax.VARMAXResults.load")(fname) | load a pickle, (class method) | | [`loglikelihood_burn`](statsmodels.tsa.statespace.varmax.varmaxresults.loglikelihood_burn#statsmodels.tsa.statespace.varmax.VARMAXResults.loglikelihood_burn "statsmodels.tsa.statespace.varmax.VARMAXResults.loglikelihood_burn")() | (float) The number of observations during which the likelihood is not evaluated. | | [`normalized_cov_params`](statsmodels.tsa.statespace.varmax.varmaxresults.normalized_cov_params#statsmodels.tsa.statespace.varmax.VARMAXResults.normalized_cov_params "statsmodels.tsa.statespace.varmax.VARMAXResults.normalized_cov_params")() | | | [`plot_diagnostics`](statsmodels.tsa.statespace.varmax.varmaxresults.plot_diagnostics#statsmodels.tsa.statespace.varmax.VARMAXResults.plot_diagnostics "statsmodels.tsa.statespace.varmax.VARMAXResults.plot_diagnostics")([variable, lags, fig, figsize]) | Diagnostic plots for standardized residuals of one endogenous variable | | [`predict`](statsmodels.tsa.statespace.varmax.varmaxresults.predict#statsmodels.tsa.statespace.varmax.VARMAXResults.predict "statsmodels.tsa.statespace.varmax.VARMAXResults.predict")([start, end, dynamic]) | In-sample prediction and out-of-sample forecasting | | [`pvalues`](statsmodels.tsa.statespace.varmax.varmaxresults.pvalues#statsmodels.tsa.statespace.varmax.VARMAXResults.pvalues "statsmodels.tsa.statespace.varmax.VARMAXResults.pvalues")() | (array) The p-values associated with the z-statistics of the coefficients. | | [`remove_data`](statsmodels.tsa.statespace.varmax.varmaxresults.remove_data#statsmodels.tsa.statespace.varmax.VARMAXResults.remove_data "statsmodels.tsa.statespace.varmax.VARMAXResults.remove_data")() | remove data arrays, all nobs arrays from result and model | | [`resid`](statsmodels.tsa.statespace.varmax.varmaxresults.resid#statsmodels.tsa.statespace.varmax.VARMAXResults.resid "statsmodels.tsa.statespace.varmax.VARMAXResults.resid")() | (array) The model residuals. | | [`save`](statsmodels.tsa.statespace.varmax.varmaxresults.save#statsmodels.tsa.statespace.varmax.VARMAXResults.save "statsmodels.tsa.statespace.varmax.VARMAXResults.save")(fname[, remove\_data]) | save a pickle of this instance | | [`simulate`](statsmodels.tsa.statespace.varmax.varmaxresults.simulate#statsmodels.tsa.statespace.varmax.VARMAXResults.simulate "statsmodels.tsa.statespace.varmax.VARMAXResults.simulate")(nsimulations[, measurement\_shocks, …]) | Simulate a new time series following the state space model | | [`summary`](statsmodels.tsa.statespace.varmax.varmaxresults.summary#statsmodels.tsa.statespace.varmax.VARMAXResults.summary "statsmodels.tsa.statespace.varmax.VARMAXResults.summary")([alpha, start, separate\_params]) | Summarize the Model | | [`t_test`](statsmodels.tsa.statespace.varmax.varmaxresults.t_test#statsmodels.tsa.statespace.varmax.VARMAXResults.t_test "statsmodels.tsa.statespace.varmax.VARMAXResults.t_test")(r\_matrix[, cov\_p, scale, use\_t]) | Compute a t-test for a each linear hypothesis of the form Rb = q | | [`t_test_pairwise`](statsmodels.tsa.statespace.varmax.varmaxresults.t_test_pairwise#statsmodels.tsa.statespace.varmax.VARMAXResults.t_test_pairwise "statsmodels.tsa.statespace.varmax.VARMAXResults.t_test_pairwise")(term\_name[, method, alpha, …]) | perform pairwise t\_test with multiple testing corrected p-values | | [`test_heteroskedasticity`](statsmodels.tsa.statespace.varmax.varmaxresults.test_heteroskedasticity#statsmodels.tsa.statespace.varmax.VARMAXResults.test_heteroskedasticity "statsmodels.tsa.statespace.varmax.VARMAXResults.test_heteroskedasticity")(method[, …]) | Test for heteroskedasticity of standardized residuals | | [`test_normality`](statsmodels.tsa.statespace.varmax.varmaxresults.test_normality#statsmodels.tsa.statespace.varmax.VARMAXResults.test_normality "statsmodels.tsa.statespace.varmax.VARMAXResults.test_normality")(method) | Test for normality of standardized residuals. | | [`test_serial_correlation`](statsmodels.tsa.statespace.varmax.varmaxresults.test_serial_correlation#statsmodels.tsa.statespace.varmax.VARMAXResults.test_serial_correlation "statsmodels.tsa.statespace.varmax.VARMAXResults.test_serial_correlation")(method[, lags]) | Ljung-box test for no serial correlation of standardized residuals | | [`tvalues`](statsmodels.tsa.statespace.varmax.varmaxresults.tvalues#statsmodels.tsa.statespace.varmax.VARMAXResults.tvalues "statsmodels.tsa.statespace.varmax.VARMAXResults.tvalues")() | Return the t-statistic for a given parameter estimate. | | [`wald_test`](statsmodels.tsa.statespace.varmax.varmaxresults.wald_test#statsmodels.tsa.statespace.varmax.VARMAXResults.wald_test "statsmodels.tsa.statespace.varmax.VARMAXResults.wald_test")(r\_matrix[, cov\_p, scale, invcov, …]) | Compute a Wald-test for a joint linear hypothesis. | | [`wald_test_terms`](statsmodels.tsa.statespace.varmax.varmaxresults.wald_test_terms#statsmodels.tsa.statespace.varmax.VARMAXResults.wald_test_terms "statsmodels.tsa.statespace.varmax.VARMAXResults.wald_test_terms")([skip\_single, …]) | Compute a sequence of Wald tests for terms over multiple columns | | [`zvalues`](statsmodels.tsa.statespace.varmax.varmaxresults.zvalues#statsmodels.tsa.statespace.varmax.VARMAXResults.zvalues "statsmodels.tsa.statespace.varmax.VARMAXResults.zvalues")() | (array) The z-statistics for the coefficients. | #### Attributes | | | | --- | --- | | `use_t` | | statsmodels statsmodels.tsa.ar_model.ARResults.f_test statsmodels.tsa.ar\_model.ARResults.f\_test =========================================== `ARResults.f_test(r_matrix, cov_p=None, scale=1.0, invcov=None)` Compute the F-test for a joint linear hypothesis. This is a special case of `wald_test` that always uses the F distribution. | Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) – + array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length k row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – Default is 1.0 for no scaling. * **invcov** (*array-like**,* *optional*) – A q x q array to specify an inverse covariance matrix based on a restrictions matrix. | | Returns: | **res** – The results for the test are attributes of this results instance. | | Return type: | ContrastResults instance | #### Examples ``` >>> import numpy as np >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> A = np.identity(len(results.params)) >>> A = A[1:,:] ``` This tests that each coefficient is jointly statistically significantly different from zero. ``` >>> print(results.f_test(A)) <F test: F=array([[ 330.28533923]]), p=4.984030528700946e-10, df_denom=9, df_num=6> ``` Compare this to ``` >>> results.fvalue 330.2853392346658 >>> results.f_pvalue 4.98403096572e-10 ``` ``` >>> B = np.array(([0,0,1,-1,0,0,0],[0,0,0,0,0,1,-1])) ``` This tests that the coefficient on the 2nd and 3rd regressors are equal and jointly that the coefficient on the 5th and 6th regressors are equal. ``` >>> print(results.f_test(B)) <F test: F=array([[ 9.74046187]]), p=0.005605288531708235, df_denom=9, df_num=2> ``` Alternatively, you can specify the hypothesis tests using a string ``` >>> from statsmodels.datasets import longley >>> from statsmodels.formula.api import ols >>> dta = longley.load_pandas().data >>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' >>> results = ols(formula, dta).fit() >>> hypotheses = '(GNPDEFL = GNP), (UNEMP = 2), (YEAR/1829 = 1)' >>> f_test = results.f_test(hypotheses) >>> print(f_test) <F test: F=array([[ 144.17976065]]), p=6.322026217355609e-08, df_denom=9, df_num=3> ``` See also [`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`wald_test`](statsmodels.tsa.ar_model.arresults.wald_test#statsmodels.tsa.ar_model.ARResults.wald_test "statsmodels.tsa.ar_model.ARResults.wald_test"), [`t_test`](statsmodels.tsa.ar_model.arresults.t_test#statsmodels.tsa.ar_model.ARResults.t_test "statsmodels.tsa.ar_model.ARResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") #### Notes The matrix `r_matrix` is assumed to be non-singular. More precisely, r\_matrix (pX pX.T) r\_matrix.T is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full. statsmodels statsmodels.regression.recursive_ls.RecursiveLS.smooth statsmodels.regression.recursive\_ls.RecursiveLS.smooth ======================================================= `RecursiveLS.smooth(return_ssm=False, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/recursive_ls.html#RecursiveLS.smooth) Kalman smoothing | Parameters: | * **params** (*array\_like*) – Array of parameters at which to evaluate the loglikelihood function. * **transformed** (*boolean**,* *optional*) – Whether or not `params` is already transformed. Default is True. * **return\_ssm** (*boolean**,**optional*) – Whether or not to return only the state space output or a full results object. Default is to return a full results object. * **cov\_type** (*str**,* *optional*) – See `MLEResults.fit` for a description of covariance matrix types for results object. * **cov\_kwds** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)") *or* *None**,* *optional*) – See `MLEResults.get_robustcov_results` for a description required keywords for alternative covariance estimators * **\*\*kwargs** – Additional keyword arguments to pass to the Kalman filter. See `KalmanFilter.filter` for more details. | statsmodels statsmodels.miscmodels.count.PoissonOffsetGMLE.nloglikeobs statsmodels.miscmodels.count.PoissonOffsetGMLE.nloglikeobs ========================================================== `PoissonOffsetGMLE.nloglikeobs(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/miscmodels/count.html#PoissonOffsetGMLE.nloglikeobs) Loglikelihood of Poisson model | Parameters: | **params** (*array-like*) – The parameters of the model. | | Returns: | | | Return type: | The log likelihood of the model evaluated at `params` | #### Notes \[\ln L=\sum\_{i=1}^{n}\left[-\lambda\_{i}+y\_{i}x\_{i}^{\prime}\beta-\ln y\_{i}!\right]\] statsmodels statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.loglikeobs statsmodels.tsa.statespace.kalman\_smoother.KalmanSmoother.loglikeobs ===================================================================== `KalmanSmoother.loglikeobs(**kwargs)` Calculate the loglikelihood for each observation associated with the statespace model. | Parameters: | **\*\*kwargs** – Additional keyword arguments to pass to the Kalman filter. See `KalmanFilter.filter` for more details. | #### Notes If `loglikelihood_burn` is positive, then the entries in the returned loglikelihood vector are set to be zero for those initial time periods. | Returns: | **loglike** – Array of loglikelihood values for each observation. | | Return type: | array of float |
programming_docs
statsmodels statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression.score statsmodels.tsa.regime\_switching.markov\_autoregression.MarkovAutoregression.score =================================================================================== `MarkovAutoregression.score(params, transformed=True)` Compute the score function at params. | Parameters: | * **params** (*array\_like*) – Array of parameters at which to evaluate the score function. * **transformed** (*boolean**,* *optional*) – Whether or not `params` is already transformed. Default is True. | statsmodels statsmodels.robust.robust_linear_model.RLMResults.f_test statsmodels.robust.robust\_linear\_model.RLMResults.f\_test =========================================================== `RLMResults.f_test(r_matrix, cov_p=None, scale=1.0, invcov=None)` Compute the F-test for a joint linear hypothesis. This is a special case of `wald_test` that always uses the F distribution. | Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) – + array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length k row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – Default is 1.0 for no scaling. * **invcov** (*array-like**,* *optional*) – A q x q array to specify an inverse covariance matrix based on a restrictions matrix. | | Returns: | **res** – The results for the test are attributes of this results instance. | | Return type: | ContrastResults instance | #### Examples ``` >>> import numpy as np >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> A = np.identity(len(results.params)) >>> A = A[1:,:] ``` This tests that each coefficient is jointly statistically significantly different from zero. ``` >>> print(results.f_test(A)) <F test: F=array([[ 330.28533923]]), p=4.984030528700946e-10, df_denom=9, df_num=6> ``` Compare this to ``` >>> results.fvalue 330.2853392346658 >>> results.f_pvalue 4.98403096572e-10 ``` ``` >>> B = np.array(([0,0,1,-1,0,0,0],[0,0,0,0,0,1,-1])) ``` This tests that the coefficient on the 2nd and 3rd regressors are equal and jointly that the coefficient on the 5th and 6th regressors are equal. ``` >>> print(results.f_test(B)) <F test: F=array([[ 9.74046187]]), p=0.005605288531708235, df_denom=9, df_num=2> ``` Alternatively, you can specify the hypothesis tests using a string ``` >>> from statsmodels.datasets import longley >>> from statsmodels.formula.api import ols >>> dta = longley.load_pandas().data >>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' >>> results = ols(formula, dta).fit() >>> hypotheses = '(GNPDEFL = GNP), (UNEMP = 2), (YEAR/1829 = 1)' >>> f_test = results.f_test(hypotheses) >>> print(f_test) <F test: F=array([[ 144.17976065]]), p=6.322026217355609e-08, df_denom=9, df_num=3> ``` See also [`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`wald_test`](statsmodels.robust.robust_linear_model.rlmresults.wald_test#statsmodels.robust.robust_linear_model.RLMResults.wald_test "statsmodels.robust.robust_linear_model.RLMResults.wald_test"), [`t_test`](statsmodels.robust.robust_linear_model.rlmresults.t_test#statsmodels.robust.robust_linear_model.RLMResults.t_test "statsmodels.robust.robust_linear_model.RLMResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") #### Notes The matrix `r_matrix` is assumed to be non-singular. More precisely, r\_matrix (pX pX.T) r\_matrix.T is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full. statsmodels statsmodels.sandbox.regression.gmm.IVGMMResults.compare_j statsmodels.sandbox.regression.gmm.IVGMMResults.compare\_j ========================================================== `IVGMMResults.compare_j(other)` overidentification test for comparing two nested gmm estimates This assumes that some moment restrictions have been dropped in one of the GMM estimates relative to the other. Not tested yet We are comparing two separately estimated models, that use different weighting matrices. It is not guaranteed that the resulting difference is positive. TODO: Check in which cases Stata programs use the same weigths statsmodels statsmodels.discrete.discrete_model.NegativeBinomialResults.llnull statsmodels.discrete.discrete\_model.NegativeBinomialResults.llnull =================================================================== `NegativeBinomialResults.llnull()` statsmodels statsmodels.stats.diagnostic.CompareJ statsmodels.stats.diagnostic.CompareJ ===================================== `class statsmodels.stats.diagnostic.CompareJ` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/diagnostic.html#CompareJ) J-Test for comparing non-nested models | Parameters: | * **results\_x** (*Result instance*) – result instance of first model * **results\_z** (*Result instance*) – result instance of second model * **attach** (*bool*) – | From description in Greene, section 8.3.3 produces correct results for Example 8.3, Greene - not checked yet #currently an exception, but I don’t have clean reload in python session check what results should be attached #### Methods | | | | --- | --- | | [`run`](statsmodels.stats.diagnostic.comparej.run#statsmodels.stats.diagnostic.CompareJ.run "statsmodels.stats.diagnostic.CompareJ.run")(results\_x, results\_z[, attach]) | run J-test for non-nested models | statsmodels statsmodels.tsa.ar_model.ARResults.cov_params statsmodels.tsa.ar\_model.ARResults.cov\_params =============================================== `ARResults.cov_params(r_matrix=None, column=None, scale=None, cov_p=None, other=None)` Returns the variance/covariance matrix. The variance/covariance matrix can be of a linear contrast of the estimates of params or all params multiplied by scale which will usually be an estimate of sigma^2. Scale is assumed to be a scalar. | Parameters: | * **r\_matrix** (*array-like*) – Can be 1d, or 2d. Can be used alone or with other. * **column** (*array-like**,* *optional*) – Must be used on its own. Can be 0d or 1d see below. * **scale** (*float**,* *optional*) – Can be specified or not. Default is None, which means that the scale argument is taken from the model. * **other** (*array-like**,* *optional*) – Can be used when r\_matrix is specified. | | Returns: | **cov** – covariance matrix of the parameter estimates or of linear combination of parameter estimates. See Notes. | | Return type: | ndarray | #### Notes (The below are assumed to be in matrix notation.) If no argument is specified returns the covariance matrix of a model `(scale)*(X.T X)^(-1)` If contrast is specified it pre and post-multiplies as follows `(scale) * r_matrix (X.T X)^(-1) r_matrix.T` If contrast and other are specified returns `(scale) * r_matrix (X.T X)^(-1) other.T` If column is specified returns `(scale) * (X.T X)^(-1)[column,column]` if column is 0d OR `(scale) * (X.T X)^(-1)[column][:,column]` if column is 1d statsmodels statsmodels.sandbox.stats.multicomp.maxzero statsmodels.sandbox.stats.multicomp.maxzero =========================================== `statsmodels.sandbox.stats.multicomp.maxzero(x)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/multicomp.html#maxzero) find all up zero crossings and return the index of the highest Not used anymore ``` >>> np.random.seed(12345) >>> x = np.random.randn(8) >>> x array([-0.20470766, 0.47894334, -0.51943872, -0.5557303 , 1.96578057, 1.39340583, 0.09290788, 0.28174615]) >>> maxzero(x) (4, array([1, 4])) ``` no up-zero-crossing at end ``` >>> np.random.seed(0) >>> x = np.random.randn(8) >>> x array([ 1.76405235, 0.40015721, 0.97873798, 2.2408932 , 1.86755799, -0.97727788, 0.95008842, -0.15135721]) >>> maxzero(x) (None, array([6])) ``` statsmodels statsmodels.stats.weightstats.DescrStatsW.nobs statsmodels.stats.weightstats.DescrStatsW.nobs ============================================== `DescrStatsW.nobs()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/weightstats.html#DescrStatsW.nobs) alias for number of observations/cases, equal to sum of weights statsmodels statsmodels.sandbox.regression.try_ols_anova.data2proddummy statsmodels.sandbox.regression.try\_ols\_anova.data2proddummy ============================================================= `statsmodels.sandbox.regression.try_ols_anova.data2proddummy(x)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/try_ols_anova.html#data2proddummy) creates product dummy variables from 2 columns of 2d array drops last dummy variable, but not from each category singular with simple dummy variable but not with constant quickly written, no safeguards statsmodels statsmodels.discrete.discrete_model.NegativeBinomial.cov_params_func_l1 statsmodels.discrete.discrete\_model.NegativeBinomial.cov\_params\_func\_l1 =========================================================================== `NegativeBinomial.cov_params_func_l1(likelihood_model, xopt, retvals)` Computes cov\_params on a reduced parameter space corresponding to the nonzero parameters resulting from the l1 regularized fit. Returns a full cov\_params matrix, with entries corresponding to zero’d values set to np.nan. statsmodels statsmodels.discrete.discrete_model.CountResults.bse statsmodels.discrete.discrete\_model.CountResults.bse ===================================================== `CountResults.bse()` statsmodels statsmodels.sandbox.distributions.extras.SkewNorm_gen.isf statsmodels.sandbox.distributions.extras.SkewNorm\_gen.isf ========================================================== `SkewNorm_gen.isf(q, *args, **kwds)` Inverse survival function (inverse of `sf`) at q of the given RV. | Parameters: | * **q** (*array\_like*) – upper tail probability * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **x** – Quantile corresponding to the upper tail probability q. | | Return type: | ndarray or scalar | statsmodels statsmodels.genmod.generalized_estimating_equations.GEEResults.save statsmodels.genmod.generalized\_estimating\_equations.GEEResults.save ===================================================================== `GEEResults.save(fname, remove_data=False)` save a pickle of this instance | Parameters: | * **fname** (*string* *or* *filehandle*) – fname can be a string to a file path or filename, or a filehandle. * **remove\_data** (*bool*) – If False (default), then the instance is pickled without changes. If True, then all arrays with length nobs are set to None before pickling. See the remove\_data method. In some cases not all arrays will be set to None. | #### Notes If remove\_data is true and the model result does not implement a remove\_data method then this will raise an exception. statsmodels statsmodels.discrete.discrete_model.NegativeBinomial.initialize statsmodels.discrete.discrete\_model.NegativeBinomial.initialize ================================================================ `NegativeBinomial.initialize()` Initialize is called by statsmodels.model.LikelihoodModel.\_\_init\_\_ and should contain any preprocessing that needs to be done for a model. statsmodels statsmodels.miscmodels.count.PoissonGMLE.predict_distribution statsmodels.miscmodels.count.PoissonGMLE.predict\_distribution ============================================================== `PoissonGMLE.predict_distribution(exog)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/miscmodels/count.html#PoissonGMLE.predict_distribution) return frozen scipy.stats distribution with mu at estimated prediction statsmodels statsmodels.tsa.vector_ar.var_model.VARProcess.forecast_cov statsmodels.tsa.vector\_ar.var\_model.VARProcess.forecast\_cov ============================================================== `VARProcess.forecast_cov(steps)` Compute theoretical forecast error variance matrices | Parameters: | **steps** (*int*) – Number of steps ahead | #### Notes \[\mathrm{MSE}(h) = \sum\_{i=0}^{h-1} \Phi \Sigma\_u \Phi^T\] | Returns: | **forc\_covs** | | Return type: | ndarray (steps x neqs x neqs) | statsmodels statsmodels.sandbox.regression.gmm.IVGMMResults.wald_test statsmodels.sandbox.regression.gmm.IVGMMResults.wald\_test ========================================================== `IVGMMResults.wald_test(r_matrix, cov_p=None, scale=1.0, invcov=None, use_f=None)` Compute a Wald-test for a joint linear hypothesis. | Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) – + array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length p row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – Default is 1.0 for no scaling. * **invcov** (*array-like**,* *optional*) – A q x q array to specify an inverse covariance matrix based on a restrictions matrix. * **use\_f** (*bool*) – If True, then the F-distribution is used. If False, then the asymptotic distribution, chisquare is used. If use\_f is None, then the F distribution is used if the model specifies that use\_t is True. The test statistic is proportionally adjusted for the distribution by the number of constraints in the hypothesis. | | Returns: | **res** – The results for the test are attributes of this results instance. | | Return type: | ContrastResults instance | See also [`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`f_test`](statsmodels.sandbox.regression.gmm.ivgmmresults.f_test#statsmodels.sandbox.regression.gmm.IVGMMResults.f_test "statsmodels.sandbox.regression.gmm.IVGMMResults.f_test"), [`t_test`](statsmodels.sandbox.regression.gmm.ivgmmresults.t_test#statsmodels.sandbox.regression.gmm.IVGMMResults.t_test "statsmodels.sandbox.regression.gmm.IVGMMResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") #### Notes The matrix `r_matrix` is assumed to be non-singular. More precisely, r\_matrix (pX pX.T) r\_matrix.T is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full. statsmodels statsmodels.regression.recursive_ls.RecursiveLSResults.test_serial_correlation statsmodels.regression.recursive\_ls.RecursiveLSResults.test\_serial\_correlation ================================================================================= `RecursiveLSResults.test_serial_correlation(method, lags=None)` Ljung-box test for no serial correlation of standardized residuals Null hypothesis is no serial correlation. | Parameters: | * **method** (*string {'ljungbox'**,**'boxpierece'}* *or* *None*) – The statistical test for serial correlation. If None, an attempt is made to select an appropriate test. * **lags** (*None**,* *int* *or* *array\_like*) – If lags is an integer then this is taken to be the largest lag that is included, the test result is reported for all smaller lag length. If lags is a list or array, then all lags are included up to the largest lag in the list, however only the tests for the lags in the list are reported. If lags is None, then the default maxlag is 12\*(nobs/100)^{1/4} | | Returns: | **output** – An array with `(test_statistic, pvalue)` for each endogenous variable and each lag. The array is then sized `(k_endog, 2, lags)`. If the method is called as `ljungbox = res.test_serial_correlation()`, then `ljungbox[i]` holds the results of the Ljung-Box test (as would be returned by `statsmodels.stats.diagnostic.acorr_ljungbox`) for the `i` th endogenous variable. | | Return type: | array | #### Notes If the first `d` loglikelihood values were burned (i.e. in the specified model, `loglikelihood_burn=d`), then this test is calculated ignoring the first `d` residuals. Output is nan for any endogenous variable which has missing values. See also [`statsmodels.stats.diagnostic.acorr_ljungbox`](statsmodels.stats.diagnostic.acorr_ljungbox#statsmodels.stats.diagnostic.acorr_ljungbox "statsmodels.stats.diagnostic.acorr_ljungbox") statsmodels statsmodels.regression.recursive_ls.RecursiveLSResults.hqic statsmodels.regression.recursive\_ls.RecursiveLSResults.hqic ============================================================ `RecursiveLSResults.hqic()` (float) Hannan-Quinn Information Criterion statsmodels statsmodels.nonparametric.kernel_regression.KernelCensoredReg.aic_hurvich statsmodels.nonparametric.kernel\_regression.KernelCensoredReg.aic\_hurvich =========================================================================== `KernelCensoredReg.aic_hurvich(bw, func=None)` Computes the AIC Hurvich criteria for the estimation of the bandwidth. | Parameters: | **bw** (*str* *or* *array\_like*) – See the `bw` parameter of `KernelReg` for details. | | Returns: | * **aic** (*ndarray*) – The AIC Hurvich criteria, one element for each variable. * **func** (*None*) – Unused here, needed in signature because it’s used in `cv_loo`. | #### References See ch.2 in [1] and p.35 in [2]. statsmodels statsmodels.sandbox.regression.gmm.LinearIVGMM.fititer statsmodels.sandbox.regression.gmm.LinearIVGMM.fititer ====================================================== `LinearIVGMM.fititer(start, maxiter=2, start_invweights=None, weights_method='cov', wargs=(), optim_method='bfgs', optim_args=None)` iterative estimation with updating of optimal weighting matrix stopping criteria are maxiter or change in parameter estimate less than self.epsilon\_iter, with default 1e-6. | Parameters: | * **start** (*array*) – starting value for parameters * **maxiter** (*int*) – maximum number of iterations * **start\_weights** (*array* *(**nmoms**,* *nmoms**)*) – initial weighting matrix; if None, then the identity matrix is used * **weights\_method** (*{'cov'**,* *..}*) – method to use to estimate the optimal weighting matrix, see calc\_weightmatrix for details | | Returns: | * **params** (*array*) – estimated parameters * **weights** (*array*) – optimal weighting matrix calculated with final parameter estimates | #### Notes
programming_docs
statsmodels statsmodels.tsa.arima_model.ARIMAResults.conf_int statsmodels.tsa.arima\_model.ARIMAResults.conf\_int =================================================== `ARIMAResults.conf_int(alpha=0.05, cols=None, method='default')` Returns the confidence interval of the fitted parameters. | Parameters: | * **alpha** (*float**,* *optional*) – The significance level for the confidence interval. ie., The default `alpha` = .05 returns a 95% confidence interval. * **cols** (*array-like**,* *optional*) – `cols` specifies which confidence intervals to return * **method** (*string*) – Not Implemented Yet Method to estimate the confidence\_interval. “Default” : uses self.bse which is based on inverse Hessian for MLE “hjjh” : “jac” : “boot-bse” “boot\_quant” “profile” | | Returns: | **conf\_int** – Each row contains [lower, upper] limits of the confidence interval for the corresponding parameter. The first column contains all lower, the second column contains all upper limits. | | Return type: | array | #### Examples ``` >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> results.conf_int() array([[-5496529.48322745, -1467987.78596704], [ -177.02903529, 207.15277984], [ -0.1115811 , 0.03994274], [ -3.12506664, -0.91539297], [ -1.5179487 , -0.54850503], [ -0.56251721, 0.460309 ], [ 798.7875153 , 2859.51541392]]) ``` ``` >>> results.conf_int(cols=(2,3)) array([[-0.1115811 , 0.03994274], [-3.12506664, -0.91539297]]) ``` #### Notes The confidence interval is based on the standard normal distribution. Models wish to use a different distribution should overwrite this method. statsmodels statsmodels.discrete.discrete_model.GeneralizedPoissonResults.wald_test_terms statsmodels.discrete.discrete\_model.GeneralizedPoissonResults.wald\_test\_terms ================================================================================ `GeneralizedPoissonResults.wald_test_terms(skip_single=False, extra_constraints=None, combine_terms=None)` Compute a sequence of Wald tests for terms over multiple columns This computes joined Wald tests for the hypothesis that all coefficients corresponding to a `term` are zero. `Terms` are defined by the underlying formula or by string matching. | Parameters: | * **skip\_single** (*boolean*) – If true, then terms that consist only of a single column and, therefore, refers only to a single parameter is skipped. If false, then all terms are included. * **extra\_constraints** (*ndarray*) – not tested yet * **combine\_terms** (*None* *or* *list of strings*) – Each string in this list is matched to the name of the terms or the name of the exogenous variables. All columns whose name includes that string are combined in one joint test. | | Returns: | **test\_result** – The result instance contains `table` which is a pandas DataFrame with the test results: test statistic, degrees of freedom and pvalues. | | Return type: | result instance | #### Examples ``` >>> res_ols = ols("np.log(Days+1) ~ C(Duration, Sum)*C(Weight, Sum)", data).fit() >>> res_ols.wald_test_terms() <class 'statsmodels.stats.contrast.WaldTestResults'> F P>F df constraint df denom Intercept 279.754525 2.37985521351e-22 1 51 C(Duration, Sum) 5.367071 0.0245738436636 1 51 C(Weight, Sum) 12.432445 3.99943118767e-05 2 51 C(Duration, Sum):C(Weight, Sum) 0.176002 0.83912310946 2 51 ``` ``` >>> res_poi = Poisson.from_formula("Days ~ C(Weight) * C(Duration)", data).fit(cov_type='HC0') >>> wt = res_poi.wald_test_terms(skip_single=False, combine_terms=['Duration', 'Weight']) >>> print(wt) chi2 P>chi2 df constraint Intercept 15.695625 7.43960374424e-05 1 C(Weight) 16.132616 0.000313940174705 2 C(Duration) 1.009147 0.315107378931 1 C(Weight):C(Duration) 0.216694 0.897315972824 2 Duration 11.187849 0.010752286833 3 Weight 30.263368 4.32586407145e-06 4 ``` statsmodels statsmodels.discrete.discrete_model.NegativeBinomialResults.t_test_pairwise statsmodels.discrete.discrete\_model.NegativeBinomialResults.t\_test\_pairwise ============================================================================== `NegativeBinomialResults.t_test_pairwise(term_name, method='hs', alpha=0.05, factor_labels=None)` perform pairwise t\_test with multiple testing corrected p-values This uses the formula design\_info encoding contrast matrix and should work for all encodings of a main effect. | Parameters: | * **result** (*result instance*) – The results of an estimated model with a categorical main effect. * **term\_name** (*str*) – name of the term for which pairwise comparisons are computed. Term names for categorical effects are created by patsy and correspond to the main part of the exog names. * **method** (*str* *or* *list of strings*) – multiple testing p-value correction, default is ‘hs’, see stats.multipletesting * **alpha** (*float*) – significance level for multiple testing reject decision. * **factor\_labels** (*None**,* *list of str*) – Labels for the factor levels used for pairwise labels. If not provided, then the labels from the formula design\_info are used. | | Returns: | **results** – The results are stored as attributes, the main attributes are the following two. Other attributes are added for debugging purposes or as background information.* result\_frame : pandas DataFrame with t\_test results and multiple testing corrected p-values. * contrasts : matrix of constraints of the null hypothesis in the t\_test. | | Return type: | instance of a simple Results class | #### Notes Status: experimental. Currently only checked for treatment coding with and without specified reference level. Currently there are no multiple testing corrected confidence intervals available. #### Examples ``` >>> res = ols("np.log(Days+1) ~ C(Weight) + C(Duration)", data).fit() >>> pw = res.t_test_pairwise("C(Weight)") >>> pw.result_frame coef std err t P>|t| Conf. Int. Low 2-1 0.632315 0.230003 2.749157 8.028083e-03 0.171563 3-1 1.302555 0.230003 5.663201 5.331513e-07 0.841803 3-2 0.670240 0.230003 2.914044 5.119126e-03 0.209488 Conf. Int. Upp. pvalue-hs reject-hs 2-1 1.093067 0.010212 True 3-1 1.763307 0.000002 True 3-2 1.130992 0.010212 True ``` statsmodels statsmodels.tsa.vector_ar.var_model.VARResults.get_eq_index statsmodels.tsa.vector\_ar.var\_model.VARResults.get\_eq\_index =============================================================== `VARResults.get_eq_index(name)` Return integer position of requested equation name statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.set_conserve_memory statsmodels.tsa.statespace.dynamic\_factor.DynamicFactor.set\_conserve\_memory ============================================================================== `DynamicFactor.set_conserve_memory(conserve_memory=None, **kwargs)` Set the memory conservation method By default, the Kalman filter computes a number of intermediate matrices at each iteration. The memory conservation options control which of those matrices are stored. | Parameters: | * **conserve\_memory** (*integer**,* *optional*) – Bitmask value to set the memory conservation method to. See notes for details. * **\*\*kwargs** – Keyword arguments may be used to influence the memory conservation method by setting individual boolean flags. | #### Notes This method is rarely used. See the corresponding function in the `KalmanFilter` class for details. statsmodels statsmodels.tsa.holtwinters.Holt.loglike statsmodels.tsa.holtwinters.Holt.loglike ======================================== `Holt.loglike(params)` Log-likelihood of model. statsmodels statsmodels.regression.quantile_regression.QuantReg.fit statsmodels.regression.quantile\_regression.QuantReg.fit ======================================================== `QuantReg.fit(q=0.5, vcov='robust', kernel='epa', bandwidth='hsheather', max_iter=1000, p_tol=1e-06, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/quantile_regression.html#QuantReg.fit) Solve by Iterative Weighted Least Squares | Parameters: | * **q** (*float*) – Quantile must be between 0 and 1 * **vcov** (*string**,* *method used to calculate the variance-covariance matrix*) – of the parameters. Default is `robust`: + robust : heteroskedasticity robust standard errors (as suggested in Greene 6th edition) + iid : iid errors (as in Stata 12) * **kernel** (*string**,* *kernel to use in the kernel density estimation for the*) – asymptotic covariance matrix: + epa: Epanechnikov + cos: Cosine + gau: Gaussian + par: Parzene * **bandwidth** (*string**,* *Bandwidth selection method in kernel density*) – estimation for asymptotic covariance estimate (full references in QuantReg docstring): + hsheather: Hall-Sheather (1988) + bofinger: Bofinger (1975) + chamberlain: Chamberlain (1994) | statsmodels statsmodels.stats.sandwich_covariance.cov_hc0 statsmodels.stats.sandwich\_covariance.cov\_hc0 =============================================== `statsmodels.stats.sandwich_covariance.cov_hc0(results)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/sandwich_covariance.html#cov_hc0) See statsmodels.RegressionResults statsmodels statsmodels.regression.recursive_ls.RecursiveLSResults.llf statsmodels.regression.recursive\_ls.RecursiveLSResults.llf =========================================================== `RecursiveLSResults.llf()` (float) The value of the log-likelihood function evaluated at `params`. statsmodels statsmodels.duration.hazard_regression.PHRegResults.predict statsmodels.duration.hazard\_regression.PHRegResults.predict ============================================================ `PHRegResults.predict(endog=None, exog=None, strata=None, offset=None, transform=True, pred_type='lhr')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/duration/hazard_regression.html#PHRegResults.predict) Returns predicted values from the proportional hazards regression model. | Parameters: | * **exog** (*array-like*) – Data to use as `exog` in forming predictions. If not provided, the `exog` values from the model used to fit the data are used. * **endog** (*array-like*) – Duration (time) values at which the predictions are made. Only used if pred\_type is either ‘cumhaz’ or ‘surv’. If using model `exog`, defaults to model `endog` (time), but may be provided explicitly to make predictions at alternative times. * **strata** (*array-like*) – A vector of stratum values used to form the predictions. Not used (may be ‘None’) if pred\_type is ‘lhr’ or ‘hr’. If `exog` is None, the model stratum values are used. If `exog` is not None and pred\_type is ‘surv’ or ‘cumhaz’, stratum values must be provided (unless there is only one stratum). * **offset** (*array-like*) – Offset values used to create the predicted values. * **pred\_type** (*string*) – If ‘lhr’, returns log hazard ratios, if ‘hr’ returns hazard ratios, if ‘surv’ returns the survival function, if ‘cumhaz’ returns the cumulative hazard function. | | Returns: | * **A bunch containing two fields** (`predicted_values` and) * `standard_errors`. | #### Notes Standard errors are only returned when predicting the log hazard ratio (pred\_type is ‘lhr’). Types `surv` and `cumhaz` require estimation of the cumulative hazard function. statsmodels statsmodels.sandbox.stats.multicomp.StepDown.iter_subsets statsmodels.sandbox.stats.multicomp.StepDown.iter\_subsets ========================================================== `StepDown.iter_subsets(indices)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/multicomp.html#StepDown.iter_subsets) statsmodels statsmodels.discrete.discrete_model.Probit.score statsmodels.discrete.discrete\_model.Probit.score ================================================= `Probit.score(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#Probit.score) Probit model score (gradient) vector | Parameters: | **params** (*array-like*) – The parameters of the model | | Returns: | **score** – The score vector of the model, i.e. the first derivative of the loglikelihood function, evaluated at `params` | | Return type: | ndarray, 1-D | #### Notes \[\frac{\partial\ln L}{\partial\beta}=\sum\_{i=1}^{n}\left[\frac{q\_{i}\phi\left(q\_{i}x\_{i}^{\prime}\beta\right)}{\Phi\left(q\_{i}x\_{i}^{\prime}\beta\right)}\right]x\_{i}\] Where \(q=2y-1\). This simplification comes from the fact that the normal distribution is symmetric. statsmodels statsmodels.multivariate.factor.FactorResults.factor_scoring statsmodels.multivariate.factor.FactorResults.factor\_scoring ============================================================= `FactorResults.factor_scoring(endog=None, method='bartlett', transform=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/multivariate/factor.html#FactorResults.factor_scoring) factor scoring: compute factors for endog If endog was not provided when creating the factor class, then a standarized endog needs to be provided here. | Parameters: | * **method** (*'bartlett'* *or* *'regression'*) – Method to use for factor scoring. ‘regression’ can be abbreviated to `reg` * **transform** (*bool*) – If transform is true and endog is provided, then it will be standardized using mean and scale of original data, which has to be available in this case. If transform is False, then a provided endog will be used unchanged. The original endog in the Factor class will always be standardized if endog is None, independently of `transform`. | | Returns: | **factor\_score** – estimated factors using scoring matrix s and standarized endog ys `f = ys dot s` | | Return type: | ndarray | #### Notes Status: transform option is experimental and might change. See also `factor_score_params` : scoring matrix statsmodels statsmodels.tsa.statespace.structural.UnobservedComponents.update statsmodels.tsa.statespace.structural.UnobservedComponents.update ================================================================= `UnobservedComponents.update(params, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/structural.html#UnobservedComponents.update) Update the parameters of the model | Parameters: | * **params** (*array\_like*) – Array of new parameters. * **transformed** (*boolean**,* *optional*) – Whether or not `params` is already transformed. If set to False, `transform_params` is called. Default is True. | | Returns: | **params** – Array of parameters. | | Return type: | array\_like | #### Notes Since Model is a base class, this method should be overridden by subclasses to perform actual updating steps. statsmodels statsmodels.sandbox.stats.multicomp.varcorrection_pairs_unequal statsmodels.sandbox.stats.multicomp.varcorrection\_pairs\_unequal ================================================================= `statsmodels.sandbox.stats.multicomp.varcorrection_pairs_unequal(var_all, nobs_all, df_all)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/multicomp.html#varcorrection_pairs_unequal) return joint variance from samples with unequal variances and unequal sample sizes for all pairs something is wrong | Parameters: | * **var\_all** (*array\_like*) – The variance for each sample * **nobs\_all** (*array\_like*) – The number of observations for each sample * **df\_all** (*array\_like*) – degrees of freedom for each sample | | Returns: | * **varjoint** (*array*) – joint variance. * **dfjoint** (*array*) – joint Satterthwait’s degrees of freedom | #### Notes (copy, paste not correct) variance is 1/k \* sum\_i 1/n\_i where k is the number of samples and summation is over i=0,…,k-1. If all n\_i are the same, then the correction factor is 1. This needs to be multiplies by the joint variance estimate, means square error, MSE. To obtain the correction factor for the standard deviation, square root needs to be taken. TODO: something looks wrong with dfjoint, is formula from SPSS statsmodels statsmodels.stats.diagnostic.kstest_normal statsmodels.stats.diagnostic.kstest\_normal =========================================== `statsmodels.stats.diagnostic.kstest_normal(x, dist='norm', pvalmethod='approx')` Lilliefors test for normality or an exponential distribution. Kolmogorov Smirnov test with estimated mean and variance | Parameters: | * **x** (*array\_like**,* *1d*) – data series, sample * **dist** (*{'norm'**,* *'exp'}**,* *optional*) – Distribution to test in set. * **pvalmethod** (*{'approx'**,* *'table'}**,* *optional*) – ‘approx’ is only valid for normality. if `dist = ‘exp’`, `table` is returned. ‘approx’ uses the approximation formula of Dalal and Wilkinson, valid for pvalues < 0.1. If the pvalue is larger than 0.1, then the result of `table` is returned For normality: ‘table’ uses the table from Dalal and Wilkinson, which is available for pvalues between 0.001 and 0.2, and the formula of Lilliefors for large n (n>900). Values in the table are linearly interpolated. Values outside the range will be returned as bounds, 0.2 for large and 0.001 for small pvalues. For exponential: ‘table’ uses the table from Lilliefors 1967, available for pvalues between 0.01 and 0.2. Values outside the range will be returned as bounds, 0.2 for large and 0.01 for small pvalues. | | Returns: | * **ksstat** (*float*) – Kolmogorov-Smirnov test statistic with estimated mean and variance. * **pvalue** (*float*) – If the pvalue is lower than some threshold, e.g. 0.05, then we can reject the Null hypothesis that the sample comes from a normal distribution | #### Notes Reported power to distinguish normal from some other distributions is lower than with the Anderson-Darling test. could be vectorized statsmodels statsmodels.tsa.statespace.varmax.VARMAXResults.fittedvalues statsmodels.tsa.statespace.varmax.VARMAXResults.fittedvalues ============================================================ `VARMAXResults.fittedvalues()` (array) The predicted values of the model. An (nobs x k\_endog) array. statsmodels statsmodels.tsa.vector_ar.vecm.VECMResults.conf_int_alpha statsmodels.tsa.vector\_ar.vecm.VECMResults.conf\_int\_alpha ============================================================ `VECMResults.conf_int_alpha(alpha=0.05)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/vecm.html#VECMResults.conf_int_alpha) statsmodels statsmodels.stats.weightstats.DescrStatsW.zconfint_mean statsmodels.stats.weightstats.DescrStatsW.zconfint\_mean ======================================================== `DescrStatsW.zconfint_mean(alpha=0.05, alternative='two-sided')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/weightstats.html#DescrStatsW.zconfint_mean) two-sided confidence interval for weighted mean of data Confidence interval is based on normal distribution. If the data is 2d, then these are separate confidence intervals for each column. | Parameters: | * **alpha** (*float*) – significance level for the confidence interval, coverage is `1-alpha` * **alternative** (*string*) – This specifies the alternative hypothesis for the test that corresponds to the confidence interval. The alternative hypothesis, H1, has to be one of the following ’two-sided’: H1: mean not equal to value (default) ‘larger’ : H1: mean larger than value ‘smaller’ : H1: mean smaller than value | | Returns: | **lower, upper** – lower and upper bound of confidence interval | | Return type: | floats or ndarrays | #### Notes In a previous version, statsmodels 0.4, alpha was the confidence level, e.g. 0.95
programming_docs
statsmodels statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression.transform_params statsmodels.tsa.regime\_switching.markov\_autoregression.MarkovAutoregression.transform\_params =============================================================================================== `MarkovAutoregression.transform_params(unconstrained)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/regime_switching/markov_autoregression.html#MarkovAutoregression.transform_params) Transform unconstrained parameters used by the optimizer to constrained parameters used in likelihood evaluation | Parameters: | **unconstrained** (*array\_like*) – Array of unconstrained parameters used by the optimizer, to be transformed. | | Returns: | **constrained** – Array of constrained parameters which may be used in likelihood evalation. | | Return type: | array\_like | statsmodels statsmodels.discrete.discrete_model.MNLogit.score statsmodels.discrete.discrete\_model.MNLogit.score ================================================== `MNLogit.score(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#MNLogit.score) Score matrix for multinomial logit model log-likelihood | Parameters: | **params** (*array*) – The parameters of the multinomial logit model. | | Returns: | **score** – The 2-d score vector, i.e. the first derivative of the loglikelihood function, of the multinomial logit model evaluated at `params`. | | Return type: | ndarray, (K \* (J-1),) | #### Notes \[\frac{\partial\ln L}{\partial\beta\_{j}}=\sum\_{i}\left(d\_{ij}-\frac{\exp\left(\beta\_{j}^{\prime}x\_{i}\right)}{\sum\_{k=0}^{J}\exp\left(\beta\_{k}^{\prime}x\_{i}\right)}\right)x\_{i}\] for \(j=1,...,J\) In the multinomial model the score matrix is K x J-1 but is returned as a flattened array to work with the solvers. statsmodels statsmodels.regression.mixed_linear_model.MixedLM.group_list statsmodels.regression.mixed\_linear\_model.MixedLM.group\_list =============================================================== `MixedLM.group_list(array)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/mixed_linear_model.html#MixedLM.group_list) Returns `array` split into subarrays corresponding to the grouping structure. statsmodels statsmodels.imputation.mice.MICEData.plot_fit_obs statsmodels.imputation.mice.MICEData.plot\_fit\_obs =================================================== `MICEData.plot_fit_obs(col_name, lowess_args=None, lowess_min_n=40, jitter=None, plot_points=True, ax=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/imputation/mice.html#MICEData.plot_fit_obs) Plot fitted versus imputed or observed values as a scatterplot. | Parameters: | * **col\_name** (*string*) – The variable to be plotted on the horizontal axis. * **lowess\_args** (*dict-like*) – Keyword arguments passed to lowess fit. A dictionary of dictionaries, keys are ‘o’ and ‘i’ denoting ‘observed’ and ‘imputed’, respectively. * **lowess\_min\_n** (*integer*) – Minimum sample size to plot a lowess fit * **jitter** (*float* *or* *tuple*) – Standard deviation for jittering points in the plot. Either a single scalar applied to both axes, or a tuple containing x-axis jitter and y-axis jitter, respectively. * **plot\_points** (*bool*) – If True, the data points are plotted. * **ax** (*matplotlib axes object*) – Axes on which to plot, created if not provided. | | Returns: | | | Return type: | The matplotlib figure on which the plot is drawn. | statsmodels statsmodels.tsa.arima_model.ARMAResults.pvalues statsmodels.tsa.arima\_model.ARMAResults.pvalues ================================================ `ARMAResults.pvalues()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_model.html#ARMAResults.pvalues) statsmodels statsmodels.discrete.discrete_model.MultinomialResults.prsquared statsmodels.discrete.discrete\_model.MultinomialResults.prsquared ================================================================= `MultinomialResults.prsquared()` statsmodels statsmodels.iolib.summary.Summary.add_table_params statsmodels.iolib.summary.Summary.add\_table\_params ==================================================== `Summary.add_table_params(res, yname=None, xname=None, alpha=0.05, use_t=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/iolib/summary.html#Summary.add_table_params) create and add a table for the parameter estimates | Parameters: | * **res** (*results instance*) – some required information is directly taken from the result instance * **yname** (*string* *or* *None*) – optional name for the endogenous variable, default is “y” * **xname** (*list of strings* *or* *None*) – optional names for the exogenous variables, default is “var\_xx” * **alpha** (*float*) – significance level for the confidence intervals * **use\_t** (*bool*) – indicator whether the p-values are based on the Student-t distribution (if True) or on the normal distribution (if False) | | Returns: | **None** | | Return type: | table is attached | statsmodels statsmodels.discrete.discrete_model.Probit.cov_params_func_l1 statsmodels.discrete.discrete\_model.Probit.cov\_params\_func\_l1 ================================================================= `Probit.cov_params_func_l1(likelihood_model, xopt, retvals)` Computes cov\_params on a reduced parameter space corresponding to the nonzero parameters resulting from the l1 regularized fit. Returns a full cov\_params matrix, with entries corresponding to zero’d values set to np.nan. statsmodels statsmodels.sandbox.regression.gmm.IVGMMResults.predict statsmodels.sandbox.regression.gmm.IVGMMResults.predict ======================================================= `IVGMMResults.predict(exog=None, transform=True, *args, **kwargs)` Call self.model.predict with self.params as the first argument. | Parameters: | * **exog** (*array-like**,* *optional*) – The values for which you want to predict. see Notes below. * **transform** (*bool**,* *optional*) – If the model was fit via a formula, do you want to pass exog through the formula. Default is True. E.g., if you fit a model y ~ log(x1) + log(x2), and transform is True, then you can pass a data structure that contains x1 and x2 in their original form. Otherwise, you’d need to log the data first. * **kwargs** (*args**,*) – Some models can take additional arguments or keywords, see the predict method of the model for the details. | | Returns: | **prediction** – See self.model.predict | | Return type: | ndarray, [pandas.Series](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html#pandas.Series "(in pandas v0.22.0)") or [pandas.DataFrame](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html#pandas.DataFrame "(in pandas v0.22.0)") | #### Notes The types of exog that are supported depends on whether a formula was used in the specification of the model. If a formula was used, then exog is processed in the same way as the original data. This transformation needs to have key access to the same variable names, and can be a pandas DataFrame or a dict like object. If no formula was used, then the provided exog needs to have the same number of columns as the original exog in the model. No transformation of the data is performed except converting it to a numpy array. Row indices as in pandas data frames are supported, and added to the returned prediction. statsmodels statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression.smooth statsmodels.tsa.regime\_switching.markov\_autoregression.MarkovAutoregression.smooth ==================================================================================== `MarkovAutoregression.smooth(params, transformed=True, cov_type=None, cov_kwds=None, return_raw=False, results_class=None, results_wrapper_class=None)` Apply the Kim smoother and Hamilton filter | Parameters: | * **params** (*array\_like*) – Array of parameters at which to perform filtering. * **transformed** (*boolean**,* *optional*) – Whether or not `params` is already transformed. Default is True. * **cov\_type** (*str**,* *optional*) – See `fit` for a description of covariance matrix types for results object. * **cov\_kwds** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)") *or* *None**,* *optional*) – See `fit` for a description of required keywords for alternative covariance estimators * **return\_raw** (*boolean**,**optional*) – Whether or not to return only the raw Hamilton filter output or a full results object. Default is to return a full results object. * **results\_class** (*type**,* *optional*) – A results class to instantiate rather than `MarkovSwitchingResults`. Usually only used internally by subclasses. * **results\_wrapper\_class** (*type**,* *optional*) – A results wrapper class to instantiate rather than `MarkovSwitchingResults`. Usually only used internally by subclasses. | | Returns: | | | Return type: | MarkovSwitchingResults | statsmodels statsmodels.sandbox.regression.gmm.IVGMMResults.llf statsmodels.sandbox.regression.gmm.IVGMMResults.llf =================================================== `IVGMMResults.llf()` statsmodels statsmodels.regression.quantile_regression.QuantRegResults.compare_f_test statsmodels.regression.quantile\_regression.QuantRegResults.compare\_f\_test ============================================================================ `QuantRegResults.compare_f_test(restricted)` use F test to test whether restricted model is correct | Parameters: | **restricted** (*Result instance*) – The restricted model is assumed to be nested in the current model. The result instance of the restricted model is required to have two attributes, residual sum of squares, `ssr`, residual degrees of freedom, `df_resid`. | | Returns: | * **f\_value** (*float*) – test statistic, F distributed * **p\_value** (*float*) – p-value of the test statistic * **df\_diff** (*int*) – degrees of freedom of the restriction, i.e. difference in df between models | #### Notes See mailing list discussion October 17, This test compares the residual sum of squares of the two models. This is not a valid test, if there is unspecified heteroscedasticity or correlation. This method will issue a warning if this is detected but still return the results under the assumption of homoscedasticity and no autocorrelation (sphericity). statsmodels statsmodels.iolib.table.SimpleTable.sort statsmodels.iolib.table.SimpleTable.sort ======================================== `SimpleTable.sort(key=None, reverse=False) → None -- stable sort *IN PLACE*` statsmodels statsmodels.tsa.statespace.sarimax.SARIMAXResults.resid statsmodels.tsa.statespace.sarimax.SARIMAXResults.resid ======================================================= `SARIMAXResults.resid()` (array) The model residuals. An (nobs x k\_endog) array. statsmodels statsmodels.iolib.summary2.Summary.add_dict statsmodels.iolib.summary2.Summary.add\_dict ============================================ `Summary.add_dict(d, ncols=2, align='l', float_format='%.4f')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/iolib/summary2.html#Summary.add_dict) Add the contents of a Dict to summary table | Parameters: | * **d** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")) – Keys and values are automatically coerced to strings with str(). Users are encouraged to format them before using add\_dict. * **ncols** (*int*) – Number of columns of the output table * **align** (*string*) – Data alignment (l/c/r) | statsmodels statsmodels.discrete.discrete_model.DiscreteResults.fittedvalues statsmodels.discrete.discrete\_model.DiscreteResults.fittedvalues ================================================================= `DiscreteResults.fittedvalues()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#DiscreteResults.fittedvalues) statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.score_obs statsmodels.tsa.statespace.dynamic\_factor.DynamicFactor.score\_obs =================================================================== `DynamicFactor.score_obs(params, method='approx', transformed=True, approx_complex_step=None, approx_centered=False, **kwargs)` Compute the score per observation, evaluated at params | Parameters: | * **params** (*array\_like*) – Array of parameters at which to evaluate the score. * **kwargs** – Additional arguments to the `loglike` method. | | Returns: | **score** – Score per observation, evaluated at `params`. | | Return type: | array | #### Notes This is a numerical approximation, calculated using first-order complex step differentiation on the `loglikeobs` method. statsmodels statsmodels.discrete.discrete_model.ProbitResults.wald_test statsmodels.discrete.discrete\_model.ProbitResults.wald\_test ============================================================= `ProbitResults.wald_test(r_matrix, cov_p=None, scale=1.0, invcov=None, use_f=None)` Compute a Wald-test for a joint linear hypothesis. | Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) – + array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length p row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – Default is 1.0 for no scaling. * **invcov** (*array-like**,* *optional*) – A q x q array to specify an inverse covariance matrix based on a restrictions matrix. * **use\_f** (*bool*) – If True, then the F-distribution is used. If False, then the asymptotic distribution, chisquare is used. If use\_f is None, then the F distribution is used if the model specifies that use\_t is True. The test statistic is proportionally adjusted for the distribution by the number of constraints in the hypothesis. | | Returns: | **res** – The results for the test are attributes of this results instance. | | Return type: | ContrastResults instance | See also [`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`f_test`](statsmodels.discrete.discrete_model.probitresults.f_test#statsmodels.discrete.discrete_model.ProbitResults.f_test "statsmodels.discrete.discrete_model.ProbitResults.f_test"), [`t_test`](statsmodels.discrete.discrete_model.probitresults.t_test#statsmodels.discrete.discrete_model.ProbitResults.t_test "statsmodels.discrete.discrete_model.ProbitResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") #### Notes The matrix `r_matrix` is assumed to be non-singular. More precisely, r\_matrix (pX pX.T) r\_matrix.T is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full. statsmodels statsmodels.iolib.summary.Summary.as_html statsmodels.iolib.summary.Summary.as\_html ========================================== `Summary.as_html()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/iolib/summary.html#Summary.as_html) return tables as string | Returns: | **html** – concatenated summary tables in HTML format | | Return type: | string | statsmodels statsmodels.tsa.vector_ar.var_model.VARResults.mse statsmodels.tsa.vector\_ar.var\_model.VARResults.mse ==================================================== `VARResults.mse(steps)` Compute theoretical forecast error variance matrices | Parameters: | **steps** (*int*) – Number of steps ahead | #### Notes \[\mathrm{MSE}(h) = \sum\_{i=0}^{h-1} \Phi \Sigma\_u \Phi^T\] | Returns: | **forc\_covs** | | Return type: | ndarray (steps x neqs x neqs) | statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.summary statsmodels.sandbox.regression.gmm.IVRegressionResults.summary ============================================================== `IVRegressionResults.summary(yname=None, xname=None, title=None, alpha=0.05)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#IVRegressionResults.summary) Summarize the Regression Results | Parameters: | * **yname** (*string**,* *optional*) – Default is `y` * **xname** (*list of strings**,* *optional*) – Default is `var_##` for ## in p the number of regressors * **title** (*string**,* *optional*) – Title for the top table. If not None, then this replaces the default title * **alpha** (*float*) – significance level for the confidence intervals | | Returns: | **smry** – this holds the summary tables and text, which can be printed or converted to various output formats. | | Return type: | Summary instance | See also [`statsmodels.iolib.summary.Summary`](statsmodels.iolib.summary.summary#statsmodels.iolib.summary.Summary "statsmodels.iolib.summary.Summary") class to hold summary results statsmodels statsmodels.tsa.arima_model.ARIMAResults.arparams statsmodels.tsa.arima\_model.ARIMAResults.arparams ================================================== `ARIMAResults.arparams()` statsmodels statsmodels.tsa.vector_ar.irf.IRAnalysis.cov statsmodels.tsa.vector\_ar.irf.IRAnalysis.cov ============================================= `IRAnalysis.cov(orth=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/irf.html#IRAnalysis.cov) Compute asymptotic standard errors for impulse response coefficients #### Notes Lütkepohl eq 3.7.5 statsmodels statsmodels.discrete.count_model.GenericZeroInflated.fit statsmodels.discrete.count\_model.GenericZeroInflated.fit ========================================================= `GenericZeroInflated.fit(start_params=None, method='bfgs', maxiter=35, full_output=1, disp=1, callback=None, cov_type='nonrobust', cov_kwds=None, use_t=None, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/count_model.html#GenericZeroInflated.fit) Fit the model using maximum likelihood. The rest of the docstring is from statsmodels.base.model.LikelihoodModel.fit Fit method for likelihood based models | Parameters: | * **start\_params** (*array-like**,* *optional*) – Initial guess of the solution for the loglikelihood maximization. The default is an array of zeros. * **method** (*str**,* *optional*) – The `method` determines which solver from `scipy.optimize` is used, and it can be chosen from among the following strings: + ’newton’ for Newton-Raphson, ‘nm’ for Nelder-Mead + ’bfgs’ for Broyden-Fletcher-Goldfarb-Shanno (BFGS) + ’lbfgs’ for limited-memory BFGS with optional box constraints + ’powell’ for modified Powell’s method + ’cg’ for conjugate gradient + ’ncg’ for Newton-conjugate gradient + ’basinhopping’ for global basin-hopping solver + ’minimize’ for generic wrapper of scipy minimize (BFGS by default)The explicit arguments in `fit` are passed to the solver, with the exception of the basin-hopping solver. Each solver has several optional arguments that are not the same across solvers. See the notes section below (or scipy.optimize) for the available arguments and for the list of explicit arguments that the basin-hopping solver supports. * **maxiter** (*int**,* *optional*) – The maximum number of iterations to perform. * **full\_output** (*bool**,* *optional*) – Set to True to have all available output in the Results object’s mle\_retvals attribute. The output is dependent on the solver. See LikelihoodModelResults notes section for more information. * **disp** (*bool**,* *optional*) – Set to True to print convergence messages. * **fargs** (*tuple**,* *optional*) – Extra arguments passed to the likelihood function, i.e., loglike(x,\*args) * **callback** (*callable callback**(**xk**)**,* *optional*) – Called after each iteration, as callback(xk), where xk is the current parameter vector. * **retall** (*bool**,* *optional*) – Set to True to return list of solutions at each iteration. Available in Results object’s mle\_retvals attribute. * **skip\_hessian** (*bool**,* *optional*) – If False (default), then the negative inverse hessian is calculated after the optimization. If True, then the hessian will not be calculated. However, it will be available in methods that use the hessian in the optimization (currently only with `“newton”`). * **kwargs** (*keywords*) – All kwargs are passed to the chosen solver with one exception. The following keyword controls what happens after the fit: ``` warn_convergence : bool, optional If True, checks the model for the converged flag. If the converged flag is False, a ConvergenceWarning is issued. ``` | #### Notes The ‘basinhopping’ solver ignores `maxiter`, `retall`, `full_output` explicit arguments. Optional arguments for solvers (see returned Results.mle\_settings): ``` 'newton' tol : float Relative error in params acceptable for convergence. 'nm' -- Nelder Mead xtol : float Relative error in params acceptable for convergence ftol : float Relative error in loglike(params) acceptable for convergence maxfun : int Maximum number of function evaluations to make. 'bfgs' gtol : float Stop when norm of gradient is less than gtol. norm : float Order of norm (np.Inf is max, -np.Inf is min) epsilon If fprime is approximated, use this value for the step size. Only relevant if LikelihoodModel.score is None. 'lbfgs' m : int This many terms are used for the Hessian approximation. factr : float A stop condition that is a variant of relative error. pgtol : float A stop condition that uses the projected gradient. epsilon If fprime is approximated, use this value for the step size. Only relevant if LikelihoodModel.score is None. maxfun : int Maximum number of function evaluations to make. bounds : sequence (min, max) pairs for each element in x, defining the bounds on that parameter. Use None for one of min or max when there is no bound in that direction. 'cg' gtol : float Stop when norm of gradient is less than gtol. norm : float Order of norm (np.Inf is max, -np.Inf is min) epsilon : float If fprime is approximated, use this value for the step size. Can be scalar or vector. Only relevant if Likelihoodmodel.score is None. 'ncg' fhess_p : callable f'(x,*args) Function which computes the Hessian of f times an arbitrary vector, p. Should only be supplied if LikelihoodModel.hessian is None. avextol : float Stop when the average relative error in the minimizer falls below this amount. epsilon : float or ndarray If fhess is approximated, use this value for the step size. Only relevant if Likelihoodmodel.hessian is None. 'powell' xtol : float Line-search error tolerance ftol : float Relative error in loglike(params) for acceptable for convergence. maxfun : int Maximum number of function evaluations to make. start_direc : ndarray Initial direction set. 'basinhopping' niter : integer The number of basin hopping iterations. niter_success : integer Stop the run if the global minimum candidate remains the same for this number of iterations. T : float The "temperature" parameter for the accept or reject criterion. Higher "temperatures" mean that larger jumps in function value will be accepted. For best results `T` should be comparable to the separation (in function value) between local minima. stepsize : float Initial step size for use in the random displacement. interval : integer The interval for how often to update the `stepsize`. minimizer : dict Extra keyword arguments to be passed to the minimizer `scipy.optimize.minimize()`, for example 'method' - the minimization method (e.g. 'L-BFGS-B'), or 'tol' - the tolerance for termination. Other arguments are mapped from explicit argument of `fit`: - `args` <- `fargs` - `jac` <- `score` - `hess` <- `hess` 'minimize' min_method : str, optional Name of minimization method to use. Any method specific arguments can be passed directly. For a list of methods and their arguments, see documentation of `scipy.optimize.minimize`. If no method is specified, then BFGS is used. ```
programming_docs
statsmodels statsmodels.genmod.generalized_linear_model.GLM.predict statsmodels.genmod.generalized\_linear\_model.GLM.predict ========================================================= `GLM.predict(params, exog=None, exposure=None, offset=None, linear=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_linear_model.html#GLM.predict) Return predicted values for a design matrix | Parameters: | * **params** (*array-like*) – Parameters / coefficients of a GLM. * **exog** (*array-like**,* *optional*) – Design / exogenous data. Is exog is None, model exog is used. * **exposure** (*array-like**,* *optional*) – Exposure time values, only can be used with the log link function. See notes for details. * **offset** (*array-like**,* *optional*) – Offset values. See notes for details. * **linear** (*bool*) – If True, returns the linear predicted values. If False, returns the value of the inverse of the model’s link function at the linear predicted values. | | Returns: | | | Return type: | An array of fitted values | #### Notes Any `exposure` and `offset` provided here take precedence over the `exposure` and `offset` used in the model fit. If `exog` is passed as an argument here, then any `exposure` and `offset` values in the fit will be ignored. Exposure values must be strictly positive. statsmodels statsmodels.genmod.generalized_estimating_equations.GEEResults.split_centered_resid statsmodels.genmod.generalized\_estimating\_equations.GEEResults.split\_centered\_resid ======================================================================================= `GEEResults.split_centered_resid()` Returns the residuals centered within each group. The residuals are returned as a list of arrays containing the centered residuals for each cluster. statsmodels statsmodels.stats.contingency_tables.SquareTable.resid_pearson statsmodels.stats.contingency\_tables.SquareTable.resid\_pearson ================================================================ `SquareTable.resid_pearson()` statsmodels statsmodels.discrete.discrete_model.DiscreteModel.fit statsmodels.discrete.discrete\_model.DiscreteModel.fit ====================================================== `DiscreteModel.fit(start_params=None, method='newton', maxiter=35, full_output=1, disp=1, callback=None, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#DiscreteModel.fit) Fit the model using maximum likelihood. The rest of the docstring is from statsmodels.base.model.LikelihoodModel.fit Fit method for likelihood based models | Parameters: | * **start\_params** (*array-like**,* *optional*) – Initial guess of the solution for the loglikelihood maximization. The default is an array of zeros. * **method** (*str**,* *optional*) – The `method` determines which solver from `scipy.optimize` is used, and it can be chosen from among the following strings: + ’newton’ for Newton-Raphson, ‘nm’ for Nelder-Mead + ’bfgs’ for Broyden-Fletcher-Goldfarb-Shanno (BFGS) + ’lbfgs’ for limited-memory BFGS with optional box constraints + ’powell’ for modified Powell’s method + ’cg’ for conjugate gradient + ’ncg’ for Newton-conjugate gradient + ’basinhopping’ for global basin-hopping solver + ’minimize’ for generic wrapper of scipy minimize (BFGS by default)The explicit arguments in `fit` are passed to the solver, with the exception of the basin-hopping solver. Each solver has several optional arguments that are not the same across solvers. See the notes section below (or scipy.optimize) for the available arguments and for the list of explicit arguments that the basin-hopping solver supports. * **maxiter** (*int**,* *optional*) – The maximum number of iterations to perform. * **full\_output** (*bool**,* *optional*) – Set to True to have all available output in the Results object’s mle\_retvals attribute. The output is dependent on the solver. See LikelihoodModelResults notes section for more information. * **disp** (*bool**,* *optional*) – Set to True to print convergence messages. * **fargs** (*tuple**,* *optional*) – Extra arguments passed to the likelihood function, i.e., loglike(x,\*args) * **callback** (*callable callback**(**xk**)**,* *optional*) – Called after each iteration, as callback(xk), where xk is the current parameter vector. * **retall** (*bool**,* *optional*) – Set to True to return list of solutions at each iteration. Available in Results object’s mle\_retvals attribute. * **skip\_hessian** (*bool**,* *optional*) – If False (default), then the negative inverse hessian is calculated after the optimization. If True, then the hessian will not be calculated. However, it will be available in methods that use the hessian in the optimization (currently only with `“newton”`). * **kwargs** (*keywords*) – All kwargs are passed to the chosen solver with one exception. The following keyword controls what happens after the fit: ``` warn_convergence : bool, optional If True, checks the model for the converged flag. If the converged flag is False, a ConvergenceWarning is issued. ``` | #### Notes The ‘basinhopping’ solver ignores `maxiter`, `retall`, `full_output` explicit arguments. Optional arguments for solvers (see returned Results.mle\_settings): ``` 'newton' tol : float Relative error in params acceptable for convergence. 'nm' -- Nelder Mead xtol : float Relative error in params acceptable for convergence ftol : float Relative error in loglike(params) acceptable for convergence maxfun : int Maximum number of function evaluations to make. 'bfgs' gtol : float Stop when norm of gradient is less than gtol. norm : float Order of norm (np.Inf is max, -np.Inf is min) epsilon If fprime is approximated, use this value for the step size. Only relevant if LikelihoodModel.score is None. 'lbfgs' m : int This many terms are used for the Hessian approximation. factr : float A stop condition that is a variant of relative error. pgtol : float A stop condition that uses the projected gradient. epsilon If fprime is approximated, use this value for the step size. Only relevant if LikelihoodModel.score is None. maxfun : int Maximum number of function evaluations to make. bounds : sequence (min, max) pairs for each element in x, defining the bounds on that parameter. Use None for one of min or max when there is no bound in that direction. 'cg' gtol : float Stop when norm of gradient is less than gtol. norm : float Order of norm (np.Inf is max, -np.Inf is min) epsilon : float If fprime is approximated, use this value for the step size. Can be scalar or vector. Only relevant if Likelihoodmodel.score is None. 'ncg' fhess_p : callable f'(x,*args) Function which computes the Hessian of f times an arbitrary vector, p. Should only be supplied if LikelihoodModel.hessian is None. avextol : float Stop when the average relative error in the minimizer falls below this amount. epsilon : float or ndarray If fhess is approximated, use this value for the step size. Only relevant if Likelihoodmodel.hessian is None. 'powell' xtol : float Line-search error tolerance ftol : float Relative error in loglike(params) for acceptable for convergence. maxfun : int Maximum number of function evaluations to make. start_direc : ndarray Initial direction set. 'basinhopping' niter : integer The number of basin hopping iterations. niter_success : integer Stop the run if the global minimum candidate remains the same for this number of iterations. T : float The "temperature" parameter for the accept or reject criterion. Higher "temperatures" mean that larger jumps in function value will be accepted. For best results `T` should be comparable to the separation (in function value) between local minima. stepsize : float Initial step size for use in the random displacement. interval : integer The interval for how often to update the `stepsize`. minimizer : dict Extra keyword arguments to be passed to the minimizer `scipy.optimize.minimize()`, for example 'method' - the minimization method (e.g. 'L-BFGS-B'), or 'tol' - the tolerance for termination. Other arguments are mapped from explicit argument of `fit`: - `args` <- `fargs` - `jac` <- `score` - `hess` <- `hess` 'minimize' min_method : str, optional Name of minimization method to use. Any method specific arguments can be passed directly. For a list of methods and their arguments, see documentation of `scipy.optimize.minimize`. If no method is specified, then BFGS is used. ``` statsmodels statsmodels.sandbox.regression.gmm.GMMResults.cov_params statsmodels.sandbox.regression.gmm.GMMResults.cov\_params ========================================================= `GMMResults.cov_params(r_matrix=None, column=None, scale=None, cov_p=None, other=None)` Returns the variance/covariance matrix. The variance/covariance matrix can be of a linear contrast of the estimates of params or all params multiplied by scale which will usually be an estimate of sigma^2. Scale is assumed to be a scalar. | Parameters: | * **r\_matrix** (*array-like*) – Can be 1d, or 2d. Can be used alone or with other. * **column** (*array-like**,* *optional*) – Must be used on its own. Can be 0d or 1d see below. * **scale** (*float**,* *optional*) – Can be specified or not. Default is None, which means that the scale argument is taken from the model. * **other** (*array-like**,* *optional*) – Can be used when r\_matrix is specified. | | Returns: | **cov** – covariance matrix of the parameter estimates or of linear combination of parameter estimates. See Notes. | | Return type: | ndarray | #### Notes (The below are assumed to be in matrix notation.) If no argument is specified returns the covariance matrix of a model `(scale)*(X.T X)^(-1)` If contrast is specified it pre and post-multiplies as follows `(scale) * r_matrix (X.T X)^(-1) r_matrix.T` If contrast and other are specified returns `(scale) * r_matrix (X.T X)^(-1) other.T` If column is specified returns `(scale) * (X.T X)^(-1)[column,column]` if column is 0d OR `(scale) * (X.T X)^(-1)[column][:,column]` if column is 1d statsmodels statsmodels.discrete.discrete_model.GeneralizedPoisson.score statsmodels.discrete.discrete\_model.GeneralizedPoisson.score ============================================================= `GeneralizedPoisson.score(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#GeneralizedPoisson.score) Score vector of model. The gradient of logL with respect to each parameter. statsmodels statsmodels.sandbox.distributions.extras.NormExpan_gen.logsf statsmodels.sandbox.distributions.extras.NormExpan\_gen.logsf ============================================================= `NormExpan_gen.logsf(x, *args, **kwds)` Log of the survival function of the given RV. Returns the log of the “survival function,” defined as (1 - `cdf`), evaluated at `x`. | Parameters: | * **x** (*array\_like*) – quantiles * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **logsf** – Log of the survival function evaluated at `x`. | | Return type: | ndarray | statsmodels statsmodels.sandbox.regression.gmm.LinearIVGMM statsmodels.sandbox.regression.gmm.LinearIVGMM ============================================== `class statsmodels.sandbox.regression.gmm.LinearIVGMM(endog, exog, instrument, k_moms=None, k_params=None, missing='none', **kwds)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#LinearIVGMM) class for linear instrumental variables models estimated with GMM Uses closed form expression instead of nonlinear optimizers for each step of the iterative GMM. The model is assumed to have the following moment condition E( z \* (y - x beta)) = 0 Where `y` is the dependent endogenous variable, `x` are the explanatory variables and `z` are the instruments. Variables in `x` that are exogenous need also be included in `z`. Notation Warning: our name `exog` stands for the explanatory variables, and includes both exogenous and explanatory variables that are endogenous, i.e. included endogenous variables | Parameters: | * **endog** (*array\_like*) – dependent endogenous variable * **exog** (*array\_like*) – explanatory, right hand side variables, including explanatory variables that are endogenous * **instrument** (*array\_like*) – Instrumental variables, variables that are exogenous to the error in the linear model containing both included and excluded exogenous variables | #### Methods | | | | --- | --- | | [`calc_weightmatrix`](statsmodels.sandbox.regression.gmm.linearivgmm.calc_weightmatrix#statsmodels.sandbox.regression.gmm.LinearIVGMM.calc_weightmatrix "statsmodels.sandbox.regression.gmm.LinearIVGMM.calc_weightmatrix")(moms[, weights\_method, …]) | calculate omega or the weighting matrix | | [`fit`](statsmodels.sandbox.regression.gmm.linearivgmm.fit#statsmodels.sandbox.regression.gmm.LinearIVGMM.fit "statsmodels.sandbox.regression.gmm.LinearIVGMM.fit")([start\_params, maxiter, inv\_weights, …]) | Estimate parameters using GMM and return GMMResults | | [`fitgmm`](statsmodels.sandbox.regression.gmm.linearivgmm.fitgmm#statsmodels.sandbox.regression.gmm.LinearIVGMM.fitgmm "statsmodels.sandbox.regression.gmm.LinearIVGMM.fitgmm")(start[, weights, optim\_method]) | estimate parameters using GMM for linear model | | [`fitgmm_cu`](statsmodels.sandbox.regression.gmm.linearivgmm.fitgmm_cu#statsmodels.sandbox.regression.gmm.LinearIVGMM.fitgmm_cu "statsmodels.sandbox.regression.gmm.LinearIVGMM.fitgmm_cu")(start[, optim\_method, optim\_args]) | estimate parameters using continuously updating GMM | | [`fititer`](statsmodels.sandbox.regression.gmm.linearivgmm.fititer#statsmodels.sandbox.regression.gmm.LinearIVGMM.fititer "statsmodels.sandbox.regression.gmm.LinearIVGMM.fititer")(start[, maxiter, start\_invweights, …]) | iterative estimation with updating of optimal weighting matrix | | [`fitstart`](statsmodels.sandbox.regression.gmm.linearivgmm.fitstart#statsmodels.sandbox.regression.gmm.LinearIVGMM.fitstart "statsmodels.sandbox.regression.gmm.LinearIVGMM.fitstart")() | | | [`from_formula`](statsmodels.sandbox.regression.gmm.linearivgmm.from_formula#statsmodels.sandbox.regression.gmm.LinearIVGMM.from_formula "statsmodels.sandbox.regression.gmm.LinearIVGMM.from_formula")(formula, data[, subset, drop\_cols]) | Create a Model from a formula and dataframe. | | [`get_error`](statsmodels.sandbox.regression.gmm.linearivgmm.get_error#statsmodels.sandbox.regression.gmm.LinearIVGMM.get_error "statsmodels.sandbox.regression.gmm.LinearIVGMM.get_error")(params) | | | [`gmmobjective`](statsmodels.sandbox.regression.gmm.linearivgmm.gmmobjective#statsmodels.sandbox.regression.gmm.LinearIVGMM.gmmobjective "statsmodels.sandbox.regression.gmm.LinearIVGMM.gmmobjective")(params, weights) | objective function for GMM minimization | | [`gmmobjective_cu`](statsmodels.sandbox.regression.gmm.linearivgmm.gmmobjective_cu#statsmodels.sandbox.regression.gmm.LinearIVGMM.gmmobjective_cu "statsmodels.sandbox.regression.gmm.LinearIVGMM.gmmobjective_cu")(params[, weights\_method, wargs]) | objective function for continuously updating GMM minimization | | [`gradient_momcond`](statsmodels.sandbox.regression.gmm.linearivgmm.gradient_momcond#statsmodels.sandbox.regression.gmm.LinearIVGMM.gradient_momcond "statsmodels.sandbox.regression.gmm.LinearIVGMM.gradient_momcond")(params, \*\*kwds) | gradient of moment conditions | | [`momcond`](statsmodels.sandbox.regression.gmm.linearivgmm.momcond#statsmodels.sandbox.regression.gmm.LinearIVGMM.momcond "statsmodels.sandbox.regression.gmm.LinearIVGMM.momcond")(params) | | | [`momcond_mean`](statsmodels.sandbox.regression.gmm.linearivgmm.momcond_mean#statsmodels.sandbox.regression.gmm.LinearIVGMM.momcond_mean "statsmodels.sandbox.regression.gmm.LinearIVGMM.momcond_mean")(params) | mean of moment conditions, | | [`predict`](statsmodels.sandbox.regression.gmm.linearivgmm.predict#statsmodels.sandbox.regression.gmm.LinearIVGMM.predict "statsmodels.sandbox.regression.gmm.LinearIVGMM.predict")(params[, exog]) | After a model has been fit predict returns the fitted values. | | [`score`](statsmodels.sandbox.regression.gmm.linearivgmm.score#statsmodels.sandbox.regression.gmm.LinearIVGMM.score "statsmodels.sandbox.regression.gmm.LinearIVGMM.score")(params, weights, \*\*kwds) | | | [`score_cu`](statsmodels.sandbox.regression.gmm.linearivgmm.score_cu#statsmodels.sandbox.regression.gmm.LinearIVGMM.score_cu "statsmodels.sandbox.regression.gmm.LinearIVGMM.score_cu")(params[, epsilon, centered]) | | | [`set_param_names`](statsmodels.sandbox.regression.gmm.linearivgmm.set_param_names#statsmodels.sandbox.regression.gmm.LinearIVGMM.set_param_names "statsmodels.sandbox.regression.gmm.LinearIVGMM.set_param_names")(param\_names[, k\_params]) | set the parameter names in the model | | [`start_weights`](statsmodels.sandbox.regression.gmm.linearivgmm.start_weights#statsmodels.sandbox.regression.gmm.LinearIVGMM.start_weights "statsmodels.sandbox.regression.gmm.LinearIVGMM.start_weights")([inv]) | | #### Attributes | | | | --- | --- | | `endog_names` | Names of endogenous variables | | `exog_names` | Names of exogenous variables | | `results_class` | | statsmodels statsmodels.genmod.cov_struct.GlobalOddsRatio.initialize statsmodels.genmod.cov\_struct.GlobalOddsRatio.initialize ========================================================= `GlobalOddsRatio.initialize(model)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/cov_struct.html#GlobalOddsRatio.initialize) Called by GEE, used by implementations that need additional setup prior to running `fit`. | Parameters: | **model** (*GEE class*) – A reference to the parent GEE class instance. | statsmodels statsmodels.robust.norms.AndrewWave.rho statsmodels.robust.norms.AndrewWave.rho ======================================= `AndrewWave.rho(z)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/norms.html#AndrewWave.rho) The robust criterion function for Andrew’s wave. | Parameters: | **z** (*array-like*) – 1d array | | Returns: | **rho** – rho(z) = a\*(1-cos(z/a)) for |z| <= a\*pirho(z) = 2\*a for |z| > a\*pi | | Return type: | array | statsmodels statsmodels.stats.proportion.binom_test statsmodels.stats.proportion.binom\_test ======================================== `statsmodels.stats.proportion.binom_test(count, nobs, prop=0.5, alternative='two-sided')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/proportion.html#binom_test) Perform a test that the probability of success is p. This is an exact, two-sided test of the null hypothesis that the probability of success in a Bernoulli experiment is `p`. | Parameters: | * **count** (*integer* *or* *array\_like*) – the number of successes in nobs trials. * **nobs** (*integer*) – the number of trials or observations. * **prop** (*float**,* *optional*) – The probability of success under the null hypothesis, `0 <= prop <= 1`. The default value is `prop = 0.5` * **alternative** (*string in* *[**'two-sided'**,* *'smaller'**,* *'larger'**]*) – alternative hypothesis, which can be two-sided or either one of the one-sided tests. | | Returns: | **p-value** – The p-value of the hypothesis test | | Return type: | float | #### Notes This uses scipy.stats.binom\_test for the two-sided alternative.
programming_docs
statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.fvalue statsmodels.sandbox.regression.gmm.IVRegressionResults.fvalue ============================================================= `IVRegressionResults.fvalue()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#IVRegressionResults.fvalue) statsmodels statsmodels.tsa.statespace.structural.UnobservedComponents.from_formula statsmodels.tsa.statespace.structural.UnobservedComponents.from\_formula ======================================================================== `classmethod UnobservedComponents.from_formula(formula, data, subset=None)` Not implemented for state space models statsmodels statsmodels.sandbox.regression.gmm.NonlinearIVGMM.predict statsmodels.sandbox.regression.gmm.NonlinearIVGMM.predict ========================================================= `NonlinearIVGMM.predict(params, exog=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#NonlinearIVGMM.predict) After a model has been fit predict returns the fitted values. This is a placeholder intended to be overwritten by individual models. statsmodels statsmodels.sandbox.distributions.extras.SkewNorm_gen.stats statsmodels.sandbox.distributions.extras.SkewNorm\_gen.stats ============================================================ `SkewNorm_gen.stats(*args, **kwds)` Some statistics of the given RV. | Parameters: | * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional* *(**continuous RVs only**)*) – scale parameter (default=1) * **moments** (*str**,* *optional*) – composed of letters [‘mvsk’] defining which moments to compute: ‘m’ = mean, ‘v’ = variance, ‘s’ = (Fisher’s) skew, ‘k’ = (Fisher’s) kurtosis. (default is ‘mv’) | | Returns: | **stats** – of requested moments. | | Return type: | sequence | statsmodels statsmodels.multivariate.cancorr.CanCorr.corr_test statsmodels.multivariate.cancorr.CanCorr.corr\_test =================================================== `CanCorr.corr_test()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/multivariate/cancorr.html#CanCorr.corr_test) Approximate F test Perform multivariate statistical tests of the hypothesis that there is no canonical correlation between endog and exog. For each canonical correlation, testing its significance based on Wilks’ lambda. | Returns: | | | Return type: | CanCorrTestResults instance | statsmodels statsmodels.robust.robust_linear_model.RLM statsmodels.robust.robust\_linear\_model.RLM ============================================ `class statsmodels.robust.robust_linear_model.RLM(endog, exog, M=<statsmodels.robust.norms.HuberT object>, missing='none', **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/robust_linear_model.html#RLM) Robust Linear Models Estimate a robust linear model via iteratively reweighted least squares given a robust criterion estimator. | Parameters: | * **endog** (*array-like*) – 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 `statsmodels.tools.add_constant`. * **M** ([statsmodels.robust.norms.RobustNorm](statsmodels.robust.norms.robustnorm#statsmodels.robust.norms.RobustNorm "statsmodels.robust.norms.RobustNorm")*,* *optional*) – The robust criterion function for downweighting outliers. The current options are LeastSquares, HuberT, RamsayE, AndrewWave, TrimmedMean, Hampel, and TukeyBiweight. The default is HuberT(). See statsmodels.robust.norms for more information. * **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.’ | #### Notes **Attributes** `df_model : float` The degrees of freedom of the model. The number of regressors p less one for the intercept. Note that the reported model degrees of freedom does not count the intercept as a regressor, though the model is assumed to have an intercept. `df_resid : float` The residual degrees of freedom. The number of observations n less the number of regressors p. Note that here p does include the intercept as using a degree of freedom. `endog : array` See above. Note that endog is a reference to the data so that if data is already an array and it is changed, then `endog` changes as well. `exog : array` See above. Note that endog is a reference to the data so that if data is already an array and it is changed, then `endog` changes as well. `M : statsmodels.robust.norms.RobustNorm` See above. Robust estimator instance instantiated. `nobs : float` The number of observations n `pinv_wexog : array` The pseudoinverse of the design / exogenous data array. Note that RLM has no whiten method, so this is just the pseudo inverse of the design. `normalized_cov_params : array` The p x p normalized covariance of the design / exogenous data. This is approximately equal to (X.T X)^(-1) #### Examples ``` >>> import statsmodels.api as sm >>> data = sm.datasets.stackloss.load() >>> data.exog = sm.add_constant(data.exog) >>> rlm_model = sm.RLM(data.endog, data.exog, M=sm.robust.norms.HuberT()) ``` ``` >>> rlm_results = rlm_model.fit() >>> rlm_results.params array([ 0.82938433, 0.92606597, -0.12784672, -41.02649835]) >>> rlm_results.bse array([ 0.11100521, 0.30293016, 0.12864961, 9.79189854]) >>> rlm_results_HC2 = rlm_model.fit(cov="H2") >>> rlm_results_HC2.params array([ 0.82938433, 0.92606597, -0.12784672, -41.02649835]) >>> rlm_results_HC2.bse array([ 0.11945975, 0.32235497, 0.11796313, 9.08950419]) >>> mod = sm.RLM(data.endog, data.exog, M=sm.robust.norms.Hampel()) >>> rlm_hamp_hub = mod.fit(scale_est=sm.robust.scale.HuberScale()) >>> rlm_hamp_hub.params array([ 0.73175452, 1.25082038, -0.14794399, -40.27122257]) ``` #### Methods | | | | --- | --- | | [`deviance`](statsmodels.robust.robust_linear_model.rlm.deviance#statsmodels.robust.robust_linear_model.RLM.deviance "statsmodels.robust.robust_linear_model.RLM.deviance")(tmp\_results) | Returns the (unnormalized) log-likelihood from the M estimator. | | [`fit`](statsmodels.robust.robust_linear_model.rlm.fit#statsmodels.robust.robust_linear_model.RLM.fit "statsmodels.robust.robust_linear_model.RLM.fit")([maxiter, tol, scale\_est, init, cov, …]) | Fits the model using iteratively reweighted least squares. | | [`from_formula`](statsmodels.robust.robust_linear_model.rlm.from_formula#statsmodels.robust.robust_linear_model.RLM.from_formula "statsmodels.robust.robust_linear_model.RLM.from_formula")(formula, data[, subset, drop\_cols]) | Create a Model from a formula and dataframe. | | [`hessian`](statsmodels.robust.robust_linear_model.rlm.hessian#statsmodels.robust.robust_linear_model.RLM.hessian "statsmodels.robust.robust_linear_model.RLM.hessian")(params) | The Hessian matrix of the model | | [`information`](statsmodels.robust.robust_linear_model.rlm.information#statsmodels.robust.robust_linear_model.RLM.information "statsmodels.robust.robust_linear_model.RLM.information")(params) | Fisher information matrix of model | | [`initialize`](statsmodels.robust.robust_linear_model.rlm.initialize#statsmodels.robust.robust_linear_model.RLM.initialize "statsmodels.robust.robust_linear_model.RLM.initialize")() | Initialize (possibly re-initialize) a Model instance. | | [`loglike`](statsmodels.robust.robust_linear_model.rlm.loglike#statsmodels.robust.robust_linear_model.RLM.loglike "statsmodels.robust.robust_linear_model.RLM.loglike")(params) | Log-likelihood of model. | | [`predict`](statsmodels.robust.robust_linear_model.rlm.predict#statsmodels.robust.robust_linear_model.RLM.predict "statsmodels.robust.robust_linear_model.RLM.predict")(params[, exog]) | Return linear predicted values from a design matrix. | | [`score`](statsmodels.robust.robust_linear_model.rlm.score#statsmodels.robust.robust_linear_model.RLM.score "statsmodels.robust.robust_linear_model.RLM.score")(params) | Score vector of model. | #### Attributes | | | | --- | --- | | `endog_names` | Names of endogenous variables | | `exog_names` | Names of exogenous variables | statsmodels statsmodels.discrete.discrete_model.DiscreteModel.from_formula statsmodels.discrete.discrete\_model.DiscreteModel.from\_formula ================================================================ `classmethod DiscreteModel.from_formula(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** (*extra arguments*) – These are passed to the model * **kwargs** (*extra keyword arguments*) – These are passed to the model with one exception. The `eval_env` keyword is passed to patsy. It can be either a [`patsy.EvalEnvironment`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.EvalEnvironment "(in patsy v0.5.0+dev)") 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** | | Return type: | 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 statsmodels.tsa.statespace.kalman_filter.KalmanFilter.loglikeobs statsmodels.tsa.statespace.kalman\_filter.KalmanFilter.loglikeobs ================================================================= `KalmanFilter.loglikeobs(**kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/kalman_filter.html#KalmanFilter.loglikeobs) Calculate the loglikelihood for each observation associated with the statespace model. | Parameters: | **\*\*kwargs** – Additional keyword arguments to pass to the Kalman filter. See `KalmanFilter.filter` for more details. | #### Notes If `loglikelihood_burn` is positive, then the entries in the returned loglikelihood vector are set to be zero for those initial time periods. | Returns: | **loglike** – Array of loglikelihood values for each observation. | | Return type: | array of float | statsmodels statsmodels.tsa.statespace.varmax.VARMAXResults.conf_int statsmodels.tsa.statespace.varmax.VARMAXResults.conf\_int ========================================================= `VARMAXResults.conf_int(alpha=0.05, cols=None, method='default')` Returns the confidence interval of the fitted parameters. | Parameters: | * **alpha** (*float**,* *optional*) – The significance level for the confidence interval. ie., The default `alpha` = .05 returns a 95% confidence interval. * **cols** (*array-like**,* *optional*) – `cols` specifies which confidence intervals to return * **method** (*string*) – Not Implemented Yet Method to estimate the confidence\_interval. “Default” : uses self.bse which is based on inverse Hessian for MLE “hjjh” : “jac” : “boot-bse” “boot\_quant” “profile” | | Returns: | **conf\_int** – Each row contains [lower, upper] limits of the confidence interval for the corresponding parameter. The first column contains all lower, the second column contains all upper limits. | | Return type: | array | #### Examples ``` >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> results.conf_int() array([[-5496529.48322745, -1467987.78596704], [ -177.02903529, 207.15277984], [ -0.1115811 , 0.03994274], [ -3.12506664, -0.91539297], [ -1.5179487 , -0.54850503], [ -0.56251721, 0.460309 ], [ 798.7875153 , 2859.51541392]]) ``` ``` >>> results.conf_int(cols=(2,3)) array([[-0.1115811 , 0.03994274], [-3.12506664, -0.91539297]]) ``` #### Notes The confidence interval is based on the standard normal distribution. Models wish to use a different distribution should overwrite this method. statsmodels statsmodels.tsa.ar_model.AR.initialize statsmodels.tsa.ar\_model.AR.initialize ======================================= `AR.initialize()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/ar_model.html#AR.initialize) Initialize (possibly re-initialize) a Model instance. For instance, the design matrix of a linear model may change and some things must be recomputed. statsmodels statsmodels.tsa.holtwinters.SimpleExpSmoothing.from_formula statsmodels.tsa.holtwinters.SimpleExpSmoothing.from\_formula ============================================================ `classmethod SimpleExpSmoothing.from_formula(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** (*extra arguments*) – These are passed to the model * **kwargs** (*extra keyword arguments*) – These are passed to the model with one exception. The `eval_env` keyword is passed to patsy. It can be either a [`patsy.EvalEnvironment`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.EvalEnvironment "(in patsy v0.5.0+dev)") 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** | | Return type: | 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 statsmodels.miscmodels.count.PoissonZiGMLE.reduceparams statsmodels.miscmodels.count.PoissonZiGMLE.reduceparams ======================================================= `PoissonZiGMLE.reduceparams(params)` statsmodels statsmodels.stats.contingency_tables.mcnemar statsmodels.stats.contingency\_tables.mcnemar ============================================= `statsmodels.stats.contingency_tables.mcnemar(table, exact=True, correction=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#mcnemar) McNemar test of homogeneity. | Parameters: | * **table** (*array-like*) – A square contingency table. * **exact** (*bool*) – If exact is true, then the binomial distribution will be used. If exact is false, then the chisquare distribution will be used, which is the approximation to the distribution of the test statistic for large sample sizes. * **correction** (*bool*) – If true, then a continuity correction is used for the chisquare distribution (if exact is false.) | | Returns: | * *A bunch with attributes* * **statistic** (*float or int, array*) – The test statistic is the chisquare statistic if exact is false. If the exact binomial distribution is used, then this contains the min(n1, n2), where n1, n2 are cases that are zero in one sample but one in the other sample. * **pvalue** (*float or array*) – p-value of the null hypothesis of equal marginal distributions. | #### Notes This is a special case of Cochran’s Q test, and of the homogeneity test. The results when the chisquare distribution is used are identical, except for continuity correction. statsmodels statsmodels.genmod.families.links.identity.deriv2 statsmodels.genmod.families.links.identity.deriv2 ================================================= `identity.deriv2(p)` Second derivative of the power transform | Parameters: | **p** (*array-like*) – Mean parameters | | Returns: | **g’‘(p)** – Second derivative of the power transform of `p` | | Return type: | array | #### Notes g’‘(`p`) = `power` \* (`power` - 1) \* `p`**(`power` - 2) statsmodels statsmodels.tsa.vector_ar.vecm.VECMResults.llf statsmodels.tsa.vector\_ar.vecm.VECMResults.llf =============================================== `VECMResults.llf()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/vecm.html#VECMResults.llf) Compute the VECM’s loglikelihood. statsmodels statsmodels.robust.norms.Hampel.rho statsmodels.robust.norms.Hampel.rho =================================== `Hampel.rho(z)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/norms.html#Hampel.rho) The robust criterion function for Hampel’s estimator | Parameters: | **z** (*array-like*) – 1d array | | Returns: | **rho** – rho(z) = (1/2.)\*z\*\*2 for |z| <= arho(z) = a\*|z| - 1/2.\*a\*\*2 for a < |z| <= b rho(z) = a\*(c\*|z|-(1/2.)\*z\*\*2)/(c-b) for b < |z| <= c rho(z) = a\*(b + c - a) for |z| > c | | Return type: | array | statsmodels statsmodels.genmod.families.family.InverseGaussian.weights statsmodels.genmod.families.family.InverseGaussian.weights ========================================================== `InverseGaussian.weights(mu)` Weights for IRLS steps | Parameters: | **mu** (*array-like*) – The transformed mean response variable in the exponential family | | Returns: | **w** – The weights for the IRLS steps | | Return type: | array | #### Notes \[w = 1 / (g'(\mu)^2 \* Var(\mu))\] statsmodels statsmodels.stats.contingency_tables.SquareTable.fittedvalues statsmodels.stats.contingency\_tables.SquareTable.fittedvalues ============================================================== `SquareTable.fittedvalues()` statsmodels statsmodels.stats.power.TTestIndPower statsmodels.stats.power.TTestIndPower ===================================== `class statsmodels.stats.power.TTestIndPower(**kwds)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/power.html#TTestIndPower) Statistical Power calculations for t-test for two independent sample currently only uses pooled variance #### Methods | | | | --- | --- | | [`plot_power`](statsmodels.stats.power.ttestindpower.plot_power#statsmodels.stats.power.TTestIndPower.plot_power "statsmodels.stats.power.TTestIndPower.plot_power")([dep\_var, nobs, effect\_size, …]) | plot power with number of observations or effect size on x-axis | | [`power`](statsmodels.stats.power.ttestindpower.power#statsmodels.stats.power.TTestIndPower.power "statsmodels.stats.power.TTestIndPower.power")(effect\_size, nobs1, alpha[, ratio, …]) | Calculate the power of a t-test for two independent sample | | [`solve_power`](statsmodels.stats.power.ttestindpower.solve_power#statsmodels.stats.power.TTestIndPower.solve_power "statsmodels.stats.power.TTestIndPower.solve_power")([effect\_size, nobs1, alpha, …]) | solve for any one parameter of the power of a two sample t-test |
programming_docs
statsmodels statsmodels.stats.weightstats.DescrStatsW.sumsquares statsmodels.stats.weightstats.DescrStatsW.sumsquares ==================================================== `DescrStatsW.sumsquares()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/weightstats.html#DescrStatsW.sumsquares) weighted sum of squares of demeaned data statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.save statsmodels.tsa.statespace.dynamic\_factor.DynamicFactorResults.save ==================================================================== `DynamicFactorResults.save(fname, remove_data=False)` save a pickle of this instance | Parameters: | * **fname** (*string* *or* *filehandle*) – fname can be a string to a file path or filename, or a filehandle. * **remove\_data** (*bool*) – If False (default), then the instance is pickled without changes. If True, then all arrays with length nobs are set to None before pickling. See the remove\_data method. In some cases not all arrays will be set to None. | #### Notes If remove\_data is true and the model result does not implement a remove\_data method then this will raise an exception. statsmodels statsmodels.sandbox.distributions.extras.ACSkewT_gen.fit_loc_scale statsmodels.sandbox.distributions.extras.ACSkewT\_gen.fit\_loc\_scale ===================================================================== `ACSkewT_gen.fit_loc_scale(data, *args)` Estimate loc and scale parameters from data using 1st and 2nd moments. | Parameters: | * **data** (*array\_like*) – Data to fit. * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information). | | Returns: | * **Lhat** (*float*) – Estimated location parameter for the data. * **Shat** (*float*) – Estimated scale parameter for the data. | statsmodels statsmodels.discrete.discrete_model.MultinomialResults.load statsmodels.discrete.discrete\_model.MultinomialResults.load ============================================================ `classmethod MultinomialResults.load(fname)` load a pickle, (class method) | Parameters: | **fname** (*string* *or* *filehandle*) – fname can be a string to a file path or filename, or a filehandle. | | Returns: | | | Return type: | unpickled instance | statsmodels statsmodels.genmod.bayes_mixed_glm.BinomialBayesMixedGLM.fit_map statsmodels.genmod.bayes\_mixed\_glm.BinomialBayesMixedGLM.fit\_map =================================================================== `BinomialBayesMixedGLM.fit_map(method='BFGS', minim_opts=None)` Construct the Laplace approximation to the posterior distribution. | Parameters: | * **method** (*string*) – Optimization method for finding the posterior mode. * **minim\_opts** (*dict-like*) – Options passed to scipy.minimize. | | Returns: | | | Return type: | BayesMixedGLMResults instance. | statsmodels statsmodels.sandbox.distributions.extras.NormExpan_gen.isf statsmodels.sandbox.distributions.extras.NormExpan\_gen.isf =========================================================== `NormExpan_gen.isf(q, *args, **kwds)` Inverse survival function (inverse of `sf`) at q of the given RV. | Parameters: | * **q** (*array\_like*) – upper tail probability * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **x** – Quantile corresponding to the upper tail probability q. | | Return type: | ndarray or scalar | statsmodels statsmodels.regression.linear_model.OLS.information statsmodels.regression.linear\_model.OLS.information ==================================================== `OLS.information(params)` Fisher information matrix of model Returns -Hessian of loglike evaluated at params. statsmodels statsmodels.tsa.statespace.varmax.VARMAXResults.loglikelihood_burn statsmodels.tsa.statespace.varmax.VARMAXResults.loglikelihood\_burn =================================================================== `VARMAXResults.loglikelihood_burn()` (float) The number of observations during which the likelihood is not evaluated. statsmodels statsmodels.sandbox.distributions.transformed.LogTransf_gen.nnlf statsmodels.sandbox.distributions.transformed.LogTransf\_gen.nnlf ================================================================= `LogTransf_gen.nnlf(theta, x)` Return negative loglikelihood function. #### Notes This is `-sum(log pdf(x, theta), axis=0)` where `theta` are the parameters (including loc and scale). statsmodels statsmodels.sandbox.regression.try_catdata.labelmeanfilter_str statsmodels.sandbox.regression.try\_catdata.labelmeanfilter\_str ================================================================ `statsmodels.sandbox.regression.try_catdata.labelmeanfilter_str(ys, x)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/try_catdata.html#labelmeanfilter_str) statsmodels statsmodels.tsa.statespace.sarimax.SARIMAXResults.aic statsmodels.tsa.statespace.sarimax.SARIMAXResults.aic ===================================================== `SARIMAXResults.aic()` (float) Akaike Information Criterion statsmodels statsmodels.stats.diagnostic.breaks_cusumolsresid statsmodels.stats.diagnostic.breaks\_cusumolsresid ================================================== `statsmodels.stats.diagnostic.breaks_cusumolsresid(olsresidual, ddof=0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/diagnostic.html#breaks_cusumolsresid) cusum test for parameter stability based on ols residuals | Parameters: | * **olsresiduals** (*ndarray*) – array of residuals from an OLS estimation * **ddof** (*int*) – number of parameters in the OLS estimation, used as degrees of freedom correction for error variance. | | Returns: | * **sup\_b** (*float*) – test statistic, maximum of absolute value of scaled cumulative OLS residuals * **pval** (*float*) – Probability of observing the data under the null hypothesis of no structural change, based on asymptotic distribution which is a Brownian Bridge * **crit** (*list*) – tabulated critical values, for alpha = 1%, 5% and 10% | #### Notes tested agains R:strucchange Not clear: Assumption 2 in Ploberger, Kramer assumes that exog x have asymptotically zero mean, x.mean(0) = [1, 0, 0, …, 0] Is this really necessary? I don’t see how it can affect the test statistic under the null. It does make a difference under the alternative. Also, the asymptotic distribution of test statistic depends on this. From examples it looks like there is little power for standard cusum if exog (other than constant) have mean zero. #### References Ploberger, Werner, and Walter Kramer. “The Cusum Test with Ols Residuals.” Econometrica 60, no. 2 (March 1992): 271-285. statsmodels statsmodels.nonparametric.kernel_regression.KernelCensoredReg.cv_loo statsmodels.nonparametric.kernel\_regression.KernelCensoredReg.cv\_loo ====================================================================== `KernelCensoredReg.cv_loo(bw, func)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/nonparametric/kernel_regression.html#KernelCensoredReg.cv_loo) The cross-validation function with leave-one-out estimator | Parameters: | * **bw** (*array\_like*) – Vector of bandwidth values * **func** (*callable function*) – Returns the estimator of g(x). Can be either `_est_loc_constant` (local constant) or `_est_loc_linear` (local\_linear). | | Returns: | **L** – The value of the CV function | | Return type: | float | #### Notes Calculates the cross-validation least-squares function. This function is minimized by compute\_bw to calculate the optimal value of bw For details see p.35 in [2] \[CV(h)=n^{-1}\sum\_{i=1}^{n}(Y\_{i}-g\_{-i}(X\_{i}))^{2}\] where \(g\_{-i}(X\_{i})\) is the leave-one-out estimator of g(X) and \(h\) is the vector of bandwidths statsmodels statsmodels.tsa.stattools.acf statsmodels.tsa.stattools.acf ============================= `statsmodels.tsa.stattools.acf(x, unbiased=False, nlags=40, qstat=False, fft=False, alpha=None, missing='none')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/stattools.html#acf) Autocorrelation function for 1d arrays. | Parameters: | * **x** (*array*) – Time series data * **unbiased** (*bool*) – If True, then denominators for autocovariance are n-k, otherwise n * **nlags** (*int**,* *optional*) – Number of lags to return autocorrelation for. * **qstat** (*bool**,* *optional*) – If True, returns the Ljung-Box q statistic for each autocorrelation coefficient. See q\_stat for more information. * **fft** (*bool**,* *optional*) – If True, computes the ACF via FFT. * **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. * **missing** (*str**,* *optional*) – A string in [‘none’, ‘raise’, ‘conservative’, ‘drop’] specifying how the NaNs are to be treated. | | Returns: | * **acf** (*array*) – autocorrelation function * **confint** (*array, optional*) – Confidence intervals for the ACF. Returned if confint is not None. * **qstat** (*array, optional*) – The Ljung-Box Q-Statistic. Returned if q\_stat is True. * **pvalues** (*array, optional*) – The p-values associated with the Q-statistics. Returned if q\_stat is True. | #### Notes The acf at lag 0 (ie., 1) is returned. This is based np.correlate which does full convolution. For very long time series it is recommended to use fft convolution instead. If unbiased is true, the denominator for the autocovariance is adjusted but the autocorrelation is not an unbiased estimtor. #### References | | | | --- | --- | | [\*] | Parzen, E., 1963. On spectral analysis with missing observations and amplitude modulation. Sankhya: The Indian Journal of Statistics, Series A, pp.383-392. | statsmodels statsmodels.stats.contingency_tables.SquareTable.homogeneity statsmodels.stats.contingency\_tables.SquareTable.homogeneity ============================================================= `SquareTable.homogeneity(method='stuart_maxwell')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#SquareTable.homogeneity) Compare row and column marginal distributions. | Parameters: | * **method** (*string*) – Either ‘stuart\_maxwell’ or ‘bhapkar’, leading to two different estimates of the covariance matrix for the estimated difference between the row margins and the column margins. * **a bunch with attributes** (*Returns*) – * **statistic** (*float*) – The chi^2 test statistic * **pvalue** (*float*) – The p-value of the test statistic * **df** (*integer*) – The degrees of freedom of the reference distribution | #### Notes For a 2x2 table this is equivalent to McNemar’s test. More generally the procedure tests the null hypothesis that the marginal distribution of the row factor is equal to the marginal distribution of the column factor. For this to be meaningful, the two factors must have the same sample space (i.e. the same categories). statsmodels statsmodels.discrete.discrete_model.ProbitResults.resid_dev statsmodels.discrete.discrete\_model.ProbitResults.resid\_dev ============================================================= `ProbitResults.resid_dev()` Deviance residuals #### Notes Deviance residuals are defined \[d\_j = \pm\left(2\left[Y\_j\ln\left(\frac{Y\_j}{M\_jp\_j}\right) + (M\_j - Y\_j\ln\left(\frac{M\_j-Y\_j}{M\_j(1-p\_j)} \right) \right] \right)^{1/2}\] where \(p\_j = cdf(X\beta)\) and \(M\_j\) is the total number of observations sharing the covariate pattern \(j\). For now \(M\_j\) is always set to 1. statsmodels statsmodels.discrete.discrete_model.ProbitResults.fittedvalues statsmodels.discrete.discrete\_model.ProbitResults.fittedvalues =============================================================== `ProbitResults.fittedvalues()` statsmodels statsmodels.miscmodels.count.PoissonGMLE.predict statsmodels.miscmodels.count.PoissonGMLE.predict ================================================ `PoissonGMLE.predict(params, exog=None, *args, **kwargs)` After a model has been fit predict returns the fitted values. This is a placeholder intended to be overwritten by individual models. statsmodels statsmodels.discrete.discrete_model.Poisson.fit statsmodels.discrete.discrete\_model.Poisson.fit ================================================ `Poisson.fit(start_params=None, method='newton', maxiter=35, full_output=1, disp=1, callback=None, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#Poisson.fit) Fit the model using maximum likelihood. The rest of the docstring is from statsmodels.base.model.LikelihoodModel.fit Fit method for likelihood based models | Parameters: | * **start\_params** (*array-like**,* *optional*) – Initial guess of the solution for the loglikelihood maximization. The default is an array of zeros. * **method** (*str**,* *optional*) – The `method` determines which solver from `scipy.optimize` is used, and it can be chosen from among the following strings: + ’newton’ for Newton-Raphson, ‘nm’ for Nelder-Mead + ’bfgs’ for Broyden-Fletcher-Goldfarb-Shanno (BFGS) + ’lbfgs’ for limited-memory BFGS with optional box constraints + ’powell’ for modified Powell’s method + ’cg’ for conjugate gradient + ’ncg’ for Newton-conjugate gradient + ’basinhopping’ for global basin-hopping solver + ’minimize’ for generic wrapper of scipy minimize (BFGS by default)The explicit arguments in `fit` are passed to the solver, with the exception of the basin-hopping solver. Each solver has several optional arguments that are not the same across solvers. See the notes section below (or scipy.optimize) for the available arguments and for the list of explicit arguments that the basin-hopping solver supports. * **maxiter** (*int**,* *optional*) – The maximum number of iterations to perform. * **full\_output** (*bool**,* *optional*) – Set to True to have all available output in the Results object’s mle\_retvals attribute. The output is dependent on the solver. See LikelihoodModelResults notes section for more information. * **disp** (*bool**,* *optional*) – Set to True to print convergence messages. * **fargs** (*tuple**,* *optional*) – Extra arguments passed to the likelihood function, i.e., loglike(x,\*args) * **callback** (*callable callback**(**xk**)**,* *optional*) – Called after each iteration, as callback(xk), where xk is the current parameter vector. * **retall** (*bool**,* *optional*) – Set to True to return list of solutions at each iteration. Available in Results object’s mle\_retvals attribute. * **skip\_hessian** (*bool**,* *optional*) – If False (default), then the negative inverse hessian is calculated after the optimization. If True, then the hessian will not be calculated. However, it will be available in methods that use the hessian in the optimization (currently only with `“newton”`). * **kwargs** (*keywords*) – All kwargs are passed to the chosen solver with one exception. The following keyword controls what happens after the fit: ``` warn_convergence : bool, optional If True, checks the model for the converged flag. If the converged flag is False, a ConvergenceWarning is issued. ``` | #### Notes The ‘basinhopping’ solver ignores `maxiter`, `retall`, `full_output` explicit arguments. Optional arguments for solvers (see returned Results.mle\_settings): ``` 'newton' tol : float Relative error in params acceptable for convergence. 'nm' -- Nelder Mead xtol : float Relative error in params acceptable for convergence ftol : float Relative error in loglike(params) acceptable for convergence maxfun : int Maximum number of function evaluations to make. 'bfgs' gtol : float Stop when norm of gradient is less than gtol. norm : float Order of norm (np.Inf is max, -np.Inf is min) epsilon If fprime is approximated, use this value for the step size. Only relevant if LikelihoodModel.score is None. 'lbfgs' m : int This many terms are used for the Hessian approximation. factr : float A stop condition that is a variant of relative error. pgtol : float A stop condition that uses the projected gradient. epsilon If fprime is approximated, use this value for the step size. Only relevant if LikelihoodModel.score is None. maxfun : int Maximum number of function evaluations to make. bounds : sequence (min, max) pairs for each element in x, defining the bounds on that parameter. Use None for one of min or max when there is no bound in that direction. 'cg' gtol : float Stop when norm of gradient is less than gtol. norm : float Order of norm (np.Inf is max, -np.Inf is min) epsilon : float If fprime is approximated, use this value for the step size. Can be scalar or vector. Only relevant if Likelihoodmodel.score is None. 'ncg' fhess_p : callable f'(x,*args) Function which computes the Hessian of f times an arbitrary vector, p. Should only be supplied if LikelihoodModel.hessian is None. avextol : float Stop when the average relative error in the minimizer falls below this amount. epsilon : float or ndarray If fhess is approximated, use this value for the step size. Only relevant if Likelihoodmodel.hessian is None. 'powell' xtol : float Line-search error tolerance ftol : float Relative error in loglike(params) for acceptable for convergence. maxfun : int Maximum number of function evaluations to make. start_direc : ndarray Initial direction set. 'basinhopping' niter : integer The number of basin hopping iterations. niter_success : integer Stop the run if the global minimum candidate remains the same for this number of iterations. T : float The "temperature" parameter for the accept or reject criterion. Higher "temperatures" mean that larger jumps in function value will be accepted. For best results `T` should be comparable to the separation (in function value) between local minima. stepsize : float Initial step size for use in the random displacement. interval : integer The interval for how often to update the `stepsize`. minimizer : dict Extra keyword arguments to be passed to the minimizer `scipy.optimize.minimize()`, for example 'method' - the minimization method (e.g. 'L-BFGS-B'), or 'tol' - the tolerance for termination. Other arguments are mapped from explicit argument of `fit`: - `args` <- `fargs` - `jac` <- `score` - `hess` <- `hess` 'minimize' min_method : str, optional Name of minimization method to use. Any method specific arguments can be passed directly. For a list of methods and their arguments, see documentation of `scipy.optimize.minimize`. If no method is specified, then BFGS is used. ``` statsmodels statsmodels.tsa.arima_process.index2lpol statsmodels.tsa.arima\_process.index2lpol ========================================= `statsmodels.tsa.arima_process.index2lpol(coeffs, index)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_process.html#index2lpol) Expand coefficients to lag poly | Parameters: | * **coeffs** (*array*) – non-zero coefficients of lag polynomial * **index** (*array*) – index (lags) of lag polynomial with non-zero elements | | Returns: | **ar** – coefficients of lag polynomial | | Return type: | array\_like |
programming_docs
statsmodels statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.initialize statsmodels.discrete.count\_model.ZeroInflatedGeneralizedPoissonResults.initialize ================================================================================== `ZeroInflatedGeneralizedPoissonResults.initialize(model, params, **kwd)` statsmodels statsmodels.tools.numdiff.approx_hess2 statsmodels.tools.numdiff.approx\_hess2 ======================================= `statsmodels.tools.numdiff.approx_hess2(x, f, epsilon=None, args=(), kwargs={}, return_grad=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tools/numdiff.html#approx_hess2) Calculate Hessian with finite difference derivative approximation | Parameters: | * **x** (*array\_like*) – value at which function derivative is evaluated * **f** (*function*) – function of one array f(x, `*args`, `**kwargs`) * **epsilon** (*float* *or* *array-like**,* *optional*) – Stepsize used, if None, then stepsize is automatically chosen according to EPS\*\*(1/3)\*x. * **args** (*tuple*) – Arguments for function `f`. * **kwargs** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")) – Keyword arguments for function `f`. * **return\_grad** (*bool*) – Whether or not to also return the gradient | | Returns: | * **hess** (*ndarray*) – array of partial second derivatives, Hessian * **grad** (*nparray*) – Gradient if return\_grad == True | #### Notes Equation (8) in Ridout. Computes the Hessian as: ``` 1/(2*d_j*d_k) * ((f(x + d[j]*e[j] + d[k]*e[k]) - f(x + d[j]*e[j])) - (f(x + d[k]*e[k]) - f(x)) + (f(x - d[j]*e[j] - d[k]*e[k]) - f(x + d[j]*e[j])) - (f(x - d[k]*e[k]) - f(x))) ``` where e[j] is a vector with element j == 1 and the rest are zero and d[i] is epsilon[i]. #### References Ridout, M.S. (2009) Statistical applications of the complex-step method of numerical differentiation. The American Statistician, 63, 66-74 statsmodels statsmodels.discrete.discrete_model.MNLogit.initialize statsmodels.discrete.discrete\_model.MNLogit.initialize ======================================================= `MNLogit.initialize()` Preprocesses the data for MNLogit. statsmodels statsmodels.sandbox.stats.multicomp.MultiComparison.allpairtest statsmodels.sandbox.stats.multicomp.MultiComparison.allpairtest =============================================================== `MultiComparison.allpairtest(testfunc, alpha=0.05, method='bonf', pvalidx=1)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/multicomp.html#MultiComparison.allpairtest) run a pairwise test on all pairs with multiple test correction The statistical test given in testfunc is calculated for all pairs and the p-values are adjusted by methods in multipletests. The p-value correction is generic and based only on the p-values, and does not take any special structure of the hypotheses into account. | Parameters: | * **testfunc** (*function*) – A test function for two (independent) samples. It is assumed that the return value on position pvalidx is the p-value. * **alpha** (*float*) – familywise error rate * **method** (*string*) – This specifies the method for the p-value correction. Any method of multipletests is possible. * **pvalidx** (*int* *(**default: 1**)*) – position of the p-value in the return of testfunc | | Returns: | * **sumtab** (*SimpleTable instance*) – summary table for printing * **errors** (*TODO: check if this is still wrong, I think it’s fixed.*) * *results from multipletests are in different order* * *pval\_corrected can be larger than 1 ???* | statsmodels statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression.loglike statsmodels.tsa.regime\_switching.markov\_autoregression.MarkovAutoregression.loglike ===================================================================================== `MarkovAutoregression.loglike(params, transformed=True)` Loglikelihood evaluation | Parameters: | * **params** (*array\_like*) – Array of parameters at which to evaluate the loglikelihood function. * **transformed** (*boolean**,* *optional*) – Whether or not `params` is already transformed. Default is True. | statsmodels statsmodels.miscmodels.tmodel.TLinearModel.expandparams statsmodels.miscmodels.tmodel.TLinearModel.expandparams ======================================================= `TLinearModel.expandparams(params)` expand to full parameter array when some parameters are fixed | Parameters: | **params** (*array*) – reduced parameter array | | Returns: | **paramsfull** – expanded parameter array where fixed parameters are included | | Return type: | array | #### Notes Calling this requires that self.fixed\_params and self.fixed\_paramsmask are defined. *developer notes:* This can be used in the log-likelihood to … this could also be replaced by a more general parameter transformation. statsmodels statsmodels.stats.contingency_tables.SquareTable statsmodels.stats.contingency\_tables.SquareTable ================================================= `class statsmodels.stats.contingency_tables.SquareTable(table, shift_zeros=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#SquareTable) Methods for analyzing a square contingency table. | Parameters: | * **table** (*array-like*) – A square contingency table, or DataFrame that is converted to a square form. * **shift\_zeros** (*boolean*) – If True and any cell count is zero, add 0.5 to all values in the table. * **methods should only be used when the rows and columns of the** (*These*) – * **have the same categories. If table is provided as a** (*table*) – * **DataFrame****,** **the row and column indices will be extended to** (*Pandas*) – * **a square table****,** **inserting zeros where a row** **or** **column is** (*create*) – * **Otherwise the table should be provided in a square form****,** (*missing.*) – * **the** **(****implicit****)** **row and column categories appearing in the** (*with*) – * **order.** (*same*) – | #### Methods | | | | --- | --- | | [`chi2_contribs`](statsmodels.stats.contingency_tables.squaretable.chi2_contribs#statsmodels.stats.contingency_tables.SquareTable.chi2_contribs "statsmodels.stats.contingency_tables.SquareTable.chi2_contribs")() | | | [`cumulative_log_oddsratios`](statsmodels.stats.contingency_tables.squaretable.cumulative_log_oddsratios#statsmodels.stats.contingency_tables.SquareTable.cumulative_log_oddsratios "statsmodels.stats.contingency_tables.SquareTable.cumulative_log_oddsratios")() | | | [`cumulative_oddsratios`](statsmodels.stats.contingency_tables.squaretable.cumulative_oddsratios#statsmodels.stats.contingency_tables.SquareTable.cumulative_oddsratios "statsmodels.stats.contingency_tables.SquareTable.cumulative_oddsratios")() | | | [`fittedvalues`](statsmodels.stats.contingency_tables.squaretable.fittedvalues#statsmodels.stats.contingency_tables.SquareTable.fittedvalues "statsmodels.stats.contingency_tables.SquareTable.fittedvalues")() | | | [`from_data`](statsmodels.stats.contingency_tables.squaretable.from_data#statsmodels.stats.contingency_tables.SquareTable.from_data "statsmodels.stats.contingency_tables.SquareTable.from_data")(data[, shift\_zeros]) | Construct a Table object from data. | | [`homogeneity`](statsmodels.stats.contingency_tables.squaretable.homogeneity#statsmodels.stats.contingency_tables.SquareTable.homogeneity "statsmodels.stats.contingency_tables.SquareTable.homogeneity")([method]) | Compare row and column marginal distributions. | | [`independence_probabilities`](statsmodels.stats.contingency_tables.squaretable.independence_probabilities#statsmodels.stats.contingency_tables.SquareTable.independence_probabilities "statsmodels.stats.contingency_tables.SquareTable.independence_probabilities")() | | | [`local_log_oddsratios`](statsmodels.stats.contingency_tables.squaretable.local_log_oddsratios#statsmodels.stats.contingency_tables.SquareTable.local_log_oddsratios "statsmodels.stats.contingency_tables.SquareTable.local_log_oddsratios")() | | | [`local_oddsratios`](statsmodels.stats.contingency_tables.squaretable.local_oddsratios#statsmodels.stats.contingency_tables.SquareTable.local_oddsratios "statsmodels.stats.contingency_tables.SquareTable.local_oddsratios")() | | | [`marginal_probabilities`](statsmodels.stats.contingency_tables.squaretable.marginal_probabilities#statsmodels.stats.contingency_tables.SquareTable.marginal_probabilities "statsmodels.stats.contingency_tables.SquareTable.marginal_probabilities")() | | | [`resid_pearson`](statsmodels.stats.contingency_tables.squaretable.resid_pearson#statsmodels.stats.contingency_tables.SquareTable.resid_pearson "statsmodels.stats.contingency_tables.SquareTable.resid_pearson")() | | | [`standardized_resids`](statsmodels.stats.contingency_tables.squaretable.standardized_resids#statsmodels.stats.contingency_tables.SquareTable.standardized_resids "statsmodels.stats.contingency_tables.SquareTable.standardized_resids")() | | | [`summary`](statsmodels.stats.contingency_tables.squaretable.summary#statsmodels.stats.contingency_tables.SquareTable.summary "statsmodels.stats.contingency_tables.SquareTable.summary")([alpha, float\_format]) | Produce a summary of the analysis. | | [`symmetry`](statsmodels.stats.contingency_tables.squaretable.symmetry#statsmodels.stats.contingency_tables.SquareTable.symmetry "statsmodels.stats.contingency_tables.SquareTable.symmetry")([method]) | Test for symmetry of a joint distribution. | | [`test_nominal_association`](statsmodels.stats.contingency_tables.squaretable.test_nominal_association#statsmodels.stats.contingency_tables.SquareTable.test_nominal_association "statsmodels.stats.contingency_tables.SquareTable.test_nominal_association")() | Assess independence for nominal factors. | | [`test_ordinal_association`](statsmodels.stats.contingency_tables.squaretable.test_ordinal_association#statsmodels.stats.contingency_tables.SquareTable.test_ordinal_association "statsmodels.stats.contingency_tables.SquareTable.test_ordinal_association")([row\_scores, …]) | Assess independence between two ordinal variables. | statsmodels statsmodels.regression.recursive_ls.RecursiveLSResults.cov_params_robust_oim statsmodels.regression.recursive\_ls.RecursiveLSResults.cov\_params\_robust\_oim ================================================================================ `RecursiveLSResults.cov_params_robust_oim()` (array) The QMLE variance / covariance matrix. Computed using the method from Harvey (1989) as the evaluated hessian. statsmodels statsmodels.discrete.discrete_model.Probit.information statsmodels.discrete.discrete\_model.Probit.information ======================================================= `Probit.information(params)` Fisher information matrix of model Returns -Hessian of loglike evaluated at params. statsmodels statsmodels.tsa.arima_model.ARMAResults.fittedvalues statsmodels.tsa.arima\_model.ARMAResults.fittedvalues ===================================================== `ARMAResults.fittedvalues()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_model.html#ARMAResults.fittedvalues) statsmodels statsmodels.robust.robust_linear_model.RLM.predict statsmodels.robust.robust\_linear\_model.RLM.predict ==================================================== `RLM.predict(params, exog=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/robust_linear_model.html#RLM.predict) Return linear predicted values from a design matrix. | Parameters: | * **params** (*array-like**,* *optional after fit has been called*) – Parameters of a linear model * **exog** (*array-like**,* *optional.*) – Design / exogenous data. Model exog is used if None. | | Returns: | | | Return type: | An array of fitted values | #### Notes If the model as not yet been fit, params is not optional. statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.coefficients_of_determination statsmodels.tsa.statespace.dynamic\_factor.DynamicFactorResults.coefficients\_of\_determination =============================================================================================== `DynamicFactorResults.coefficients_of_determination()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/dynamic_factor.html#DynamicFactorResults.coefficients_of_determination) Coefficients of determination (\(R^2\)) from regressions of individual estimated factors on endogenous variables. | Returns: | **coefficients\_of\_determination** – A `k_endog` x `k_factors` array, where `coefficients_of_determination[i, j]` represents the \(R^2\) value from a regression of factor `j` and a constant on endogenous variable `i`. | | Return type: | array | #### Notes Although it can be difficult to interpret the estimated factor loadings and factors, it is often helpful to use the cofficients of determination from univariate regressions to assess the importance of each factor in explaining the variation in each endogenous variable. In models with many variables and factors, this can sometimes lend interpretation to the factors (for example sometimes one factor will load primarily on real variables and another on nominal variables). See also [`plot_coefficients_of_determination`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactorresults.plot_coefficients_of_determination#statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.plot_coefficients_of_determination "statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.plot_coefficients_of_determination") statsmodels statsmodels.discrete.discrete_model.NegativeBinomial.hessian statsmodels.discrete.discrete\_model.NegativeBinomial.hessian ============================================================= `NegativeBinomial.hessian(params)` The Hessian matrix of the model statsmodels statsmodels.sandbox.distributions.extras.ACSkewT_gen.moment statsmodels.sandbox.distributions.extras.ACSkewT\_gen.moment ============================================================ `ACSkewT_gen.moment(n, *args, **kwds)` n-th order non-central moment of distribution. | Parameters: | * **n** (*int**,* *n >= 1*) – Order of moment. * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information). * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | statsmodels statsmodels.discrete.discrete_model.MultinomialResults.t_test_pairwise statsmodels.discrete.discrete\_model.MultinomialResults.t\_test\_pairwise ========================================================================= `MultinomialResults.t_test_pairwise(term_name, method='hs', alpha=0.05, factor_labels=None)` perform pairwise t\_test with multiple testing corrected p-values This uses the formula design\_info encoding contrast matrix and should work for all encodings of a main effect. | Parameters: | * **result** (*result instance*) – The results of an estimated model with a categorical main effect. * **term\_name** (*str*) – name of the term for which pairwise comparisons are computed. Term names for categorical effects are created by patsy and correspond to the main part of the exog names. * **method** (*str* *or* *list of strings*) – multiple testing p-value correction, default is ‘hs’, see stats.multipletesting * **alpha** (*float*) – significance level for multiple testing reject decision. * **factor\_labels** (*None**,* *list of str*) – Labels for the factor levels used for pairwise labels. If not provided, then the labels from the formula design\_info are used. | | Returns: | **results** – The results are stored as attributes, the main attributes are the following two. Other attributes are added for debugging purposes or as background information.* result\_frame : pandas DataFrame with t\_test results and multiple testing corrected p-values. * contrasts : matrix of constraints of the null hypothesis in the t\_test. | | Return type: | instance of a simple Results class | #### Notes Status: experimental. Currently only checked for treatment coding with and without specified reference level. Currently there are no multiple testing corrected confidence intervals available. #### Examples ``` >>> res = ols("np.log(Days+1) ~ C(Weight) + C(Duration)", data).fit() >>> pw = res.t_test_pairwise("C(Weight)") >>> pw.result_frame coef std err t P>|t| Conf. Int. Low 2-1 0.632315 0.230003 2.749157 8.028083e-03 0.171563 3-1 1.302555 0.230003 5.663201 5.331513e-07 0.841803 3-2 0.670240 0.230003 2.914044 5.119126e-03 0.209488 Conf. Int. Upp. pvalue-hs reject-hs 2-1 1.093067 0.010212 True 3-1 1.763307 0.000002 True 3-2 1.130992 0.010212 True ``` statsmodels statsmodels.stats.contingency_tables.StratifiedTable.oddsratio_pooled_confint statsmodels.stats.contingency\_tables.StratifiedTable.oddsratio\_pooled\_confint ================================================================================ `StratifiedTable.oddsratio_pooled_confint(alpha=0.05, method='normal')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#StratifiedTable.oddsratio_pooled_confint) A confidence interval for the pooled odds ratio. | Parameters: | * **alpha** (*float*) – `1 - alpha` is the nominal coverage probability of the interval. * **method** (*string*) – The method for producing the confidence interval. Currently must be ‘normal’ which uses the normal approximation. | | Returns: | * **lcb** (*float*) – The lower confidence limit. * **ucb** (*float*) – The upper confidence limit. | statsmodels statsmodels.stats.weightstats.CompareMeans.ztost_ind statsmodels.stats.weightstats.CompareMeans.ztost\_ind ===================================================== `CompareMeans.ztost_ind(low, upp, usevar='pooled')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/weightstats.html#CompareMeans.ztost_ind) test of equivalence for two independent samples, based on z-test | Parameters: | * **upp** (*low**,*) – equivalence interval low < m1 - m2 < upp * **usevar** (*string**,* *'pooled'* *or* *'unequal'*) – If `pooled`, then the standard deviation of the samples is assumed to be the same. If `unequal`, then Welsh ttest with Satterthwait degrees of freedom is used | | Returns: | * **pvalue** (*float*) – pvalue of the non-equivalence test * **t1, pv1** (*tuple of floats*) – test statistic and pvalue for lower threshold test * **t2, pv2** (*tuple of floats*) – test statistic and pvalue for upper threshold test | statsmodels statsmodels.iolib.table.SimpleTable.reverse statsmodels.iolib.table.SimpleTable.reverse =========================================== `SimpleTable.reverse()` L.reverse() – reverse *IN PLACE* statsmodels statsmodels.tsa.arima_model.ARMAResults.aic statsmodels.tsa.arima\_model.ARMAResults.aic ============================================ `ARMAResults.aic()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_model.html#ARMAResults.aic) statsmodels statsmodels.tsa.arima_process.ArmaProcess.acf statsmodels.tsa.arima\_process.ArmaProcess.acf ============================================== `ArmaProcess.acf(lags=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_process.html#ArmaProcess.acf) Theoretical autocorrelation function of an ARMA process | Parameters: | * **ar** (*array\_like**,* *1d*) – coefficient for autoregressive lag polynomial, including zero lag * **ma** (*array\_like**,* *1d*) – coefficient for moving-average lag polynomial, including zero lag * **lags** (*int*) – number of terms (lags plus zero lag) to include in returned acf | | Returns: | **acf** – autocorrelation of ARMA process given by ar, ma | | Return type: | array | See also [`arma_acovf`](statsmodels.tsa.arima_process.arma_acovf#statsmodels.tsa.arima_process.arma_acovf "statsmodels.tsa.arima_process.arma_acovf"), [`acf`](#statsmodels.tsa.arima_process.ArmaProcess.acf "statsmodels.tsa.arima_process.ArmaProcess.acf"), [`acovf`](statsmodels.tsa.arima_process.armaprocess.acovf#statsmodels.tsa.arima_process.ArmaProcess.acovf "statsmodels.tsa.arima_process.ArmaProcess.acovf")
programming_docs
statsmodels statsmodels.sandbox.stats.multicomp.compare_ordered statsmodels.sandbox.stats.multicomp.compare\_ordered ==================================================== `statsmodels.sandbox.stats.multicomp.compare_ordered(vals, alpha)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/multicomp.html#compare_ordered) simple ordered sequential comparison of means `vals : array_like` means or rankmeans for independent groups incomplete, no return, not used yet statsmodels statsmodels.regression.quantile_regression.QuantRegResults.cov_params statsmodels.regression.quantile\_regression.QuantRegResults.cov\_params ======================================================================= `QuantRegResults.cov_params(r_matrix=None, column=None, scale=None, cov_p=None, other=None)` Returns the variance/covariance matrix. The variance/covariance matrix can be of a linear contrast of the estimates of params or all params multiplied by scale which will usually be an estimate of sigma^2. Scale is assumed to be a scalar. | Parameters: | * **r\_matrix** (*array-like*) – Can be 1d, or 2d. Can be used alone or with other. * **column** (*array-like**,* *optional*) – Must be used on its own. Can be 0d or 1d see below. * **scale** (*float**,* *optional*) – Can be specified or not. Default is None, which means that the scale argument is taken from the model. * **other** (*array-like**,* *optional*) – Can be used when r\_matrix is specified. | | Returns: | **cov** – covariance matrix of the parameter estimates or of linear combination of parameter estimates. See Notes. | | Return type: | ndarray | #### Notes (The below are assumed to be in matrix notation.) If no argument is specified returns the covariance matrix of a model `(scale)*(X.T X)^(-1)` If contrast is specified it pre and post-multiplies as follows `(scale) * r_matrix (X.T X)^(-1) r_matrix.T` If contrast and other are specified returns `(scale) * r_matrix (X.T X)^(-1) other.T` If column is specified returns `(scale) * (X.T X)^(-1)[column,column]` if column is 0d OR `(scale) * (X.T X)^(-1)[column][:,column]` if column is 1d statsmodels statsmodels.tsa.vector_ar.var_model.VARProcess.forecast statsmodels.tsa.vector\_ar.var\_model.VARProcess.forecast ========================================================= `VARProcess.forecast(y, steps, exog_future=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/var_model.html#VARProcess.forecast) Produce linear minimum MSE forecasts for desired number of steps ahead, using prior values y | Parameters: | * **y** (*ndarray* *(**p x k**)*) – * **steps** (*int*) – | | Returns: | **forecasts** | | Return type: | ndarray (steps x neqs) | #### Notes Lütkepohl pp 37-38 statsmodels statsmodels.regression.recursive_ls.RecursiveLS.filter statsmodels.regression.recursive\_ls.RecursiveLS.filter ======================================================= `RecursiveLS.filter(return_ssm=False, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/recursive_ls.html#RecursiveLS.filter) Kalman filtering | Parameters: | * **params** (*array\_like*) – Array of parameters at which to evaluate the loglikelihood function. * **transformed** (*boolean**,* *optional*) – Whether or not `params` is already transformed. Default is True. * **return\_ssm** (*boolean**,**optional*) – Whether or not to return only the state space output or a full results object. Default is to return a full results object. * **cov\_type** (*str**,* *optional*) – See `MLEResults.fit` for a description of covariance matrix types for results object. * **cov\_kwds** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)") *or* *None**,* *optional*) – See `MLEResults.get_robustcov_results` for a description required keywords for alternative covariance estimators * **\*\*kwargs** – Additional keyword arguments to pass to the Kalman filter. See `KalmanFilter.filter` for more details. | statsmodels statsmodels.robust.norms.HuberT.rho statsmodels.robust.norms.HuberT.rho =================================== `HuberT.rho(z)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/norms.html#HuberT.rho) The robust criterion function for Huber’s t. | Parameters: | **z** (*array-like*) – 1d array | | Returns: | **rho** – rho(z) = .5\*z\*\*2 for |z| <= trho(z) = |z|\*t - .5\*t\*\*2 for |z| > t | | Return type: | array | statsmodels statsmodels.discrete.discrete_model.CountModel.predict statsmodels.discrete.discrete\_model.CountModel.predict ======================================================= `CountModel.predict(params, exog=None, exposure=None, offset=None, linear=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#CountModel.predict) Predict response variable of a count model given exogenous variables. #### Notes If exposure is specified, then it will be logged by the method. The user does not need to log it first. statsmodels statsmodels.tools.numdiff.approx_fprime statsmodels.tools.numdiff.approx\_fprime ======================================== `statsmodels.tools.numdiff.approx_fprime(x, f, epsilon=None, args=(), kwargs={}, centered=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tools/numdiff.html#approx_fprime) Gradient of function, or Jacobian if function f returns 1d array | Parameters: | * **x** (*array*) – parameters at which the derivative is evaluated * **f** (*function*) – `f(*((x,)+args), **kwargs)` returning either one value or 1d array * **epsilon** (*float**,* *optional*) – Stepsize, if None, optimal stepsize is used. This is EPS\*\*(1/2)\*x for `centered` == False and EPS\*\*(1/3)\*x for `centered` == True. * **args** (*tuple*) – Tuple of additional arguments for function `f`. * **kwargs** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")) – Dictionary of additional keyword arguments for function `f`. * **centered** (*bool*) – Whether central difference should be returned. If not, does forward differencing. | | Returns: | **grad** – gradient or Jacobian | | Return type: | array | #### Notes If f returns a 1d array, it returns a Jacobian. If a 2d array is returned by f (e.g., with a value for each observation), it returns a 3d array with the Jacobian of each observation with shape xk x nobs x xk. I.e., the Jacobian of the first observation would be [:, 0, :] statsmodels statsmodels.stats.weightstats.CompareMeans.dof_satt statsmodels.stats.weightstats.CompareMeans.dof\_satt ==================================================== `CompareMeans.dof_satt()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/weightstats.html#CompareMeans.dof_satt) degrees of freedom of Satterthwaite for unequal variance statsmodels statsmodels.miscmodels.tmodel.TLinearModel.initialize statsmodels.miscmodels.tmodel.TLinearModel.initialize ===================================================== `TLinearModel.initialize()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/miscmodels/tmodel.html#TLinearModel.initialize) Initialize (possibly re-initialize) a Model instance. For instance, the design matrix of a linear model may change and some things must be recomputed. statsmodels statsmodels.miscmodels.tmodel.TLinearModel.loglike statsmodels.miscmodels.tmodel.TLinearModel.loglike ================================================== `TLinearModel.loglike(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/miscmodels/tmodel.html#TLinearModel.loglike) Log-likelihood of model. statsmodels statsmodels.graphics.tsaplots.quarter_plot statsmodels.graphics.tsaplots.quarter\_plot =========================================== `statsmodels.graphics.tsaplots.quarter_plot(x, dates=None, ylabel=None, ax=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/graphics/tsaplots.html#quarter_plot) Seasonal plot of quarterly data | Parameters: | * **x** (*array-like*) – Seasonal data to plot. If dates is None, x must be a pandas object with a PeriodIndex or DatetimeIndex with a monthly frequency. * **dates** (*array-like**,* *optional*) – If `x` is not a pandas object, then dates must be supplied. * **ylabel** (*str**,* *optional*) – The label for the y-axis. Will attempt to use the `name` attribute of the Series. * **ax** (*matplotlib.axes**,* *optional*) – Existing axes instance. | | Returns: | | | Return type: | matplotlib.Figure | statsmodels statsmodels.genmod.cov_struct.GlobalOddsRatio.covariance_matrix_solve statsmodels.genmod.cov\_struct.GlobalOddsRatio.covariance\_matrix\_solve ======================================================================== `GlobalOddsRatio.covariance_matrix_solve(expval, index, stdev, rhs)` Solves matrix equations of the form `covmat * soln = rhs` and returns the values of `soln`, where `covmat` is the covariance matrix represented by this class. | Parameters: | * **expval** (*array-like*) – The expected value of endog for each observed value in the group. * **index** (*integer*) – The group index. * **stdev** (*array-like*) – The standard deviation of endog for each observation in the group. * **rhs** (*list/tuple of array-like*) – A set of right-hand sides; each defines a matrix equation to be solved. | | Returns: | **soln** – The solutions to the matrix equations. | | Return type: | list/tuple of array-like | #### Notes Returns None if the solver fails. Some dependence structures do not use `expval` and/or `index` to determine the correlation matrix. Some families (e.g. binomial) do not use the `stdev` parameter when forming the covariance matrix. If the covariance matrix is singular or not SPD, it is projected to the nearest such matrix. These projection events are recorded in the fit\_history member of the GEE model. Systems of linear equations with the covariance matrix as the left hand side (LHS) are solved for different right hand sides (RHS); the LHS is only factorized once to save time. This is a default implementation, it can be reimplemented in subclasses to optimize the linear algebra according to the struture of the covariance matrix. statsmodels statsmodels.tsa.vector_ar.var_model.VARResults.test_causality statsmodels.tsa.vector\_ar.var\_model.VARResults.test\_causality ================================================================ `VARResults.test_causality(caused, causing=None, kind='f', signif=0.05)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/var_model.html#VARResults.test_causality) Test Granger causality | Parameters: | * **caused** (*int* *or* *str* *or* *sequence of int* *or* *str*) – If int or str, test whether the variable specified via this index (int) or name (str) is Granger-caused by the variable(s) specified by `causing`. If a sequence of int or str, test whether the corresponding variables are Granger-caused by the variable(s) specified by `causing`. * **causing** (*int* *or* *str* *or* *sequence of int* *or* *str* *or* *None**,* *default: None*) – If int or str, test whether the variable specified via this index (int) or name (str) is Granger-causing the variable(s) specified by `caused`. If a sequence of int or str, test whether the corresponding variables are Granger-causing the variable(s) specified by `caused`. If None, `causing` is assumed to be the complement of `caused`. * **kind** (*{'f'**,* *'wald'}*) – Perform F-test or Wald (chi-sq) test * **signif** (*float**,* *default 5%*) – Significance level for computing critical values for test, defaulting to standard 0.05 level | #### Notes Null hypothesis is that there is no Granger-causality for the indicated variables. The degrees of freedom in the F-test are based on the number of variables in the VAR system, that is, degrees of freedom are equal to the number of equations in the VAR times degree of freedom of a single equation. Test for Granger-causality as described in chapter 7.6.3 of [[1]](#id2). Test H0: “`causing` does not Granger-cause the remaining variables of the system” against H1: “`causing` is Granger-causal for the remaining variables”. | Returns: | **results** | | Return type: | [CausalityTestResults](statsmodels.tsa.vector_ar.hypothesis_test_results.causalitytestresults#statsmodels.tsa.vector_ar.hypothesis_test_results.CausalityTestResults "statsmodels.tsa.vector_ar.hypothesis_test_results.CausalityTestResults") | #### References | | | | --- | --- | | [[1]](#id1) | Lütkepohl, H. 2005. *New Introduction to Multiple Time Series Analysis*. Springer. | statsmodels statsmodels.sandbox.distributions.transformed.LogTransf_gen.logpdf statsmodels.sandbox.distributions.transformed.LogTransf\_gen.logpdf =================================================================== `LogTransf_gen.logpdf(x, *args, **kwds)` Log of the probability density function at x of the given RV. This uses a more numerically accurate calculation if available. | Parameters: | * **x** (*array\_like*) – quantiles * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **logpdf** – Log of the probability density function evaluated at x | | Return type: | array\_like | statsmodels statsmodels.tsa.statespace.varmax.VARMAX.fit statsmodels.tsa.statespace.varmax.VARMAX.fit ============================================ `VARMAX.fit(start_params=None, transformed=True, cov_type='opg', cov_kwds=None, method='lbfgs', maxiter=50, full_output=1, disp=5, callback=None, return_params=False, optim_score=None, optim_complex_step=None, optim_hessian=None, flags=None, **kwargs)` Fits the model by maximum likelihood via Kalman filter. | Parameters: | * **start\_params** (*array\_like**,* *optional*) – Initial guess of the solution for the loglikelihood maximization. If None, the default is given by Model.start\_params. * **transformed** (*boolean**,* *optional*) – Whether or not `start_params` is already transformed. Default is True. * **cov\_type** (*str**,* *optional*) – The `cov_type` keyword governs the method for calculating the covariance matrix of parameter estimates. Can be one of: + ’opg’ for the outer product of gradient estimator + ’oim’ for the observed information matrix estimator, calculated using the method of Harvey (1989) + ’approx’ for the observed information matrix estimator, calculated using a numerical approximation of the Hessian matrix. + ’robust’ for an approximate (quasi-maximum likelihood) covariance matrix that may be valid even in the presense of some misspecifications. Intermediate calculations use the ‘oim’ method. + ’robust\_approx’ is the same as ‘robust’ except that the intermediate calculations use the ‘approx’ method. + ’none’ for no covariance matrix calculation. * **cov\_kwds** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)") *or* *None**,* *optional*) – A dictionary of arguments affecting covariance matrix computation. **opg, oim, approx, robust, robust\_approx** + ’approx\_complex\_step’ : boolean, optional - If True, numerical approximations are computed using complex-step methods. If False, numerical approximations are computed using finite difference methods. Default is True. + ’approx\_centered’ : boolean, optional - If True, numerical approximations computed using finite difference methods use a centered approximation. Default is False. * **method** (*str**,* *optional*) – The `method` determines which solver from `scipy.optimize` is used, and it can be chosen from among the following strings: + ’newton’ for Newton-Raphson, ‘nm’ for Nelder-Mead + ’bfgs’ for Broyden-Fletcher-Goldfarb-Shanno (BFGS) + ’lbfgs’ for limited-memory BFGS with optional box constraints + ’powell’ for modified Powell’s method + ’cg’ for conjugate gradient + ’ncg’ for Newton-conjugate gradient + ’basinhopping’ for global basin-hopping solverThe explicit arguments in `fit` are passed to the solver, with the exception of the basin-hopping solver. Each solver has several optional arguments that are not the same across solvers. See the notes section below (or scipy.optimize) for the available arguments and for the list of explicit arguments that the basin-hopping solver supports. * **maxiter** (*int**,* *optional*) – The maximum number of iterations to perform. * **full\_output** (*boolean**,* *optional*) – Set to True to have all available output in the Results object’s mle\_retvals attribute. The output is dependent on the solver. See LikelihoodModelResults notes section for more information. * **disp** (*boolean**,* *optional*) – Set to True to print convergence messages. * **callback** (*callable callback**(**xk**)**,* *optional*) – Called after each iteration, as callback(xk), where xk is the current parameter vector. * **return\_params** (*boolean**,* *optional*) – Whether or not to return only the array of maximizing parameters. Default is False. * **optim\_score** (*{'harvey'**,* *'approx'}* *or* *None**,* *optional*) – The method by which the score vector is calculated. ‘harvey’ uses the method from Harvey (1989), ‘approx’ uses either finite difference or complex step differentiation depending upon the value of `optim_complex_step`, and None uses the built-in gradient approximation of the optimizer. Default is None. This keyword is only relevant if the optimization method uses the score. * **optim\_complex\_step** (*bool**,* *optional*) – Whether or not to use complex step differentiation when approximating the score; if False, finite difference approximation is used. Default is True. This keyword is only relevant if `optim_score` is set to ‘harvey’ or ‘approx’. * **optim\_hessian** (*{'opg'**,**'oim'**,**'approx'}**,* *optional*) – The method by which the Hessian is numerically approximated. ‘opg’ uses outer product of gradients, ‘oim’ uses the information matrix formula from Harvey (1989), and ‘approx’ uses numerical approximation. This keyword is only relevant if the optimization method uses the Hessian matrix. * **\*\*kwargs** – Additional keyword arguments to pass to the optimizer. | | Returns: | | | Return type: | [MLEResults](statsmodels.tsa.statespace.mlemodel.mleresults#statsmodels.tsa.statespace.mlemodel.MLEResults "statsmodels.tsa.statespace.mlemodel.MLEResults") | See also [`statsmodels.base.model.LikelihoodModel.fit`](http://www.statsmodels.org/stable/dev/generated/statsmodels.base.model.LikelihoodModel.fit.html#statsmodels.base.model.LikelihoodModel.fit "statsmodels.base.model.LikelihoodModel.fit"), `MLEResults` statsmodels statsmodels.regression.mixed_linear_model.MixedLM.get_fe_params statsmodels.regression.mixed\_linear\_model.MixedLM.get\_fe\_params =================================================================== `MixedLM.get_fe_params(cov_re, vcomp)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/mixed_linear_model.html#MixedLM.get_fe_params) Use GLS to update the fixed effects parameter estimates. | Parameters: | **cov\_re** (*array-like*) – The covariance matrix of the random effects. | | Returns: | | | Return type: | The GLS estimates of the fixed effects parameters. | statsmodels statsmodels.tsa.arima_model.ARIMAResults.cov_params statsmodels.tsa.arima\_model.ARIMAResults.cov\_params ===================================================== `ARIMAResults.cov_params()` Returns the variance/covariance matrix. The variance/covariance matrix can be of a linear contrast of the estimates of params or all params multiplied by scale which will usually be an estimate of sigma^2. Scale is assumed to be a scalar. | Parameters: | * **r\_matrix** (*array-like*) – Can be 1d, or 2d. Can be used alone or with other. * **column** (*array-like**,* *optional*) – Must be used on its own. Can be 0d or 1d see below. * **scale** (*float**,* *optional*) – Can be specified or not. Default is None, which means that the scale argument is taken from the model. * **other** (*array-like**,* *optional*) – Can be used when r\_matrix is specified. | | Returns: | **cov** – covariance matrix of the parameter estimates or of linear combination of parameter estimates. See Notes. | | Return type: | ndarray | #### Notes (The below are assumed to be in matrix notation.) If no argument is specified returns the covariance matrix of a model `(scale)*(X.T X)^(-1)` If contrast is specified it pre and post-multiplies as follows `(scale) * r_matrix (X.T X)^(-1) r_matrix.T` If contrast and other are specified returns `(scale) * r_matrix (X.T X)^(-1) other.T` If column is specified returns `(scale) * (X.T X)^(-1)[column,column]` if column is 0d OR `(scale) * (X.T X)^(-1)[column][:,column]` if column is 1d
programming_docs
statsmodels statsmodels.stats.contingency_tables.Table2x2 statsmodels.stats.contingency\_tables.Table2x2 ============================================== `class statsmodels.stats.contingency_tables.Table2x2(table, shift_zeros=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table2x2) Analyses that can be performed on a 2x2 contingency table. | Parameters: | * **table** (*array-like*) – A 2x2 contingency table * **shift\_zeros** (*boolean*) – If true, 0.5 is added to all cells of the table if any cell is equal to zero. | `log_oddsratio` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table2x2.log_oddsratio) *float* – The log odds ratio of the table. `log_oddsratio_se` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table2x2.log_oddsratio_se) *float* – The asymptotic standard error of the estimated log odds ratio. `oddsratio` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table2x2.oddsratio) *float* – The odds ratio of the table. `riskratio` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table2x2.riskratio) *float* – The ratio between the risk in the first row and the risk in the second row. Column 0 is interpreted as containing the number of occurences of the event of interest. `log_riskratio` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table2x2.log_riskratio) *float* – The estimated log risk ratio for the table. `log_riskratio_se` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table2x2.log_riskratio_se) *float* – The standard error of the estimated log risk ratio for the table. #### Notes The inference procedures used here are all based on a sampling model in which the units are independent and identically distributed, with each unit being classified with respect to two categorical variables. Note that for the risk ratio, the analysis is not symmetric with respect to the rows and columns of the contingency table. The two rows define population subgroups, column 0 is the number of ‘events’, and column 1 is the number of ‘non-events’. #### Methods | | | | --- | --- | | [`chi2_contribs`](statsmodels.stats.contingency_tables.table2x2.chi2_contribs#statsmodels.stats.contingency_tables.Table2x2.chi2_contribs "statsmodels.stats.contingency_tables.Table2x2.chi2_contribs")() | | | [`cumulative_log_oddsratios`](statsmodels.stats.contingency_tables.table2x2.cumulative_log_oddsratios#statsmodels.stats.contingency_tables.Table2x2.cumulative_log_oddsratios "statsmodels.stats.contingency_tables.Table2x2.cumulative_log_oddsratios")() | | | [`cumulative_oddsratios`](statsmodels.stats.contingency_tables.table2x2.cumulative_oddsratios#statsmodels.stats.contingency_tables.Table2x2.cumulative_oddsratios "statsmodels.stats.contingency_tables.Table2x2.cumulative_oddsratios")() | | | [`fittedvalues`](statsmodels.stats.contingency_tables.table2x2.fittedvalues#statsmodels.stats.contingency_tables.Table2x2.fittedvalues "statsmodels.stats.contingency_tables.Table2x2.fittedvalues")() | | | [`from_data`](statsmodels.stats.contingency_tables.table2x2.from_data#statsmodels.stats.contingency_tables.Table2x2.from_data "statsmodels.stats.contingency_tables.Table2x2.from_data")(data[, shift\_zeros]) | Construct a Table object from data. | | [`homogeneity`](statsmodels.stats.contingency_tables.table2x2.homogeneity#statsmodels.stats.contingency_tables.Table2x2.homogeneity "statsmodels.stats.contingency_tables.Table2x2.homogeneity")([method]) | Compare row and column marginal distributions. | | [`independence_probabilities`](statsmodels.stats.contingency_tables.table2x2.independence_probabilities#statsmodels.stats.contingency_tables.Table2x2.independence_probabilities "statsmodels.stats.contingency_tables.Table2x2.independence_probabilities")() | | | [`local_log_oddsratios`](statsmodels.stats.contingency_tables.table2x2.local_log_oddsratios#statsmodels.stats.contingency_tables.Table2x2.local_log_oddsratios "statsmodels.stats.contingency_tables.Table2x2.local_log_oddsratios")() | | | [`local_oddsratios`](statsmodels.stats.contingency_tables.table2x2.local_oddsratios#statsmodels.stats.contingency_tables.Table2x2.local_oddsratios "statsmodels.stats.contingency_tables.Table2x2.local_oddsratios")() | | | [`log_oddsratio`](statsmodels.stats.contingency_tables.table2x2.log_oddsratio#statsmodels.stats.contingency_tables.Table2x2.log_oddsratio "statsmodels.stats.contingency_tables.Table2x2.log_oddsratio")() | | | [`log_oddsratio_confint`](statsmodels.stats.contingency_tables.table2x2.log_oddsratio_confint#statsmodels.stats.contingency_tables.Table2x2.log_oddsratio_confint "statsmodels.stats.contingency_tables.Table2x2.log_oddsratio_confint")([alpha, method]) | A confidence level for the log odds ratio. | | [`log_oddsratio_pvalue`](statsmodels.stats.contingency_tables.table2x2.log_oddsratio_pvalue#statsmodels.stats.contingency_tables.Table2x2.log_oddsratio_pvalue "statsmodels.stats.contingency_tables.Table2x2.log_oddsratio_pvalue")([null]) | P-value for a hypothesis test about the log odds ratio. | | [`log_oddsratio_se`](statsmodels.stats.contingency_tables.table2x2.log_oddsratio_se#statsmodels.stats.contingency_tables.Table2x2.log_oddsratio_se "statsmodels.stats.contingency_tables.Table2x2.log_oddsratio_se")() | | | [`log_riskratio`](statsmodels.stats.contingency_tables.table2x2.log_riskratio#statsmodels.stats.contingency_tables.Table2x2.log_riskratio "statsmodels.stats.contingency_tables.Table2x2.log_riskratio")() | | | [`log_riskratio_confint`](statsmodels.stats.contingency_tables.table2x2.log_riskratio_confint#statsmodels.stats.contingency_tables.Table2x2.log_riskratio_confint "statsmodels.stats.contingency_tables.Table2x2.log_riskratio_confint")([alpha, method]) | A confidence interval for the log risk ratio. | | [`log_riskratio_pvalue`](statsmodels.stats.contingency_tables.table2x2.log_riskratio_pvalue#statsmodels.stats.contingency_tables.Table2x2.log_riskratio_pvalue "statsmodels.stats.contingency_tables.Table2x2.log_riskratio_pvalue")([null]) | p-value for a hypothesis test about the log risk ratio. | | [`log_riskratio_se`](statsmodels.stats.contingency_tables.table2x2.log_riskratio_se#statsmodels.stats.contingency_tables.Table2x2.log_riskratio_se "statsmodels.stats.contingency_tables.Table2x2.log_riskratio_se")() | | | [`marginal_probabilities`](statsmodels.stats.contingency_tables.table2x2.marginal_probabilities#statsmodels.stats.contingency_tables.Table2x2.marginal_probabilities "statsmodels.stats.contingency_tables.Table2x2.marginal_probabilities")() | | | [`oddsratio`](statsmodels.stats.contingency_tables.table2x2.oddsratio#statsmodels.stats.contingency_tables.Table2x2.oddsratio "statsmodels.stats.contingency_tables.Table2x2.oddsratio")() | | | [`oddsratio_confint`](statsmodels.stats.contingency_tables.table2x2.oddsratio_confint#statsmodels.stats.contingency_tables.Table2x2.oddsratio_confint "statsmodels.stats.contingency_tables.Table2x2.oddsratio_confint")([alpha, method]) | A confidence interval for the odds ratio. | | [`oddsratio_pvalue`](statsmodels.stats.contingency_tables.table2x2.oddsratio_pvalue#statsmodels.stats.contingency_tables.Table2x2.oddsratio_pvalue "statsmodels.stats.contingency_tables.Table2x2.oddsratio_pvalue")([null]) | P-value for a hypothesis test about the odds ratio. | | [`resid_pearson`](statsmodels.stats.contingency_tables.table2x2.resid_pearson#statsmodels.stats.contingency_tables.Table2x2.resid_pearson "statsmodels.stats.contingency_tables.Table2x2.resid_pearson")() | | | [`riskratio`](statsmodels.stats.contingency_tables.table2x2.riskratio#statsmodels.stats.contingency_tables.Table2x2.riskratio "statsmodels.stats.contingency_tables.Table2x2.riskratio")() | | | [`riskratio_confint`](statsmodels.stats.contingency_tables.table2x2.riskratio_confint#statsmodels.stats.contingency_tables.Table2x2.riskratio_confint "statsmodels.stats.contingency_tables.Table2x2.riskratio_confint")([alpha, method]) | A confidence interval for the risk ratio. | | [`riskratio_pvalue`](statsmodels.stats.contingency_tables.table2x2.riskratio_pvalue#statsmodels.stats.contingency_tables.Table2x2.riskratio_pvalue "statsmodels.stats.contingency_tables.Table2x2.riskratio_pvalue")([null]) | p-value for a hypothesis test about the risk ratio. | | [`standardized_resids`](statsmodels.stats.contingency_tables.table2x2.standardized_resids#statsmodels.stats.contingency_tables.Table2x2.standardized_resids "statsmodels.stats.contingency_tables.Table2x2.standardized_resids")() | | | [`summary`](statsmodels.stats.contingency_tables.table2x2.summary#statsmodels.stats.contingency_tables.Table2x2.summary "statsmodels.stats.contingency_tables.Table2x2.summary")([alpha, float\_format, method]) | Summarizes results for a 2x2 table analysis. | | [`symmetry`](statsmodels.stats.contingency_tables.table2x2.symmetry#statsmodels.stats.contingency_tables.Table2x2.symmetry "statsmodels.stats.contingency_tables.Table2x2.symmetry")([method]) | Test for symmetry of a joint distribution. | | [`test_nominal_association`](statsmodels.stats.contingency_tables.table2x2.test_nominal_association#statsmodels.stats.contingency_tables.Table2x2.test_nominal_association "statsmodels.stats.contingency_tables.Table2x2.test_nominal_association")() | Assess independence for nominal factors. | | [`test_ordinal_association`](statsmodels.stats.contingency_tables.table2x2.test_ordinal_association#statsmodels.stats.contingency_tables.Table2x2.test_ordinal_association "statsmodels.stats.contingency_tables.Table2x2.test_ordinal_association")([row\_scores, …]) | Assess independence between two ordinal variables. | statsmodels statsmodels.discrete.discrete_model.CountResults.get_margeff statsmodels.discrete.discrete\_model.CountResults.get\_margeff ============================================================== `CountResults.get_margeff(at='overall', method='dydx', atexog=None, dummy=False, count=False)` Get marginal effects of the fitted model. | Parameters: | * **at** (*str**,* *optional*) – Options are: + ’overall’, The average of the marginal effects at each observation. + ’mean’, The marginal effects at the mean of each regressor. + ’median’, The marginal effects at the median of each regressor. + ’zero’, The marginal effects at zero for each regressor. + ’all’, The marginal effects at each observation. If `at` is all only margeff will be available from the returned object.Note that if `exog` is specified, then marginal effects for all variables not specified by `exog` are calculated using the `at` option. * **method** (*str**,* *optional*) – Options are: + ’dydx’ - dy/dx - No transformation is made and marginal effects are returned. This is the default. + ’eyex’ - estimate elasticities of variables in `exog` – d(lny)/d(lnx) + ’dyex’ - estimate semielasticity – dy/d(lnx) + ’eydx’ - estimate semeilasticity – d(lny)/dxNote that tranformations are done after each observation is calculated. Semi-elasticities for binary variables are computed using the midpoint method. ‘dyex’ and ‘eyex’ do not make sense for discrete variables. * **atexog** (*array-like**,* *optional*) – Optionally, you can provide the exogenous variables over which to get the marginal effects. This should be a dictionary with the key as the zero-indexed column number and the value of the dictionary. Default is None for all independent variables less the constant. * **dummy** (*bool**,* *optional*) – If False, treats binary variables (if present) as continuous. This is the default. Else if True, treats binary variables as changing from 0 to 1. Note that any variable that is either 0 or 1 is treated as binary. Each binary variable is treated separately for now. * **count** (*bool**,* *optional*) – If False, treats count variables (if present) as continuous. This is the default. Else if True, the marginal effect is the change in probabilities when each observation is increased by one. | | Returns: | **DiscreteMargins** – Returns an object that holds the marginal effects, standard errors, confidence intervals, etc. See `statsmodels.discrete.discrete_margins.DiscreteMargins` for more information. | | Return type: | marginal effects instance | #### Notes When using after Poisson, returns the expected number of events per period, assuming that the model is loglinear. statsmodels statsmodels.duration.hazard_regression.PHRegResults.initialize statsmodels.duration.hazard\_regression.PHRegResults.initialize =============================================================== `PHRegResults.initialize(model, params, **kwd)` statsmodels statsmodels.tsa.arima_model.ARMAResults.arroots statsmodels.tsa.arima\_model.ARMAResults.arroots ================================================ `ARMAResults.arroots()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_model.html#ARMAResults.arroots) statsmodels statsmodels.sandbox.tsa.fftarma.ArmaFft.invpowerspd statsmodels.sandbox.tsa.fftarma.ArmaFft.invpowerspd =================================================== `ArmaFft.invpowerspd(n)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/tsa/fftarma.html#ArmaFft.invpowerspd) autocovariance from spectral density scaling is correct, but n needs to be large for numerical accuracy maybe padding with zero in fft would be faster without slicing it returns 2-sided autocovariance with fftshift ``` >>> ArmaFft([1, -0.5], [1., 0.4], 40).invpowerspd(2**8)[:10] array([ 2.08 , 1.44 , 0.72 , 0.36 , 0.18 , 0.09 , 0.045 , 0.0225 , 0.01125 , 0.005625]) >>> ArmaFft([1, -0.5], [1., 0.4], 40).acovf(10) array([ 2.08 , 1.44 , 0.72 , 0.36 , 0.18 , 0.09 , 0.045 , 0.0225 , 0.01125 , 0.005625]) ``` statsmodels statsmodels.discrete.count_model.ZeroInflatedPoisson.score statsmodels.discrete.count\_model.ZeroInflatedPoisson.score =========================================================== `ZeroInflatedPoisson.score(params)` Score vector of model. The gradient of logL with respect to each parameter. statsmodels statsmodels.sandbox.distributions.extras.ACSkewT_gen.isf statsmodels.sandbox.distributions.extras.ACSkewT\_gen.isf ========================================================= `ACSkewT_gen.isf(q, *args, **kwds)` Inverse survival function (inverse of `sf`) at q of the given RV. | Parameters: | * **q** (*array\_like*) – upper tail probability * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **x** – Quantile corresponding to the upper tail probability q. | | Return type: | ndarray or scalar | statsmodels statsmodels.discrete.discrete_model.LogitResults.resid_response statsmodels.discrete.discrete\_model.LogitResults.resid\_response ================================================================= `LogitResults.resid_response()` The response residuals #### Notes Response residuals are defined to be \[y - p\] where \(p=cdf(X\beta)\). statsmodels statsmodels.genmod.families.family.Poisson.predict statsmodels.genmod.families.family.Poisson.predict ================================================== `Poisson.predict(mu)` Linear predictors based on given mu values. | Parameters: | **mu** (*array*) – The mean response variables | | Returns: | **lin\_pred** – Linear predictors based on the mean response variables. The value of the link function at the given mu. | | Return type: | array | statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.f_test statsmodels.tsa.statespace.dynamic\_factor.DynamicFactorResults.f\_test ======================================================================= `DynamicFactorResults.f_test(r_matrix, cov_p=None, scale=1.0, invcov=None)` Compute the F-test for a joint linear hypothesis. This is a special case of `wald_test` that always uses the F distribution. | Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) – + array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length k row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – Default is 1.0 for no scaling. * **invcov** (*array-like**,* *optional*) – A q x q array to specify an inverse covariance matrix based on a restrictions matrix. | | Returns: | **res** – The results for the test are attributes of this results instance. | | Return type: | ContrastResults instance | #### Examples ``` >>> import numpy as np >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> A = np.identity(len(results.params)) >>> A = A[1:,:] ``` This tests that each coefficient is jointly statistically significantly different from zero. ``` >>> print(results.f_test(A)) <F test: F=array([[ 330.28533923]]), p=4.984030528700946e-10, df_denom=9, df_num=6> ``` Compare this to ``` >>> results.fvalue 330.2853392346658 >>> results.f_pvalue 4.98403096572e-10 ``` ``` >>> B = np.array(([0,0,1,-1,0,0,0],[0,0,0,0,0,1,-1])) ``` This tests that the coefficient on the 2nd and 3rd regressors are equal and jointly that the coefficient on the 5th and 6th regressors are equal. ``` >>> print(results.f_test(B)) <F test: F=array([[ 9.74046187]]), p=0.005605288531708235, df_denom=9, df_num=2> ``` Alternatively, you can specify the hypothesis tests using a string ``` >>> from statsmodels.datasets import longley >>> from statsmodels.formula.api import ols >>> dta = longley.load_pandas().data >>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' >>> results = ols(formula, dta).fit() >>> hypotheses = '(GNPDEFL = GNP), (UNEMP = 2), (YEAR/1829 = 1)' >>> f_test = results.f_test(hypotheses) >>> print(f_test) <F test: F=array([[ 144.17976065]]), p=6.322026217355609e-08, df_denom=9, df_num=3> ``` See also [`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`wald_test`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactorresults.wald_test#statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.wald_test "statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.wald_test"), [`t_test`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactorresults.t_test#statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.t_test "statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") #### Notes The matrix `r_matrix` is assumed to be non-singular. More precisely, r\_matrix (pX pX.T) r\_matrix.T is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full.
programming_docs
statsmodels statsmodels.sandbox.regression.gmm.LinearIVGMM.gradient_momcond statsmodels.sandbox.regression.gmm.LinearIVGMM.gradient\_momcond ================================================================ `LinearIVGMM.gradient_momcond(params, **kwds)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#LinearIVGMM.gradient_momcond) gradient of moment conditions | Parameters: | * **params** (*ndarray*) – parameter at which the moment conditions are evaluated * **epsilon** (*float*) – stepsize for finite difference calculation * **centered** (*bool*) – This refers to the finite difference calculation. If `centered` is true, then the centered finite difference calculation is used. Otherwise the one-sided forward differences are used. * **TODO** (*looks like not used yet*) – missing argument `weights` | statsmodels statsmodels.iolib.summary.Summary.as_csv statsmodels.iolib.summary.Summary.as\_csv ========================================= `Summary.as_csv()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/iolib/summary.html#Summary.as_csv) return tables as string | Returns: | **csv** – concatenated summary tables in comma delimited format | | Return type: | string | statsmodels statsmodels.stats.correlation_tools.corr_thresholded statsmodels.stats.correlation\_tools.corr\_thresholded ====================================================== `statsmodels.stats.correlation_tools.corr_thresholded(data, minabs=None, max_elt=10000000.0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/correlation_tools.html#corr_thresholded) Construct a sparse matrix containing the thresholded row-wise correlation matrix from a data array. | Parameters: | * **data** (*array\_like*) – The data from which the row-wise thresholded correlation matrix is to be computed. * **minabs** (*non-negative real*) – The threshold value; correlation coefficients smaller in magnitude than minabs are set to zero. If None, defaults to 1 / sqrt(n), see Notes for more information. | | Returns: | **cormat** – The thresholded correlation matrix, in COO format. | | Return type: | sparse.coo\_matrix | #### Notes This is an alternative to C = np.corrcoef(data); C \*= (np.abs(C) >= absmin), suitable for very tall data matrices. If the data are jointly Gaussian, the marginal sampling distributions of the elements of the sample correlation matrix are approximately Gaussian with standard deviation 1 / sqrt(n). The default value of `minabs` is thus equal to 1 standard error, which will set to zero approximately 68% of the estimated correlation coefficients for which the population value is zero. No intermediate matrix with more than `max_elt` values will be constructed. However memory use could still be high if a large number of correlation values exceed `minabs` in magnitude. The thresholded matrix is returned in COO format, which can easily be converted to other sparse formats. #### Examples Here X is a tall data matrix (e.g. with 100,000 rows and 50 columns). The row-wise correlation matrix of X is calculated and stored in sparse form, with all entries smaller than 0.3 treated as 0. ``` >>> import numpy as np >>> np.random.seed(1234) >>> b = 1.5 - np.random.rand(10, 1) >>> x = np.random.randn(100,1).dot(b.T) + np.random.randn(100,10) >>> cmat = corr_thresholded(x, 0.3) ``` statsmodels statsmodels.sandbox.stats.multicomp.GroupsStats.runbasic_old statsmodels.sandbox.stats.multicomp.GroupsStats.runbasic\_old ============================================================= `GroupsStats.runbasic_old(useranks=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/multicomp.html#GroupsStats.runbasic_old) statsmodels statsmodels.regression.quantile_regression.QuantReg.whiten statsmodels.regression.quantile\_regression.QuantReg.whiten =========================================================== `QuantReg.whiten(data)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/quantile_regression.html#QuantReg.whiten) QuantReg model whitener does nothing: returns data. statsmodels statsmodels.sandbox.distributions.transformed.loggammaexpg statsmodels.sandbox.distributions.transformed.loggammaexpg ========================================================== `statsmodels.sandbox.distributions.transformed.loggammaexpg = <statsmodels.sandbox.distributions.transformed.Transf_gen object>` univariate distribution of a non-linear monotonic transformation of a random variable statsmodels statsmodels.imputation.mice.MICEData.impute_pmm statsmodels.imputation.mice.MICEData.impute\_pmm ================================================ `MICEData.impute_pmm(vname)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/imputation/mice.html#MICEData.impute_pmm) Use predictive mean matching to impute missing values. #### Notes The `perturb_params` method must be called first to define the model. statsmodels statsmodels.stats.multitest.fdrcorrection statsmodels.stats.multitest.fdrcorrection ========================================= `statsmodels.stats.multitest.fdrcorrection(pvals, alpha=0.05, method='indep', is_sorted=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/multitest.html#fdrcorrection) pvalue correction for false discovery rate This covers Benjamini/Hochberg for independent or positively correlated and Benjamini/Yekutieli for general or negatively correlated tests. Both are available in the function multipletests, as method=`fdr\_bh`, resp. `fdr_by`. | Parameters: | * **pvals** (*array\_like*) – set of p-values of the individual tests. * **alpha** (*float*) – error rate * **method** (*{'indep'**,* *'negcorr'**)*) – | | Returns: | * **rejected** (*array, bool*) – True if a hypothesis is rejected, False if not * **pvalue-corrected** (*array*) – pvalues adjusted for multiple hypothesis testing to limit FDR | #### Notes If there is prior information on the fraction of true hypothesis, then alpha should be set to alpha \* m/m\_0 where m is the number of tests, given by the p-values, and m\_0 is an estimate of the true hypothesis. (see Benjamini, Krieger and Yekuteli) The two-step method of Benjamini, Krieger and Yekutiel that estimates the number of false hypotheses will be available (soon). Method names can be abbreviated to first letter, ‘i’ or ‘p’ for fdr\_bh and ‘n’ for fdr\_by. statsmodels statsmodels.stats.diagnostic.normal_ad statsmodels.stats.diagnostic.normal\_ad ======================================= `statsmodels.stats.diagnostic.normal_ad(x, axis=0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/_adnorm.html#normal_ad) Anderson-Darling test for normal distribution unknown mean and variance | Parameters: | **x** (*array\_like*) – data array, currently only 1d | | Returns: | * **ad2** (*float*) – Anderson Darling test statistic * **pval** (*float*) – pvalue for hypothesis that the data comes from a normal distribution with unknown mean and variance | statsmodels statsmodels.sandbox.regression.gmm.NonlinearIVGMM.fit statsmodels.sandbox.regression.gmm.NonlinearIVGMM.fit ===================================================== `NonlinearIVGMM.fit(start_params=None, maxiter=10, inv_weights=None, weights_method='cov', wargs=(), has_optimal_weights=True, optim_method='bfgs', optim_args=None)` Estimate parameters using GMM and return GMMResults TODO: weight and covariance arguments still need to be made consistent with similar options in other models, see RegressionResult.get\_robustcov\_results | Parameters: | * **start\_params** (*array* *(**optional**)*) – starting value for parameters ub minimization. If None then fitstart method is called for the starting values. * **maxiter** (*int* *or* *'cue'*) – Number of iterations in iterated GMM. The onestep estimate can be obtained with maxiter=0 or 1. If maxiter is large, then the iteration will stop either at maxiter or on convergence of the parameters (TODO: no options for convergence criteria yet.) If `maxiter == ‘cue’`, the the continuously updated GMM is calculated which updates the weight matrix during the minimization of the GMM objective function. The CUE estimation uses the onestep parameters as starting values. * **inv\_weights** (*None* *or* *ndarray*) – inverse of the starting weighting matrix. If inv\_weights are not given then the method `start_weights` is used which depends on the subclass, for IV subclasses `inv_weights = z’z` where `z` are the instruments, otherwise an identity matrix is used. * **weights\_method** (*string**,* *defines method for robust*) – Options here are similar to `statsmodels.stats.robust_covariance` default is heteroscedasticity consistent, HC0 currently available methods are + `cov` : HC0, optionally with degrees of freedom correction + `hac` : + `iid` : untested, only for Z\*u case, IV cases with u as error indep of Z + `ac` : not available yet + `cluster` : not connected yet + others from robust\_covariance * **wargs`** (*tuple* *or* [dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")*,*) – required and optional arguments for weights\_method + `centered` : bool, indicates whether moments are centered for the calculation of the weights and covariance matrix, applies to all weight\_methods + `ddof` : int degrees of freedom correction, applies currently only to `cov` + `maxlag` : int number of lags to include in HAC calculation , applies only to `hac` + others not yet, e.g. groups for cluster robust * **has\_optimal\_weights** (*If true**,* *then the calculation of the covariance*) – matrix assumes that we have optimal GMM with \(W = S^{-1}\). Default is True. TODO: do we want to have a different default after `onestep`? * **optim\_method** (*string**,* *default is 'bfgs'*) – numerical optimization method. Currently not all optimizers that are available in LikelihoodModels are connected. * **optim\_args** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")) – keyword arguments for the numerical optimizer. | | Returns: | **results** – this is also attached as attribute results | | Return type: | instance of GMMResults | #### Notes Warning: One-step estimation, `maxiter` either 0 or 1, still has problems (at least compared to Stata’s gmm). By default it uses a heteroscedasticity robust covariance matrix, but uses the assumption that the weight matrix is optimal. See options for cov\_params in the results instance. The same options as for weight matrix also apply to the calculation of the estimate of the covariance matrix of the parameter estimates. statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.compare_lm_test statsmodels.sandbox.regression.gmm.IVRegressionResults.compare\_lm\_test ======================================================================== `IVRegressionResults.compare_lm_test(restricted, demean=True, use_lr=False)` Use Lagrange Multiplier test to test whether restricted model is correct | Parameters: | * **restricted** (*Result instance*) – The restricted model is assumed to be nested in the current model. The result instance of the restricted model is required to have two attributes, residual sum of squares, `ssr`, residual degrees of freedom, `df_resid`. * **demean** (*bool*) – Flag indicating whether the demean the scores based on the residuals from the restricted model. If True, the covariance of the scores are used and the LM test is identical to the large sample version of the LR test. | | Returns: | * **lm\_value** (*float*) – test statistic, chi2 distributed * **p\_value** (*float*) – p-value of the test statistic * **df\_diff** (*int*) – degrees of freedom of the restriction, i.e. difference in df between models | #### Notes TODO: explain LM text statsmodels statsmodels.discrete.discrete_model.DiscreteModel.fit_regularized statsmodels.discrete.discrete\_model.DiscreteModel.fit\_regularized =================================================================== `DiscreteModel.fit_regularized(start_params=None, method='l1', maxiter='defined_by_method', full_output=1, disp=True, callback=None, alpha=0, trim_mode='auto', auto_trim_tol=0.01, size_trim_tol=0.0001, qc_tol=0.03, qc_verbose=False, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#DiscreteModel.fit_regularized) Fit the model using a regularized maximum likelihood. The regularization method AND the solver used is determined by the argument method. | Parameters: | * **start\_params** (*array-like**,* *optional*) – Initial guess of the solution for the loglikelihood maximization. The default is an array of zeros. * **method** (*'l1'* *or* *'l1\_cvxopt\_cp'*) – See notes for details. * **maxiter** (*Integer* *or* *'defined\_by\_method'*) – Maximum number of iterations to perform. If ‘defined\_by\_method’, then use method defaults (see notes). * **full\_output** (*bool*) – Set to True to have all available output in the Results object’s mle\_retvals attribute. The output is dependent on the solver. See LikelihoodModelResults notes section for more information. * **disp** (*bool*) – Set to True to print convergence messages. * **fargs** (*tuple*) – Extra arguments passed to the likelihood function, i.e., loglike(x,\*args) * **callback** (*callable callback**(**xk**)*) – Called after each iteration, as callback(xk), where xk is the current parameter vector. * **retall** (*bool*) – Set to True to return list of solutions at each iteration. Available in Results object’s mle\_retvals attribute. * **alpha** (*non-negative scalar* *or* *numpy array* *(**same size as parameters**)*) – The weight multiplying the l1 penalty term * **trim\_mode** (*'auto**,* *'size'**, or* *'off'*) – If not ‘off’, trim (set to zero) parameters that would have been zero if the solver reached the theoretical minimum. If ‘auto’, trim params using the Theory above. If ‘size’, trim params if they have very small absolute value * **size\_trim\_tol** (*float* *or* *'auto'* *(**default = 'auto'**)*) – For use when trim\_mode == ‘size’ * **auto\_trim\_tol** (*float*) – For sue when trim\_mode == ‘auto’. Use * **qc\_tol** (*float*) – Print warning and don’t allow auto trim when (ii) (above) is violated by this much. * **qc\_verbose** (*Boolean*) – If true, print out a full QC report upon failure | #### Notes Extra parameters are not penalized if alpha is given as a scalar. An example is the shape parameter in NegativeBinomial `nb1` and `nb2`. Optional arguments for the solvers (available in Results.mle\_settings): ``` 'l1' acc : float (default 1e-6) Requested accuracy as used by slsqp 'l1_cvxopt_cp' abstol : float absolute accuracy (default: 1e-7). reltol : float relative accuracy (default: 1e-6). feastol : float tolerance for feasibility conditions (default: 1e-7). refinement : int number of iterative refinement steps when solving KKT equations (default: 1). ``` Optimization methodology With \(L\) the negative log likelihood, we solve the convex but non-smooth problem \[\min\_\beta L(\beta) + \sum\_k\alpha\_k |\beta\_k|\] via the transformation to the smooth, convex, constrained problem in twice as many variables (adding the “added variables” \(u\_k\)) \[\min\_{\beta,u} L(\beta) + \sum\_k\alpha\_k u\_k,\] subject to \[-u\_k \leq \beta\_k \leq u\_k.\] With \(\partial\_k L\) the derivative of \(L\) in the \(k^{th}\) parameter direction, theory dictates that, at the minimum, exactly one of two conditions holds: 1. \(|\partial\_k L| = \alpha\_k\) and \(\beta\_k \neq 0\) 2. \(|\partial\_k L| \leq \alpha\_k\) and \(\beta\_k = 0\) statsmodels statsmodels.sandbox.stats.multicomp.homogeneous_subsets statsmodels.sandbox.stats.multicomp.homogeneous\_subsets ======================================================== `statsmodels.sandbox.stats.multicomp.homogeneous_subsets(vals, dcrit)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/multicomp.html#homogeneous_subsets) recursively check all pairs of vals for minimum distance step down method as in Newman-Keuls and Ryan procedures. This is not a closed procedure since not all partitions are checked. | Parameters: | * **vals** (*array\_like*) – values that are pairwise compared * **dcrit** (*array\_like* *or* *float*) – critical distance for rejecting, either float, or 2-dimensional array with distances on the upper triangle. | | Returns: | * **rejs** (*list of pairs*) – list of pair-indices with (strictly) larger than critical difference * **nrejs** (*list of pairs*) – list of pair-indices with smaller than critical difference * **lli** (*list of tuples*) – list of subsets with smaller than critical difference * **res** (*tree*) – result of all comparisons (for checking) | this follows description in SPSS notes on Post-Hoc Tests Because of the recursive structure, some comparisons are made several times, but only unique pairs or sets are returned. #### Examples ``` >>> m = [0, 2, 2.5, 3, 6, 8, 9, 9.5,10 ] >>> rej, nrej, ssli, res = homogeneous_subsets(m, 2) >>> set_partition(ssli) ([(5, 6, 7, 8), (1, 2, 3), (4,)], [0]) >>> [np.array(m)[list(pp)] for pp in set_partition(ssli)[0]] [array([ 8. , 9. , 9.5, 10. ]), array([ 2. , 2.5, 3. ]), array([ 6.])] ``` statsmodels statsmodels.discrete.discrete_model.DiscreteModel.score statsmodels.discrete.discrete\_model.DiscreteModel.score ======================================================== `DiscreteModel.score(params)` Score vector of model. The gradient of logL with respect to each parameter. statsmodels statsmodels.tsa.statespace.mlemodel.MLEResults.fittedvalues statsmodels.tsa.statespace.mlemodel.MLEResults.fittedvalues =========================================================== `MLEResults.fittedvalues()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEResults.fittedvalues) (array) The predicted values of the model. An (nobs x k\_endog) array. statsmodels statsmodels.tsa.arima_model.ARMAResults.initialize statsmodels.tsa.arima\_model.ARMAResults.initialize =================================================== `ARMAResults.initialize(model, params, **kwd)` statsmodels statsmodels.sandbox.distributions.extras.SkewNorm2_gen.fit_loc_scale statsmodels.sandbox.distributions.extras.SkewNorm2\_gen.fit\_loc\_scale ======================================================================= `SkewNorm2_gen.fit_loc_scale(data, *args)` Estimate loc and scale parameters from data using 1st and 2nd moments. | Parameters: | * **data** (*array\_like*) – Data to fit. * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information). | | Returns: | * **Lhat** (*float*) – Estimated location parameter for the data. * **Shat** (*float*) – Estimated scale parameter for the data. | statsmodels statsmodels.miscmodels.count.PoissonOffsetGMLE.expandparams statsmodels.miscmodels.count.PoissonOffsetGMLE.expandparams =========================================================== `PoissonOffsetGMLE.expandparams(params)` expand to full parameter array when some parameters are fixed | Parameters: | **params** (*array*) – reduced parameter array | | Returns: | **paramsfull** – expanded parameter array where fixed parameters are included | | Return type: | array | #### Notes Calling this requires that self.fixed\_params and self.fixed\_paramsmask are defined. *developer notes:* This can be used in the log-likelihood to … this could also be replaced by a more general parameter transformation. statsmodels statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.filter statsmodels.tsa.statespace.kalman\_smoother.KalmanSmoother.filter ================================================================= `KalmanSmoother.filter(filter_method=None, inversion_method=None, stability_method=None, conserve_memory=None, filter_timing=None, tolerance=None, loglikelihood_burn=None, complex_step=False)` Apply the Kalman filter to the statespace model. | Parameters: | * **filter\_method** (*int**,* *optional*) – Determines which Kalman filter to use. Default is conventional. * **inversion\_method** (*int**,* *optional*) – Determines which inversion technique to use. Default is by Cholesky decomposition. * **stability\_method** (*int**,* *optional*) – Determines which numerical stability techniques to use. Default is to enforce symmetry of the predicted state covariance matrix. * **conserve\_memory** (*int**,* *optional*) – Determines what output from the filter to store. Default is to store everything. * **filter\_timing** (*int**,* *optional*) – Determines the timing convention of the filter. Default is that from Durbin and Koopman (2012), in which the filter is initialized with predicted values. * **tolerance** (*float**,* *optional*) – The tolerance at which the Kalman filter determines convergence to steady-state. Default is 1e-19. * **loglikelihood\_burn** (*int**,* *optional*) – The number of initial periods during which the loglikelihood is not recorded. Default is 0. | #### Notes This function by default does not compute variables required for smoothing.
programming_docs
statsmodels statsmodels.discrete.count_model.ZeroInflatedPoissonResults.llf statsmodels.discrete.count\_model.ZeroInflatedPoissonResults.llf ================================================================ `ZeroInflatedPoissonResults.llf()` statsmodels statsmodels.genmod.families.links.identity statsmodels.genmod.families.links.identity ========================================== `class statsmodels.genmod.families.links.identity` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/links.html#identity) The identity transform #### Notes g(`p`) = `p` Alias of statsmodels.family.links.Power(power=1.) #### Methods | | | | --- | --- | | [`deriv`](statsmodels.genmod.families.links.identity.deriv#statsmodels.genmod.families.links.identity.deriv "statsmodels.genmod.families.links.identity.deriv")(p) | Derivative of the power transform | | [`deriv2`](statsmodels.genmod.families.links.identity.deriv2#statsmodels.genmod.families.links.identity.deriv2 "statsmodels.genmod.families.links.identity.deriv2")(p) | Second derivative of the power transform | | [`inverse`](statsmodels.genmod.families.links.identity.inverse#statsmodels.genmod.families.links.identity.inverse "statsmodels.genmod.families.links.identity.inverse")(z) | Inverse of the power transform link function | | [`inverse_deriv`](statsmodels.genmod.families.links.identity.inverse_deriv#statsmodels.genmod.families.links.identity.inverse_deriv "statsmodels.genmod.families.links.identity.inverse_deriv")(z) | Derivative of the inverse of the power transform | statsmodels statsmodels.discrete.discrete_model.BinaryModel.predict statsmodels.discrete.discrete\_model.BinaryModel.predict ======================================================== `BinaryModel.predict(params, exog=None, linear=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#BinaryModel.predict) Predict response variable of a model given exogenous variables. | Parameters: | * **params** (*array-like*) – Fitted parameters of the model. * **exog** (*array-like*) – 1d or 2d array of exogenous values. If not supplied, the whole exog attribute of the model is used. * **linear** (*bool**,* *optional*) – If True, returns the linear predictor dot(exog,params). Else, returns the value of the cdf at the linear predictor. | | Returns: | Fitted values at exog. | | Return type: | array | statsmodels statsmodels.iolib.foreign.StataReader.file_label statsmodels.iolib.foreign.StataReader.file\_label ================================================= `StataReader.file_label()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/iolib/foreign.html#StataReader.file_label) Returns the dataset’s label. | Returns: | **out** | | Return type: | string | statsmodels statsmodels.regression.quantile_regression.QuantRegResults.HC0_se statsmodels.regression.quantile\_regression.QuantRegResults.HC0\_se =================================================================== `QuantRegResults.HC0_se()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/quantile_regression.html#QuantRegResults.HC0_se) See statsmodels.RegressionResults statsmodels statsmodels.regression.quantile_regression.QuantRegResults.scale statsmodels.regression.quantile\_regression.QuantRegResults.scale ================================================================= `QuantRegResults.scale()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/quantile_regression.html#QuantRegResults.scale) statsmodels statsmodels.tsa.statespace.representation.Representation.initialize_stationary statsmodels.tsa.statespace.representation.Representation.initialize\_stationary =============================================================================== `Representation.initialize_stationary()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/representation.html#Representation.initialize_stationary) Initialize the statespace model as stationary. statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.initialize_known statsmodels.tsa.statespace.dynamic\_factor.DynamicFactor.initialize\_known ========================================================================== `DynamicFactor.initialize_known(initial_state, initial_state_cov)` statsmodels statsmodels.sandbox.tsa.fftarma.ArmaFft.fftar statsmodels.sandbox.tsa.fftarma.ArmaFft.fftar ============================================= `ArmaFft.fftar(n=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/tsa/fftarma.html#ArmaFft.fftar) Fourier transform of AR polynomial, zero-padded at end to n | Parameters: | **n** (*int*) – length of array after zero-padding | | Returns: | **fftar** – fft of zero-padded ar polynomial | | Return type: | ndarray | statsmodels statsmodels.tsa.statespace.structural.UnobservedComponents.score_obs statsmodels.tsa.statespace.structural.UnobservedComponents.score\_obs ===================================================================== `UnobservedComponents.score_obs(params, method='approx', transformed=True, approx_complex_step=None, approx_centered=False, **kwargs)` Compute the score per observation, evaluated at params | Parameters: | * **params** (*array\_like*) – Array of parameters at which to evaluate the score. * **kwargs** – Additional arguments to the `loglike` method. | | Returns: | **score** – Score per observation, evaluated at `params`. | | Return type: | array | #### Notes This is a numerical approximation, calculated using first-order complex step differentiation on the `loglikeobs` method. statsmodels statsmodels.duration.hazard_regression.PHRegResults.load statsmodels.duration.hazard\_regression.PHRegResults.load ========================================================= `classmethod PHRegResults.load(fname)` load a pickle, (class method) | Parameters: | **fname** (*string* *or* *filehandle*) – fname can be a string to a file path or filename, or a filehandle. | | Returns: | | | Return type: | unpickled instance | statsmodels statsmodels.sandbox.regression.gmm.IVGMMResults.t_test_pairwise statsmodels.sandbox.regression.gmm.IVGMMResults.t\_test\_pairwise ================================================================= `IVGMMResults.t_test_pairwise(term_name, method='hs', alpha=0.05, factor_labels=None)` perform pairwise t\_test with multiple testing corrected p-values This uses the formula design\_info encoding contrast matrix and should work for all encodings of a main effect. | Parameters: | * **result** (*result instance*) – The results of an estimated model with a categorical main effect. * **term\_name** (*str*) – name of the term for which pairwise comparisons are computed. Term names for categorical effects are created by patsy and correspond to the main part of the exog names. * **method** (*str* *or* *list of strings*) – multiple testing p-value correction, default is ‘hs’, see stats.multipletesting * **alpha** (*float*) – significance level for multiple testing reject decision. * **factor\_labels** (*None**,* *list of str*) – Labels for the factor levels used for pairwise labels. If not provided, then the labels from the formula design\_info are used. | | Returns: | **results** – The results are stored as attributes, the main attributes are the following two. Other attributes are added for debugging purposes or as background information.* result\_frame : pandas DataFrame with t\_test results and multiple testing corrected p-values. * contrasts : matrix of constraints of the null hypothesis in the t\_test. | | Return type: | instance of a simple Results class | #### Notes Status: experimental. Currently only checked for treatment coding with and without specified reference level. Currently there are no multiple testing corrected confidence intervals available. #### Examples ``` >>> res = ols("np.log(Days+1) ~ C(Weight) + C(Duration)", data).fit() >>> pw = res.t_test_pairwise("C(Weight)") >>> pw.result_frame coef std err t P>|t| Conf. Int. Low 2-1 0.632315 0.230003 2.749157 8.028083e-03 0.171563 3-1 1.302555 0.230003 5.663201 5.331513e-07 0.841803 3-2 0.670240 0.230003 2.914044 5.119126e-03 0.209488 Conf. Int. Upp. pvalue-hs reject-hs 2-1 1.093067 0.010212 True 3-1 1.763307 0.000002 True 3-2 1.130992 0.010212 True ``` statsmodels statsmodels.tsa.statespace.sarimax.SARIMAXResults.conf_int statsmodels.tsa.statespace.sarimax.SARIMAXResults.conf\_int =========================================================== `SARIMAXResults.conf_int(alpha=0.05, cols=None, method='default')` Returns the confidence interval of the fitted parameters. | Parameters: | * **alpha** (*float**,* *optional*) – The significance level for the confidence interval. ie., The default `alpha` = .05 returns a 95% confidence interval. * **cols** (*array-like**,* *optional*) – `cols` specifies which confidence intervals to return * **method** (*string*) – Not Implemented Yet Method to estimate the confidence\_interval. “Default” : uses self.bse which is based on inverse Hessian for MLE “hjjh” : “jac” : “boot-bse” “boot\_quant” “profile” | | Returns: | **conf\_int** – Each row contains [lower, upper] limits of the confidence interval for the corresponding parameter. The first column contains all lower, the second column contains all upper limits. | | Return type: | array | #### Examples ``` >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> results.conf_int() array([[-5496529.48322745, -1467987.78596704], [ -177.02903529, 207.15277984], [ -0.1115811 , 0.03994274], [ -3.12506664, -0.91539297], [ -1.5179487 , -0.54850503], [ -0.56251721, 0.460309 ], [ 798.7875153 , 2859.51541392]]) ``` ``` >>> results.conf_int(cols=(2,3)) array([[-0.1115811 , 0.03994274], [-3.12506664, -0.91539297]]) ``` #### Notes The confidence interval is based on the standard normal distribution. Models wish to use a different distribution should overwrite this method. statsmodels statsmodels.stats.contingency_tables.Table.cumulative_log_oddsratios statsmodels.stats.contingency\_tables.Table.cumulative\_log\_oddsratios ======================================================================= `Table.cumulative_log_oddsratios()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table.cumulative_log_oddsratios) statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.cov_params_robust_oim statsmodels.tsa.statespace.dynamic\_factor.DynamicFactorResults.cov\_params\_robust\_oim ======================================================================================== `DynamicFactorResults.cov_params_robust_oim()` (array) The QMLE variance / covariance matrix. Computed using the method from Harvey (1989) as the evaluated hessian. statsmodels statsmodels.tsa.vector_ar.vecm.VECMResults.stderr_alpha statsmodels.tsa.vector\_ar.vecm.VECMResults.stderr\_alpha ========================================================= `VECMResults.stderr_alpha()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/vecm.html#VECMResults.stderr_alpha) statsmodels statsmodels.sandbox.distributions.extras.SkewNorm2_gen.expect statsmodels.sandbox.distributions.extras.SkewNorm2\_gen.expect ============================================================== `SkewNorm2_gen.expect(func=None, args=(), loc=0, scale=1, lb=None, ub=None, conditional=False, **kwds)` Calculate expected value of a function with respect to the distribution. The expected value of a function `f(x)` with respect to a distribution `dist` is defined as: ``` ubound E[x] = Integral(f(x) * dist.pdf(x)) lbound ``` | Parameters: | * **func** (*callable**,* *optional*) – Function for which integral is calculated. Takes only one argument. The default is the identity mapping f(x) = x. * **args** (*tuple**,* *optional*) – Shape parameters of the distribution. * **loc** (*float**,* *optional*) – Location parameter (default=0). * **scale** (*float**,* *optional*) – Scale parameter (default=1). * **ub** (*lb**,*) – Lower and upper bound for integration. Default is set to the support of the distribution. * **conditional** (*bool**,* *optional*) – If True, the integral is corrected by the conditional probability of the integration interval. The return value is the expectation of the function, conditional on being in the given interval. Default is False. * **keyword arguments are passed to the integration routine.** (*Additional*) – | | Returns: | **expect** – The calculated expected value. | | Return type: | float | #### Notes The integration behavior of this function is inherited from `integrate.quad`. statsmodels statsmodels.tsa.ar_model.AR.information statsmodels.tsa.ar\_model.AR.information ======================================== `AR.information(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/ar_model.html#AR.information) Not Implemented Yet statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.HC3_se statsmodels.sandbox.regression.gmm.IVRegressionResults.HC3\_se ============================================================== `IVRegressionResults.HC3_se()` See statsmodels.RegressionResults statsmodels statsmodels.regression.linear_model.RegressionResults.fittedvalues statsmodels.regression.linear\_model.RegressionResults.fittedvalues =================================================================== `RegressionResults.fittedvalues()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#RegressionResults.fittedvalues) statsmodels statsmodels.duration.hazard_regression.PHReg.weighted_covariate_averages statsmodels.duration.hazard\_regression.PHReg.weighted\_covariate\_averages =========================================================================== `PHReg.weighted_covariate_averages(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/duration/hazard_regression.html#PHReg.weighted_covariate_averages) Returns the hazard-weighted average of covariate values for subjects who are at-risk at a particular time. | Parameters: | **params** (*ndarray*) – Parameter vector | | Returns: | **averages** – averages[stx][i,:] is a row vector containing the weighted average values (for all the covariates) of at-risk subjects a the i^th largest observed failure time in stratum `stx`, using the hazard multipliers as weights. | | Return type: | list of ndarrays | #### Notes Used to calculate leverages and score residuals. statsmodels statsmodels.discrete.discrete_model.LogitResults.remove_data statsmodels.discrete.discrete\_model.LogitResults.remove\_data ============================================================== `LogitResults.remove_data()` remove data arrays, all nobs arrays from result and model This reduces the size of the instance, so it can be pickled with less memory. Currently tested for use with predict from an unpickled results and model instance. Warning Since data and some intermediate results have been removed calculating new statistics that require them will raise exceptions. The exception will occur the first time an attribute is accessed that has been set to None. Not fully tested for time series models, tsa, and might delete too much for prediction or not all that would be possible. The lists of arrays to delete are maintained as attributes of the result and model instance, except for cached values. These lists could be changed before calling remove\_data. The attributes to remove are named in: `model._data_attr : arrays attached to both the model instance` and the results instance with the same attribute name. `result.data_in_cache : arrays that may exist as values in` result.\_cache (TODO : should privatize name) `result._data_attr_model : arrays attached to the model` instance but not to the results instance statsmodels statsmodels.sandbox.distributions.transformed.Transf_gen.fit statsmodels.sandbox.distributions.transformed.Transf\_gen.fit ============================================================= `Transf_gen.fit(data, *args, **kwds)` Return MLEs for shape (if applicable), location, and scale parameters from data. MLE stands for Maximum Likelihood Estimate. Starting estimates for the fit are given by input arguments; for any arguments not provided with starting estimates, `self._fitstart(data)` is called to generate such. One can hold some parameters fixed to specific values by passing in keyword arguments `f0`, `f1`, …, `fn` (for shape parameters) and `floc` and `fscale` (for location and scale parameters, respectively). | Parameters: | * **data** (*array\_like*) – Data to use in calculating the MLEs. * **args** (*floats**,* *optional*) – Starting value(s) for any shape-characterizing arguments (those not provided will be determined by a call to `_fitstart(data)`). No default value. * **kwds** (*floats**,* *optional*) – Starting values for the location and scale parameters; no default. Special keyword arguments are recognized as holding certain parameters fixed: + f0…fn : hold respective shape parameters fixed. Alternatively, shape parameters to fix can be specified by name. For example, if `self.shapes == "a, b"`, `fa``and ``fix_a` are equivalent to `f0`, and `fb` and `fix_b` are equivalent to `f1`. + floc : hold location parameter fixed to specified value. + fscale : hold scale parameter fixed to specified value. + optimizer : The optimizer to use. The optimizer must take `func`, and starting position as the first two arguments, plus `args` (for extra arguments to pass to the function to be optimized) and `disp=0` to suppress output as keyword arguments. | | Returns: | **mle\_tuple** – MLEs for any shape parameters (if applicable), followed by those for location and scale. For most random variables, shape statistics will be returned, but there are exceptions (e.g. `norm`). | | Return type: | tuple of floats | #### Notes This fit is computed by maximizing a log-likelihood function, with penalty applied for samples outside of range of the distribution. The returned answer is not guaranteed to be the globally optimal MLE, it may only be locally optimal, or the optimization may fail altogether. #### Examples Generate some data to fit: draw random variates from the `beta` distribution ``` >>> from scipy.stats import beta >>> a, b = 1., 2. >>> x = beta.rvs(a, b, size=1000) ``` Now we can fit all four parameters (`a`, `b`, `loc` and `scale`): ``` >>> a1, b1, loc1, scale1 = beta.fit(x) ``` We can also use some prior knowledge about the dataset: let’s keep `loc` and `scale` fixed: ``` >>> a1, b1, loc1, scale1 = beta.fit(x, floc=0, fscale=1) >>> loc1, scale1 (0, 1) ``` We can also keep shape parameters fixed by using `f`-keywords. To keep the zero-th shape parameter `a` equal 1, use `f0=1` or, equivalently, `fa=1`: ``` >>> a1, b1, loc1, scale1 = beta.fit(x, fa=1, floc=0, fscale=1) >>> a1 1 ``` Not all distributions return estimates for the shape parameters. `norm` for example just returns estimates for location and scale: ``` >>> from scipy.stats import norm >>> x = norm.rvs(a, b, size=1000, random_state=123) >>> loc1, scale1 = norm.fit(x) >>> loc1, scale1 (0.92087172783841631, 2.0015750750324668) ``` statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.cov_params statsmodels.tsa.statespace.dynamic\_factor.DynamicFactorResults.cov\_params =========================================================================== `DynamicFactorResults.cov_params(r_matrix=None, column=None, scale=None, cov_p=None, other=None)` Returns the variance/covariance matrix. The variance/covariance matrix can be of a linear contrast of the estimates of params or all params multiplied by scale which will usually be an estimate of sigma^2. Scale is assumed to be a scalar. | Parameters: | * **r\_matrix** (*array-like*) – Can be 1d, or 2d. Can be used alone or with other. * **column** (*array-like**,* *optional*) – Must be used on its own. Can be 0d or 1d see below. * **scale** (*float**,* *optional*) – Can be specified or not. Default is None, which means that the scale argument is taken from the model. * **other** (*array-like**,* *optional*) – Can be used when r\_matrix is specified. | | Returns: | **cov** – covariance matrix of the parameter estimates or of linear combination of parameter estimates. See Notes. | | Return type: | ndarray | #### Notes (The below are assumed to be in matrix notation.) If no argument is specified returns the covariance matrix of a model `(scale)*(X.T X)^(-1)` If contrast is specified it pre and post-multiplies as follows `(scale) * r_matrix (X.T X)^(-1) r_matrix.T` If contrast and other are specified returns `(scale) * r_matrix (X.T X)^(-1) other.T` If column is specified returns `(scale) * (X.T X)^(-1)[column,column]` if column is 0d OR `(scale) * (X.T X)^(-1)[column][:,column]` if column is 1d
programming_docs
statsmodels statsmodels.tsa.vector_ar.hypothesis_test_results.NormalityTestResults.summary statsmodels.tsa.vector\_ar.hypothesis\_test\_results.NormalityTestResults.summary ================================================================================= `NormalityTestResults.summary()` statsmodels statsmodels.discrete.discrete_model.Logit.fit statsmodels.discrete.discrete\_model.Logit.fit ============================================== `Logit.fit(start_params=None, method='newton', maxiter=35, full_output=1, disp=1, callback=None, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#Logit.fit) Fit the model using maximum likelihood. The rest of the docstring is from statsmodels.base.model.LikelihoodModel.fit Fit method for likelihood based models | Parameters: | * **start\_params** (*array-like**,* *optional*) – Initial guess of the solution for the loglikelihood maximization. The default is an array of zeros. * **method** (*str**,* *optional*) – The `method` determines which solver from `scipy.optimize` is used, and it can be chosen from among the following strings: + ’newton’ for Newton-Raphson, ‘nm’ for Nelder-Mead + ’bfgs’ for Broyden-Fletcher-Goldfarb-Shanno (BFGS) + ’lbfgs’ for limited-memory BFGS with optional box constraints + ’powell’ for modified Powell’s method + ’cg’ for conjugate gradient + ’ncg’ for Newton-conjugate gradient + ’basinhopping’ for global basin-hopping solver + ’minimize’ for generic wrapper of scipy minimize (BFGS by default)The explicit arguments in `fit` are passed to the solver, with the exception of the basin-hopping solver. Each solver has several optional arguments that are not the same across solvers. See the notes section below (or scipy.optimize) for the available arguments and for the list of explicit arguments that the basin-hopping solver supports. * **maxiter** (*int**,* *optional*) – The maximum number of iterations to perform. * **full\_output** (*bool**,* *optional*) – Set to True to have all available output in the Results object’s mle\_retvals attribute. The output is dependent on the solver. See LikelihoodModelResults notes section for more information. * **disp** (*bool**,* *optional*) – Set to True to print convergence messages. * **fargs** (*tuple**,* *optional*) – Extra arguments passed to the likelihood function, i.e., loglike(x,\*args) * **callback** (*callable callback**(**xk**)**,* *optional*) – Called after each iteration, as callback(xk), where xk is the current parameter vector. * **retall** (*bool**,* *optional*) – Set to True to return list of solutions at each iteration. Available in Results object’s mle\_retvals attribute. * **skip\_hessian** (*bool**,* *optional*) – If False (default), then the negative inverse hessian is calculated after the optimization. If True, then the hessian will not be calculated. However, it will be available in methods that use the hessian in the optimization (currently only with `“newton”`). * **kwargs** (*keywords*) – All kwargs are passed to the chosen solver with one exception. The following keyword controls what happens after the fit: ``` warn_convergence : bool, optional If True, checks the model for the converged flag. If the converged flag is False, a ConvergenceWarning is issued. ``` | #### Notes The ‘basinhopping’ solver ignores `maxiter`, `retall`, `full_output` explicit arguments. Optional arguments for solvers (see returned Results.mle\_settings): ``` 'newton' tol : float Relative error in params acceptable for convergence. 'nm' -- Nelder Mead xtol : float Relative error in params acceptable for convergence ftol : float Relative error in loglike(params) acceptable for convergence maxfun : int Maximum number of function evaluations to make. 'bfgs' gtol : float Stop when norm of gradient is less than gtol. norm : float Order of norm (np.Inf is max, -np.Inf is min) epsilon If fprime is approximated, use this value for the step size. Only relevant if LikelihoodModel.score is None. 'lbfgs' m : int This many terms are used for the Hessian approximation. factr : float A stop condition that is a variant of relative error. pgtol : float A stop condition that uses the projected gradient. epsilon If fprime is approximated, use this value for the step size. Only relevant if LikelihoodModel.score is None. maxfun : int Maximum number of function evaluations to make. bounds : sequence (min, max) pairs for each element in x, defining the bounds on that parameter. Use None for one of min or max when there is no bound in that direction. 'cg' gtol : float Stop when norm of gradient is less than gtol. norm : float Order of norm (np.Inf is max, -np.Inf is min) epsilon : float If fprime is approximated, use this value for the step size. Can be scalar or vector. Only relevant if Likelihoodmodel.score is None. 'ncg' fhess_p : callable f'(x,*args) Function which computes the Hessian of f times an arbitrary vector, p. Should only be supplied if LikelihoodModel.hessian is None. avextol : float Stop when the average relative error in the minimizer falls below this amount. epsilon : float or ndarray If fhess is approximated, use this value for the step size. Only relevant if Likelihoodmodel.hessian is None. 'powell' xtol : float Line-search error tolerance ftol : float Relative error in loglike(params) for acceptable for convergence. maxfun : int Maximum number of function evaluations to make. start_direc : ndarray Initial direction set. 'basinhopping' niter : integer The number of basin hopping iterations. niter_success : integer Stop the run if the global minimum candidate remains the same for this number of iterations. T : float The "temperature" parameter for the accept or reject criterion. Higher "temperatures" mean that larger jumps in function value will be accepted. For best results `T` should be comparable to the separation (in function value) between local minima. stepsize : float Initial step size for use in the random displacement. interval : integer The interval for how often to update the `stepsize`. minimizer : dict Extra keyword arguments to be passed to the minimizer `scipy.optimize.minimize()`, for example 'method' - the minimization method (e.g. 'L-BFGS-B'), or 'tol' - the tolerance for termination. Other arguments are mapped from explicit argument of `fit`: - `args` <- `fargs` - `jac` <- `score` - `hess` <- `hess` 'minimize' min_method : str, optional Name of minimization method to use. Any method specific arguments can be passed directly. For a list of methods and their arguments, see documentation of `scipy.optimize.minimize`. If no method is specified, then BFGS is used. ``` statsmodels statsmodels.discrete.discrete_model.GeneralizedPoissonResults.summary2 statsmodels.discrete.discrete\_model.GeneralizedPoissonResults.summary2 ======================================================================= `GeneralizedPoissonResults.summary2(yname=None, xname=None, title=None, alpha=0.05, float_format='%.4f')` Experimental function to summarize regression results | Parameters: | * **xname** (*List of strings of length equal to the number of parameters*) – Names of the independent variables (optional) * **yname** (*string*) – Name of the dependent variable (optional) * **title** (*string**,* *optional*) – Title for the top table. If not None, then this replaces the default title * **alpha** (*float*) – significance level for the confidence intervals * **float\_format** (*string*) – print format for floats in parameters summary | | Returns: | **smry** – this holds the summary tables and text, which can be printed or converted to various output formats. | | Return type: | Summary instance | See also [`statsmodels.iolib.summary.Summary`](statsmodels.iolib.summary.summary#statsmodels.iolib.summary.Summary "statsmodels.iolib.summary.Summary") class to hold summary results statsmodels statsmodels.sandbox.stats.multicomp.GroupsStats.groupsswithin statsmodels.sandbox.stats.multicomp.GroupsStats.groupsswithin ============================================================= `GroupsStats.groupsswithin()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/multicomp.html#GroupsStats.groupsswithin) statsmodels statsmodels.genmod.generalized_linear_model.GLMResults.cov_params statsmodels.genmod.generalized\_linear\_model.GLMResults.cov\_params ==================================================================== `GLMResults.cov_params(r_matrix=None, column=None, scale=None, cov_p=None, other=None)` Returns the variance/covariance matrix. The variance/covariance matrix can be of a linear contrast of the estimates of params or all params multiplied by scale which will usually be an estimate of sigma^2. Scale is assumed to be a scalar. | Parameters: | * **r\_matrix** (*array-like*) – Can be 1d, or 2d. Can be used alone or with other. * **column** (*array-like**,* *optional*) – Must be used on its own. Can be 0d or 1d see below. * **scale** (*float**,* *optional*) – Can be specified or not. Default is None, which means that the scale argument is taken from the model. * **other** (*array-like**,* *optional*) – Can be used when r\_matrix is specified. | | Returns: | **cov** – covariance matrix of the parameter estimates or of linear combination of parameter estimates. See Notes. | | Return type: | ndarray | #### Notes (The below are assumed to be in matrix notation.) If no argument is specified returns the covariance matrix of a model `(scale)*(X.T X)^(-1)` If contrast is specified it pre and post-multiplies as follows `(scale) * r_matrix (X.T X)^(-1) r_matrix.T` If contrast and other are specified returns `(scale) * r_matrix (X.T X)^(-1) other.T` If column is specified returns `(scale) * (X.T X)^(-1)[column,column]` if column is 0d OR `(scale) * (X.T X)^(-1)[column][:,column]` if column is 1d statsmodels statsmodels.sandbox.distributions.transformed.LogTransf_gen.sf statsmodels.sandbox.distributions.transformed.LogTransf\_gen.sf =============================================================== `LogTransf_gen.sf(x, *args, **kwds)` Survival function (1 - `cdf`) at x of the given RV. | Parameters: | * **x** (*array\_like*) – quantiles * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **sf** – Survival function evaluated at x | | Return type: | array\_like | statsmodels statsmodels.regression.linear_model.RegressionResults.rsquared statsmodels.regression.linear\_model.RegressionResults.rsquared =============================================================== `RegressionResults.rsquared()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#RegressionResults.rsquared) statsmodels statsmodels.regression.linear_model.OLS.whiten statsmodels.regression.linear\_model.OLS.whiten =============================================== `OLS.whiten(Y)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#OLS.whiten) OLS model whitener does nothing: returns Y. statsmodels statsmodels.genmod.cov_struct.GlobalOddsRatio.pooled_odds_ratio statsmodels.genmod.cov\_struct.GlobalOddsRatio.pooled\_odds\_ratio ================================================================== `GlobalOddsRatio.pooled_odds_ratio(tables)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/cov_struct.html#GlobalOddsRatio.pooled_odds_ratio) Returns the pooled odds ratio for a list of 2x2 tables. The pooled odds ratio is the inverse variance weighted average of the sample odds ratios of the tables. statsmodels statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.prsquared statsmodels.discrete.count\_model.ZeroInflatedGeneralizedPoissonResults.prsquared ================================================================================= `ZeroInflatedGeneralizedPoissonResults.prsquared()` statsmodels statsmodels.tsa.arima_process.lpol2index statsmodels.tsa.arima\_process.lpol2index ========================================= `statsmodels.tsa.arima_process.lpol2index(ar)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_process.html#lpol2index) Remove zeros from lag polynomial | Parameters: | **ar** (*array\_like*) – coefficients of lag polynomial | | Returns: | * **coeffs** (*array*) – non-zero coefficients of lag polynomial * **index** (*array*) – index (lags) of lag polynomial with non-zero elements | statsmodels statsmodels.sandbox.distributions.transformed.TransfTwo_gen.mean statsmodels.sandbox.distributions.transformed.TransfTwo\_gen.mean ================================================================= `TransfTwo_gen.mean(*args, **kwds)` Mean of the distribution. | Parameters: | * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **mean** – the mean of the distribution | | Return type: | float | statsmodels statsmodels.genmod.generalized_estimating_equations.GEEResults.remove_data statsmodels.genmod.generalized\_estimating\_equations.GEEResults.remove\_data ============================================================================= `GEEResults.remove_data()` remove data arrays, all nobs arrays from result and model This reduces the size of the instance, so it can be pickled with less memory. Currently tested for use with predict from an unpickled results and model instance. Warning Since data and some intermediate results have been removed calculating new statistics that require them will raise exceptions. The exception will occur the first time an attribute is accessed that has been set to None. Not fully tested for time series models, tsa, and might delete too much for prediction or not all that would be possible. The lists of arrays to delete are maintained as attributes of the result and model instance, except for cached values. These lists could be changed before calling remove\_data. The attributes to remove are named in: `model._data_attr : arrays attached to both the model instance` and the results instance with the same attribute name. `result.data_in_cache : arrays that may exist as values in` result.\_cache (TODO : should privatize name) `result._data_attr_model : arrays attached to the model` instance but not to the results instance statsmodels statsmodels.tsa.statespace.varmax.VARMAXResults.test_normality statsmodels.tsa.statespace.varmax.VARMAXResults.test\_normality =============================================================== `VARMAXResults.test_normality(method)` Test for normality of standardized residuals. Null hypothesis is normality. | Parameters: | **method** (*string {'jarquebera'}* *or* *None*) – The statistical test for normality. Must be ‘jarquebera’ for Jarque-Bera normality test. If None, an attempt is made to select an appropriate test. | #### Notes If the first `d` loglikelihood values were burned (i.e. in the specified model, `loglikelihood_burn=d`), then this test is calculated ignoring the first `d` residuals. In the case of missing data, the maintained hypothesis is that the data are missing completely at random. This test is then run on the standardized residuals excluding those corresponding to missing observations. See also [`statsmodels.stats.stattools.jarque_bera`](statsmodels.stats.stattools.jarque_bera#statsmodels.stats.stattools.jarque_bera "statsmodels.stats.stattools.jarque_bera") statsmodels statsmodels.regression.linear_model.WLS.fit statsmodels.regression.linear\_model.WLS.fit ============================================ `WLS.fit(method='pinv', cov_type='nonrobust', cov_kwds=None, use_t=None, **kwargs)` Full fit of the model. The results include an estimate of covariance matrix, (whitened) residuals and an estimate of scale. | Parameters: | * **method** (*str**,* *optional*) – Can be “pinv”, “qr”. “pinv” uses the Moore-Penrose pseudoinverse to solve the least squares problem. “qr” uses the QR factorization. * **cov\_type** (*str**,* *optional*) – See `regression.linear_model.RegressionResults` for a description of the available covariance estimators * **cov\_kwds** (*list* *or* *None**,* *optional*) – See `linear_model.RegressionResults.get_robustcov_results` for a description required keywords for alternative covariance estimators * **use\_t** (*bool**,* *optional*) – Flag indicating to use the Student’s t distribution when computing p-values. Default behavior depends on cov\_type. See `linear_model.RegressionResults.get_robustcov_results` for implementation details. | | Returns: | | | Return type: | A RegressionResults class instance. | See also `regression.linear_model.RegressionResults`, `regression.linear_model.RegressionResults.get_robustcov_results` #### Notes The fit method uses the pseudoinverse of the design/exogenous variables to solve the least squares minimization. statsmodels statsmodels.tsa.arima_process.arma_acovf statsmodels.tsa.arima\_process.arma\_acovf ========================================== `statsmodels.tsa.arima_process.arma_acovf(ar, ma, nobs=10)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_process.html#arma_acovf) Theoretical autocovariance function of ARMA process | Parameters: | * **ar** (*array\_like**,* *1d*) – coefficient for autoregressive lag polynomial, including zero lag * **ma** (*array\_like**,* *1d*) – coefficient for moving-average lag polynomial, including zero lag * **nobs** (*int*) – number of terms (lags plus zero lag) to include in returned acovf | | Returns: | **acovf** – autocovariance of ARMA process given by ar, ma | | Return type: | array | See also [`arma_acf`](statsmodels.tsa.arima_process.arma_acf#statsmodels.tsa.arima_process.arma_acf "statsmodels.tsa.arima_process.arma_acf"), `acovf` #### Notes Tries to do some crude numerical speed improvements for cases with high persistence. However, this algorithm is slow if the process is highly persistent and only a few autocovariances are desired. statsmodels statsmodels.stats.contingency_tables.Table2x2.log_riskratio_confint statsmodels.stats.contingency\_tables.Table2x2.log\_riskratio\_confint ====================================================================== `Table2x2.log_riskratio_confint(alpha=0.05, method='normal')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table2x2.log_riskratio_confint) A confidence interval for the log risk ratio. | Parameters: | * **alpha** (*float*) – `1 - alpha` is the nominal coverage probability of the confidence interval. * **method** (*string*) – The method for producing the confidence interval. Currently must be ‘normal’ which uses the normal approximation. | statsmodels statsmodels.sandbox.distributions.transformed.SquareFunc.squarefunc statsmodels.sandbox.distributions.transformed.SquareFunc.squarefunc =================================================================== `SquareFunc.squarefunc(x)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/distributions/transformed.html#SquareFunc.squarefunc)
programming_docs
statsmodels statsmodels.stats.contingency_tables.Table2x2.log_riskratio_se statsmodels.stats.contingency\_tables.Table2x2.log\_riskratio\_se ================================================================= `Table2x2.log_riskratio_se()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table2x2.log_riskratio_se) statsmodels statsmodels.discrete.discrete_model.DiscreteResults.summary2 statsmodels.discrete.discrete\_model.DiscreteResults.summary2 ============================================================= `DiscreteResults.summary2(yname=None, xname=None, title=None, alpha=0.05, float_format='%.4f')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#DiscreteResults.summary2) Experimental function to summarize regression results | Parameters: | * **xname** (*List of strings of length equal to the number of parameters*) – Names of the independent variables (optional) * **yname** (*string*) – Name of the dependent variable (optional) * **title** (*string**,* *optional*) – Title for the top table. If not None, then this replaces the default title * **alpha** (*float*) – significance level for the confidence intervals * **float\_format** (*string*) – print format for floats in parameters summary | | Returns: | **smry** – this holds the summary tables and text, which can be printed or converted to various output formats. | | Return type: | Summary instance | See also [`statsmodels.iolib.summary.Summary`](statsmodels.iolib.summary.summary#statsmodels.iolib.summary.Summary "statsmodels.iolib.summary.Summary") class to hold summary results statsmodels statsmodels.regression.mixed_linear_model.MixedLMResults.f_test statsmodels.regression.mixed\_linear\_model.MixedLMResults.f\_test ================================================================== `MixedLMResults.f_test(r_matrix, cov_p=None, scale=1.0, invcov=None)` Compute the F-test for a joint linear hypothesis. This is a special case of `wald_test` that always uses the F distribution. | Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) – + array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length k row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – Default is 1.0 for no scaling. * **invcov** (*array-like**,* *optional*) – A q x q array to specify an inverse covariance matrix based on a restrictions matrix. | | Returns: | **res** – The results for the test are attributes of this results instance. | | Return type: | ContrastResults instance | #### Examples ``` >>> import numpy as np >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> A = np.identity(len(results.params)) >>> A = A[1:,:] ``` This tests that each coefficient is jointly statistically significantly different from zero. ``` >>> print(results.f_test(A)) <F test: F=array([[ 330.28533923]]), p=4.984030528700946e-10, df_denom=9, df_num=6> ``` Compare this to ``` >>> results.fvalue 330.2853392346658 >>> results.f_pvalue 4.98403096572e-10 ``` ``` >>> B = np.array(([0,0,1,-1,0,0,0],[0,0,0,0,0,1,-1])) ``` This tests that the coefficient on the 2nd and 3rd regressors are equal and jointly that the coefficient on the 5th and 6th regressors are equal. ``` >>> print(results.f_test(B)) <F test: F=array([[ 9.74046187]]), p=0.005605288531708235, df_denom=9, df_num=2> ``` Alternatively, you can specify the hypothesis tests using a string ``` >>> from statsmodels.datasets import longley >>> from statsmodels.formula.api import ols >>> dta = longley.load_pandas().data >>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' >>> results = ols(formula, dta).fit() >>> hypotheses = '(GNPDEFL = GNP), (UNEMP = 2), (YEAR/1829 = 1)' >>> f_test = results.f_test(hypotheses) >>> print(f_test) <F test: F=array([[ 144.17976065]]), p=6.322026217355609e-08, df_denom=9, df_num=3> ``` See also [`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`wald_test`](statsmodels.regression.mixed_linear_model.mixedlmresults.wald_test#statsmodels.regression.mixed_linear_model.MixedLMResults.wald_test "statsmodels.regression.mixed_linear_model.MixedLMResults.wald_test"), [`t_test`](statsmodels.regression.mixed_linear_model.mixedlmresults.t_test#statsmodels.regression.mixed_linear_model.MixedLMResults.t_test "statsmodels.regression.mixed_linear_model.MixedLMResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") #### Notes The matrix `r_matrix` is assumed to be non-singular. More precisely, r\_matrix (pX pX.T) r\_matrix.T is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full. statsmodels statsmodels.stats.contingency_tables.Table2x2.log_oddsratio_pvalue statsmodels.stats.contingency\_tables.Table2x2.log\_oddsratio\_pvalue ===================================================================== `Table2x2.log_oddsratio_pvalue(null=0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table2x2.log_oddsratio_pvalue) P-value for a hypothesis test about the log odds ratio. | Parameters: | **null** (*float*) – The null value of the log odds ratio. | statsmodels statsmodels.sandbox.stats.multicomp.MultiComparison.getranks statsmodels.sandbox.stats.multicomp.MultiComparison.getranks ============================================================ `MultiComparison.getranks()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/multicomp.html#MultiComparison.getranks) convert data to rankdata and attach This creates rankdata as it is used for non-parametric tests, where in the case of ties the average rank is assigned. statsmodels statsmodels.tsa.statespace.varmax.VARMAXResults.hqic statsmodels.tsa.statespace.varmax.VARMAXResults.hqic ==================================================== `VARMAXResults.hqic()` (float) Hannan-Quinn Information Criterion statsmodels statsmodels.discrete.discrete_model.Logit.loglike statsmodels.discrete.discrete\_model.Logit.loglike ================================================== `Logit.loglike(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#Logit.loglike) Log-likelihood of logit model. | Parameters: | **params** (*array-like*) – The parameters of the logit model. | | Returns: | **loglike** – The log-likelihood function of the model evaluated at `params`. See notes. | | Return type: | float | #### Notes \[\ln L=\sum\_{i}\ln\Lambda\left(q\_{i}x\_{i}^{\prime}\beta\right)\] Where \(q=2y-1\). This simplification comes from the fact that the logistic distribution is symmetric. statsmodels statsmodels.tsa.holtwinters.ExponentialSmoothing.hessian statsmodels.tsa.holtwinters.ExponentialSmoothing.hessian ======================================================== `ExponentialSmoothing.hessian(params)` The Hessian matrix of the model statsmodels statsmodels.nonparametric.kde.KDEUnivariate.cdf statsmodels.nonparametric.kde.KDEUnivariate.cdf =============================================== `KDEUnivariate.cdf()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/nonparametric/kde.html#KDEUnivariate.cdf) Returns the cumulative distribution function evaluated at the support. #### Notes Will not work if fit has not been called. statsmodels statsmodels.discrete.discrete_model.Logit.initialize statsmodels.discrete.discrete\_model.Logit.initialize ===================================================== `Logit.initialize()` Initialize is called by statsmodels.model.LikelihoodModel.\_\_init\_\_ and should contain any preprocessing that needs to be done for a model. statsmodels statsmodels.stats.weightstats.DescrStatsW statsmodels.stats.weightstats.DescrStatsW ========================================= `class statsmodels.stats.weightstats.DescrStatsW(data, weights=None, ddof=0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/weightstats.html#DescrStatsW) descriptive statistics and tests with weights for case weights Assumes that the data is 1d or 2d with (nobs, nvars) observations in rows, variables in columns, and that the same weight applies to each column. If degrees of freedom correction is used, then weights should add up to the number of observations. ttest also assumes that the sum of weights corresponds to the sample size. This is essentially the same as replicating each observations by its weight, if the weights are integers, often called case or frequency weights. | Parameters: | * **data** (*array\_like**,* *1-D* *or* *2-D*) – dataset * **weights** (*None* *or* *1-D ndarray*) – weights for each observation, with same length as zero axis of data * **ddof** (*int*) – default ddof=0, degrees of freedom correction used for second moments, var, std, cov, corrcoef. However, statistical tests are independent of `ddof`, based on the standard formulas. | #### Examples ``` >>> import numpy as np >>> np.random.seed(0) >>> x1_2d = 1.0 + np.random.randn(20, 3) >>> w1 = np.random.randint(1, 4, 20) >>> d1 = DescrStatsW(x1_2d, weights=w1) >>> d1.mean array([ 1.42739844, 1.23174284, 1.083753 ]) >>> d1.var array([ 0.94855633, 0.52074626, 1.12309325]) >>> d1.std_mean array([ 0.14682676, 0.10878944, 0.15976497]) ``` ``` >>> tstat, pval, df = d1.ttest_mean(0) >>> tstat; pval; df array([ 9.72165021, 11.32226471, 6.78342055]) array([ 1.58414212e-12, 1.26536887e-14, 2.37623126e-08]) 44.0 ``` ``` >>> tstat, pval, df = d1.ttest_mean([0, 1, 1]) >>> tstat; pval; df array([ 9.72165021, 2.13019609, 0.52422632]) array([ 1.58414212e-12, 3.87842808e-02, 6.02752170e-01]) 44.0 ``` #if weiqhts are integers, then asrepeats can be used ``` >>> x1r = d1.asrepeats() >>> x1r.shape ... >>> stats.ttest_1samp(x1r, [0, 1, 1]) ... ``` #### Methods | | | | --- | --- | | [`asrepeats`](statsmodels.stats.weightstats.descrstatsw.asrepeats#statsmodels.stats.weightstats.DescrStatsW.asrepeats "statsmodels.stats.weightstats.DescrStatsW.asrepeats")() | get array that has repeats given by floor(weights) | | [`corrcoef`](statsmodels.stats.weightstats.descrstatsw.corrcoef#statsmodels.stats.weightstats.DescrStatsW.corrcoef "statsmodels.stats.weightstats.DescrStatsW.corrcoef")() | weighted correlation with default ddof | | [`cov`](statsmodels.stats.weightstats.descrstatsw.cov#statsmodels.stats.weightstats.DescrStatsW.cov "statsmodels.stats.weightstats.DescrStatsW.cov")() | weighted covariance of data if data is 2 dimensional | | [`demeaned`](statsmodels.stats.weightstats.descrstatsw.demeaned#statsmodels.stats.weightstats.DescrStatsW.demeaned "statsmodels.stats.weightstats.DescrStatsW.demeaned")() | data with weighted mean subtracted | | [`get_compare`](statsmodels.stats.weightstats.descrstatsw.get_compare#statsmodels.stats.weightstats.DescrStatsW.get_compare "statsmodels.stats.weightstats.DescrStatsW.get_compare")(other[, weights]) | return an instance of CompareMeans with self and other | | [`mean`](statsmodels.stats.weightstats.descrstatsw.mean#statsmodels.stats.weightstats.DescrStatsW.mean "statsmodels.stats.weightstats.DescrStatsW.mean")() | weighted mean of data | | [`nobs`](statsmodels.stats.weightstats.descrstatsw.nobs#statsmodels.stats.weightstats.DescrStatsW.nobs "statsmodels.stats.weightstats.DescrStatsW.nobs")() | alias for number of observations/cases, equal to sum of weights | | [`quantile`](statsmodels.stats.weightstats.descrstatsw.quantile#statsmodels.stats.weightstats.DescrStatsW.quantile "statsmodels.stats.weightstats.DescrStatsW.quantile")(probs[, return\_pandas]) | Compute quantiles for a weighted sample. | | [`std`](statsmodels.stats.weightstats.descrstatsw.std#statsmodels.stats.weightstats.DescrStatsW.std "statsmodels.stats.weightstats.DescrStatsW.std")() | standard deviation with default degrees of freedom correction | | [`std_ddof`](statsmodels.stats.weightstats.descrstatsw.std_ddof#statsmodels.stats.weightstats.DescrStatsW.std_ddof "statsmodels.stats.weightstats.DescrStatsW.std_ddof")([ddof]) | standard deviation of data with given ddof | | [`std_mean`](statsmodels.stats.weightstats.descrstatsw.std_mean#statsmodels.stats.weightstats.DescrStatsW.std_mean "statsmodels.stats.weightstats.DescrStatsW.std_mean")() | standard deviation of weighted mean | | [`sum`](statsmodels.stats.weightstats.descrstatsw.sum#statsmodels.stats.weightstats.DescrStatsW.sum "statsmodels.stats.weightstats.DescrStatsW.sum")() | weighted sum of data | | [`sum_weights`](statsmodels.stats.weightstats.descrstatsw.sum_weights#statsmodels.stats.weightstats.DescrStatsW.sum_weights "statsmodels.stats.weightstats.DescrStatsW.sum_weights")() | | | [`sumsquares`](statsmodels.stats.weightstats.descrstatsw.sumsquares#statsmodels.stats.weightstats.DescrStatsW.sumsquares "statsmodels.stats.weightstats.DescrStatsW.sumsquares")() | weighted sum of squares of demeaned data | | [`tconfint_mean`](statsmodels.stats.weightstats.descrstatsw.tconfint_mean#statsmodels.stats.weightstats.DescrStatsW.tconfint_mean "statsmodels.stats.weightstats.DescrStatsW.tconfint_mean")([alpha, alternative]) | two-sided confidence interval for weighted mean of data | | [`ttest_mean`](statsmodels.stats.weightstats.descrstatsw.ttest_mean#statsmodels.stats.weightstats.DescrStatsW.ttest_mean "statsmodels.stats.weightstats.DescrStatsW.ttest_mean")([value, alternative]) | ttest of Null hypothesis that mean is equal to value. | | [`ttost_mean`](statsmodels.stats.weightstats.descrstatsw.ttost_mean#statsmodels.stats.weightstats.DescrStatsW.ttost_mean "statsmodels.stats.weightstats.DescrStatsW.ttost_mean")(low, upp) | test of (non-)equivalence of one sample | | [`var`](statsmodels.stats.weightstats.descrstatsw.var#statsmodels.stats.weightstats.DescrStatsW.var "statsmodels.stats.weightstats.DescrStatsW.var")() | variance with default degrees of freedom correction | | [`var_ddof`](statsmodels.stats.weightstats.descrstatsw.var_ddof#statsmodels.stats.weightstats.DescrStatsW.var_ddof "statsmodels.stats.weightstats.DescrStatsW.var_ddof")([ddof]) | variance of data given ddof | | [`zconfint_mean`](statsmodels.stats.weightstats.descrstatsw.zconfint_mean#statsmodels.stats.weightstats.DescrStatsW.zconfint_mean "statsmodels.stats.weightstats.DescrStatsW.zconfint_mean")([alpha, alternative]) | two-sided confidence interval for weighted mean of data | | [`ztest_mean`](statsmodels.stats.weightstats.descrstatsw.ztest_mean#statsmodels.stats.weightstats.DescrStatsW.ztest_mean "statsmodels.stats.weightstats.DescrStatsW.ztest_mean")([value, alternative]) | z-test of Null hypothesis that mean is equal to value. | | [`ztost_mean`](statsmodels.stats.weightstats.descrstatsw.ztost_mean#statsmodels.stats.weightstats.DescrStatsW.ztost_mean "statsmodels.stats.weightstats.DescrStatsW.ztost_mean")(low, upp) | test of (non-)equivalence of one sample, based on z-test | statsmodels statsmodels.tools.eval_measures.rmse statsmodels.tools.eval\_measures.rmse ===================================== `statsmodels.tools.eval_measures.rmse(x1, x2, axis=0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tools/eval_measures.html#rmse) root mean squared error | Parameters: | * **x2** (*x1**,*) – The performance measure depends on the difference between these two arrays. * **axis** (*int*) – axis along which the summary statistic is calculated | | Returns: | **rmse** – root mean squared error along given axis. | | Return type: | ndarray or float | #### Notes If `x1` and `x2` have different shapes, then they need to broadcast. This uses `numpy.asanyarray` to convert the input. Whether this is the desired result or not depends on the array subclass, for example numpy matrices will silently produce an incorrect result. statsmodels statsmodels.sandbox.distributions.extras.SkewNorm2_gen.nnlf statsmodels.sandbox.distributions.extras.SkewNorm2\_gen.nnlf ============================================================ `SkewNorm2_gen.nnlf(theta, x)` Return negative loglikelihood function. #### Notes This is `-sum(log pdf(x, theta), axis=0)` where `theta` are the parameters (including loc and scale). statsmodels statsmodels.iolib.smpickle.save_pickle statsmodels.iolib.smpickle.save\_pickle ======================================= `statsmodels.iolib.smpickle.save_pickle(obj, fname)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/iolib/smpickle.html#save_pickle) Save the object to file via pickling. | Parameters: | **fname** (*str*) – Filename to pickle to | statsmodels statsmodels.tsa.vector_ar.vecm.VECMResults.pvalues_det_coef statsmodels.tsa.vector\_ar.vecm.VECMResults.pvalues\_det\_coef ============================================================== `VECMResults.pvalues_det_coef()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/vecm.html#VECMResults.pvalues_det_coef) statsmodels statsmodels.discrete.discrete_model.GeneralizedPoissonResults.llnull statsmodels.discrete.discrete\_model.GeneralizedPoissonResults.llnull ===================================================================== `GeneralizedPoissonResults.llnull()` statsmodels statsmodels.robust.robust_linear_model.RLMResults.initialize statsmodels.robust.robust\_linear\_model.RLMResults.initialize ============================================================== `RLMResults.initialize(model, params, **kwd)` statsmodels statsmodels.sandbox.regression.gmm.IVGMM.gmmobjective statsmodels.sandbox.regression.gmm.IVGMM.gmmobjective ===================================================== `IVGMM.gmmobjective(params, weights)` objective function for GMM minimization | Parameters: | * **params** (*array*) – parameter values at which objective is evaluated * **weights** (*array*) – weighting matrix | | Returns: | **jval** – value of objective function | | Return type: | float | statsmodels statsmodels.robust.norms.RamsayE.psi statsmodels.robust.norms.RamsayE.psi ==================================== `RamsayE.psi(z)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/norms.html#RamsayE.psi) The psi function for Ramsay’s Ea estimator The analytic derivative of rho | Parameters: | **z** (*array-like*) – 1d array | | Returns: | **psi** – psi(z) = z\*exp(-a\*|z|) | | Return type: | array | statsmodels statsmodels.sandbox.distributions.transformed.LogTransf_gen.fit_loc_scale statsmodels.sandbox.distributions.transformed.LogTransf\_gen.fit\_loc\_scale ============================================================================ `LogTransf_gen.fit_loc_scale(data, *args)` Estimate loc and scale parameters from data using 1st and 2nd moments. | Parameters: | * **data** (*array\_like*) – Data to fit. * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information). | | Returns: | * **Lhat** (*float*) – Estimated location parameter for the data. * **Shat** (*float*) – Estimated scale parameter for the data. |
programming_docs
statsmodels statsmodels.stats.contingency_tables.Table2x2.riskratio statsmodels.stats.contingency\_tables.Table2x2.riskratio ======================================================== `Table2x2.riskratio()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table2x2.riskratio) statsmodels statsmodels.stats.contingency_tables.Table.local_log_oddsratios statsmodels.stats.contingency\_tables.Table.local\_log\_oddsratios ================================================================== `Table.local_log_oddsratios()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table.local_log_oddsratios) statsmodels statsmodels.regression.linear_model.GLSAR.hessian statsmodels.regression.linear\_model.GLSAR.hessian ================================================== `GLSAR.hessian(params)` The Hessian matrix of the model statsmodels statsmodels.tsa.statespace.mlemodel.MLEResults.summary statsmodels.tsa.statespace.mlemodel.MLEResults.summary ====================================================== `MLEResults.summary(alpha=0.05, start=None, title=None, model_name=None, display_params=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEResults.summary) Summarize the Model | Parameters: | * **alpha** (*float**,* *optional*) – Significance level for the confidence intervals. Default is 0.05. * **start** (*int**,* *optional*) – Integer of the start observation. Default is 0. * **model\_name** (*string*) – The name of the model used. Default is to use model class name. | | Returns: | **summary** – This holds the summary table and text, which can be printed or converted to various output formats. | | Return type: | Summary instance | See also [`statsmodels.iolib.summary.Summary`](statsmodels.iolib.summary.summary#statsmodels.iolib.summary.Summary "statsmodels.iolib.summary.Summary") statsmodels statsmodels.tsa.statespace.varmax.VARMAX.predict statsmodels.tsa.statespace.varmax.VARMAX.predict ================================================ `VARMAX.predict(params, exog=None, *args, **kwargs)` After a model has been fit predict returns the fitted values. This is a placeholder intended to be overwritten by individual models. statsmodels statsmodels.regression.quantile_regression.QuantRegResults.get_robustcov_results statsmodels.regression.quantile\_regression.QuantRegResults.get\_robustcov\_results =================================================================================== `QuantRegResults.get_robustcov_results(cov_type='HC1', use_t=None, **kwds)` create new results instance with robust covariance as default | Parameters: | * **cov\_type** (*string*) – the type of robust sandwich estimator to use. see Notes below * **use\_t** (*bool*) – If true, then the t distribution is used for inference. If false, then the normal distribution is used. If `use_t` is None, then an appropriate default is used, which is `true` if the cov\_type is nonrobust, and `false` in all other cases. * **kwds** (*depends on cov\_type*) – Required or optional arguments for robust covariance calculation. see Notes below | | Returns: | **results** – This method creates a new results instance with the requested robust covariance as the default covariance of the parameters. Inferential statistics like p-values and hypothesis tests will be based on this covariance matrix. | | Return type: | results instance | #### Notes The following covariance types and required or optional arguments are currently available: * ‘fixed scale’ and optional keyword argument ‘scale’ which uses a predefined scale estimate with default equal to one. * ‘HC0’, ‘HC1’, ‘HC2’, ‘HC3’ and no keyword arguments: heteroscedasticity robust covariance * ‘HAC’ and keywords + `maxlag` integer (required) : number of lags to use + `kernel callable or str (optional) : kernel` currently available kernels are [‘bartlett’, ‘uniform’], default is Bartlett + `use_correction bool (optional) : If true, use small sample` correction * ‘cluster’ and required keyword `groups`, integer group indicator + `groups array_like, integer (required) :` index of clusters or groups + `use_correction bool (optional) :` If True the sandwich covariance is calculated with a small sample correction. If False the sandwich covariance is calculated without small sample correction. + `df_correction bool (optional)` If True (default), then the degrees of freedom for the inferential statistics and hypothesis tests, such as pvalues, f\_pvalue, conf\_int, and t\_test and f\_test, are based on the number of groups minus one instead of the total number of observations minus the number of explanatory variables. `df_resid` of the results instance is adjusted. If False, then `df_resid` of the results instance is not adjusted. * ‘hac-groupsum’ Driscoll and Kraay, heteroscedasticity and autocorrelation robust standard errors in panel data keywords + `time` array\_like (required) : index of time periods + `maxlag` integer (required) : number of lags to use + `kernel callable or str (optional) : kernel` currently available kernels are [‘bartlett’, ‘uniform’], default is Bartlett + `use_correction False or string in [‘hac’, ‘cluster’] (optional) :` If False the the sandwich covariance is calulated without small sample correction. If `use_correction = ‘cluster’` (default), then the same small sample correction as in the case of ‘covtype=’cluster’’ is used. + `df_correction bool (optional)` adjustment to df\_resid, see cov\_type ‘cluster’ above # TODO: we need more options here * ‘hac-panel’ heteroscedasticity and autocorrelation robust standard errors in panel data. The data needs to be sorted in this case, the time series for each panel unit or cluster need to be stacked. The membership to a timeseries of an individual or group can be either specified by group indicators or by increasing time periods. keywords + either `groups` or `time` : array\_like (required) `groups` : indicator for groups `time` : index of time periods + `maxlag` integer (required) : number of lags to use + `kernel callable or str (optional) : kernel` currently available kernels are [‘bartlett’, ‘uniform’], default is Bartlett + `use_correction False or string in [‘hac’, ‘cluster’] (optional) :` If False the sandwich covariance is calculated without small sample correction. + `df_correction bool (optional)` adjustment to df\_resid, see cov\_type ‘cluster’ above # TODO: we need more options here Reminder: `use_correction` in “hac-groupsum” and “hac-panel” is not bool, needs to be in [False, ‘hac’, ‘cluster’] TODO: Currently there is no check for extra or misspelled keywords, except in the case of cov\_type `HCx` statsmodels statsmodels.duration.hazard_regression.PHReg.score statsmodels.duration.hazard\_regression.PHReg.score =================================================== `PHReg.score(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/duration/hazard_regression.html#PHReg.score) Returns the score function evaluated at `params`. statsmodels statsmodels.stats.sandwich_covariance.cov_cluster_2groups statsmodels.stats.sandwich\_covariance.cov\_cluster\_2groups ============================================================ `statsmodels.stats.sandwich_covariance.cov_cluster_2groups(results, group, group2=None, use_correction=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/sandwich_covariance.html#cov_cluster_2groups) cluster robust covariance matrix for two groups/clusters | Parameters: | * **results** (*result instance*) – result of a regression, uses results.model.exog and results.resid TODO: this should use wexog instead * **use\_correction** (*bool*) – If true (default), then the small sample correction factor is used. | | Returns: | * **cov\_both** (*ndarray, (k\_vars, k\_vars)*) – cluster robust covariance matrix for parameter estimates, for both clusters * **cov\_0** (*ndarray, (k\_vars, k\_vars)*) – cluster robust covariance matrix for parameter estimates for first cluster * **cov\_1** (*ndarray, (k\_vars, k\_vars)*) – cluster robust covariance matrix for parameter estimates for second cluster | #### Notes verified against Peterson’s table, (4 decimal print precision) statsmodels statsmodels.sandbox.distributions.extras.SkewNorm2_gen.logcdf statsmodels.sandbox.distributions.extras.SkewNorm2\_gen.logcdf ============================================================== `SkewNorm2_gen.logcdf(x, *args, **kwds)` Log of the cumulative distribution function at x of the given RV. | Parameters: | * **x** (*array\_like*) – quantiles * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **logcdf** – Log of the cumulative distribution function evaluated at x | | Return type: | array\_like | statsmodels statsmodels.regression.linear_model.RegressionResults.HC1_se statsmodels.regression.linear\_model.RegressionResults.HC1\_se ============================================================== `RegressionResults.HC1_se()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#RegressionResults.HC1_se) See statsmodels.RegressionResults statsmodels statsmodels.tsa.statespace.mlemodel.MLEResults.llf statsmodels.tsa.statespace.mlemodel.MLEResults.llf ================================================== `MLEResults.llf()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEResults.llf) (float) The value of the log-likelihood function evaluated at `params`. statsmodels statsmodels.sandbox.distributions.transformed.TransfTwo_gen.rvs statsmodels.sandbox.distributions.transformed.TransfTwo\_gen.rvs ================================================================ `TransfTwo_gen.rvs(*args, **kwds)` Random variates of given type. | Parameters: | * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information). * **loc** (*array\_like**,* *optional*) – Location parameter (default=0). * **scale** (*array\_like**,* *optional*) – Scale parameter (default=1). * **size** (*int* *or* *tuple of ints**,* *optional*) – Defining number of random variates (default is 1). * **random\_state** (None or int or `np.random.RandomState` instance, optional) – If int or RandomState, use it for drawing the random variates. If None, rely on `self.random_state`. Default is None. | | Returns: | **rvs** – Random variates of given `size`. | | Return type: | ndarray or scalar | statsmodels statsmodels.genmod.bayes_mixed_glm.PoissonBayesMixedGLM.vb_elbo_grad statsmodels.genmod.bayes\_mixed\_glm.PoissonBayesMixedGLM.vb\_elbo\_grad ======================================================================== `PoissonBayesMixedGLM.vb_elbo_grad(vb_mean, vb_sd)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/bayes_mixed_glm.html#PoissonBayesMixedGLM.vb_elbo_grad) Returns the gradient of the model’s evidence lower bound (ELBO). statsmodels statsmodels.genmod.families.links.inverse_power statsmodels.genmod.families.links.inverse\_power ================================================ `class statsmodels.genmod.families.links.inverse_power` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/links.html#inverse_power) The inverse transform #### Notes g(p) = 1/p Alias of statsmodels.family.links.Power(power=-1.) #### Methods | | | | --- | --- | | [`deriv`](statsmodels.genmod.families.links.inverse_power.deriv#statsmodels.genmod.families.links.inverse_power.deriv "statsmodels.genmod.families.links.inverse_power.deriv")(p) | Derivative of the power transform | | [`deriv2`](statsmodels.genmod.families.links.inverse_power.deriv2#statsmodels.genmod.families.links.inverse_power.deriv2 "statsmodels.genmod.families.links.inverse_power.deriv2")(p) | Second derivative of the power transform | | [`inverse`](statsmodels.genmod.families.links.inverse_power.inverse#statsmodels.genmod.families.links.inverse_power.inverse "statsmodels.genmod.families.links.inverse_power.inverse")(z) | Inverse of the power transform link function | | [`inverse_deriv`](statsmodels.genmod.families.links.inverse_power.inverse_deriv#statsmodels.genmod.families.links.inverse_power.inverse_deriv "statsmodels.genmod.families.links.inverse_power.inverse_deriv")(z) | Derivative of the inverse of the power transform | statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.pvalues statsmodels.tsa.statespace.dynamic\_factor.DynamicFactorResults.pvalues ======================================================================= `DynamicFactorResults.pvalues()` (array) The p-values associated with the z-statistics of the coefficients. Note that the coefficients are assumed to have a Normal distribution. statsmodels statsmodels.genmod.generalized_linear_model.GLMResults.remove_data statsmodels.genmod.generalized\_linear\_model.GLMResults.remove\_data ===================================================================== `GLMResults.remove_data()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_linear_model.html#GLMResults.remove_data) remove data arrays, all nobs arrays from result and model This reduces the size of the instance, so it can be pickled with less memory. Currently tested for use with predict from an unpickled results and model instance. Warning Since data and some intermediate results have been removed calculating new statistics that require them will raise exceptions. The exception will occur the first time an attribute is accessed that has been set to None. Not fully tested for time series models, tsa, and might delete too much for prediction or not all that would be possible. The lists of arrays to delete are maintained as attributes of the result and model instance, except for cached values. These lists could be changed before calling remove\_data. The attributes to remove are named in: `model._data_attr : arrays attached to both the model instance` and the results instance with the same attribute name. `result.data_in_cache : arrays that may exist as values in` result.\_cache (TODO : should privatize name) `result._data_attr_model : arrays attached to the model` instance but not to the results instance statsmodels statsmodels.discrete.discrete_model.LogitResults.summary statsmodels.discrete.discrete\_model.LogitResults.summary ========================================================= `LogitResults.summary(yname=None, xname=None, title=None, alpha=0.05, yname_list=None)` Summarize the Regression Results | Parameters: | * **yname** (*string**,* *optional*) – Default is `y` * **xname** (*list of strings**,* *optional*) – Default is `var_##` for ## in p the number of regressors * **title** (*string**,* *optional*) – Title for the top table. If not None, then this replaces the default title * **alpha** (*float*) – significance level for the confidence intervals | | Returns: | **smry** – this holds the summary tables and text, which can be printed or converted to various output formats. | | Return type: | Summary instance | See also [`statsmodels.iolib.summary.Summary`](statsmodels.iolib.summary.summary#statsmodels.iolib.summary.Summary "statsmodels.iolib.summary.Summary") class to hold summary results statsmodels statsmodels.duration.hazard_regression.PHRegResults.martingale_residuals statsmodels.duration.hazard\_regression.PHRegResults.martingale\_residuals ========================================================================== `PHRegResults.martingale_residuals()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/duration/hazard_regression.html#PHRegResults.martingale_residuals) The martingale residuals. statsmodels statsmodels.stats.contingency_tables.Table2x2.from_data statsmodels.stats.contingency\_tables.Table2x2.from\_data ========================================================= `classmethod Table2x2.from_data(data, shift_zeros=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table2x2.from_data) Construct a Table object from data. | Parameters: | * **data** (*array-like*) – The raw data, the first column defines the rows and the second column defines the columns. * **shift\_zeros** (*boolean*) – If True, and if there are any zeros in the contingency table, add 0.5 to all four cells of the table. | statsmodels statsmodels.tsa.arima_process.arma_periodogram statsmodels.tsa.arima\_process.arma\_periodogram ================================================ `statsmodels.tsa.arima_process.arma_periodogram(ar, ma, worN=None, whole=0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_process.html#arma_periodogram) Periodogram for ARMA process given by lag-polynomials ar and ma | Parameters: | * **ar** (*array\_like*) – autoregressive lag-polynomial with leading 1 and lhs sign * **ma** (*array\_like*) – moving average lag-polynomial with leading 1 * **worN** (*{None**,* *int}**,* *optional*) – option for scipy.signal.freqz (read “w or N”) If None, then compute at 512 frequencies around the unit circle. If a single integer, the compute at that many frequencies. Otherwise, compute the response at frequencies given in worN * **whole** (*{0**,**1}**,* *optional*) – options for scipy.signal.freqz Normally, frequencies are computed from 0 to pi (upper-half of unit-circle. If whole is non-zero compute frequencies from 0 to 2\*pi. | | Returns: | * **w** (*array*) – frequencies * **sd** (*array*) – periodogram, spectral density | #### Notes Normalization ? This uses signal.freqz, which does not use fft. There is a fft version somewhere. statsmodels statsmodels.regression.quantile_regression.QuantRegResults.pvalues statsmodels.regression.quantile\_regression.QuantRegResults.pvalues =================================================================== `QuantRegResults.pvalues()` statsmodels statsmodels.tsa.statespace.mlemodel.MLEResults.normalized_cov_params statsmodels.tsa.statespace.mlemodel.MLEResults.normalized\_cov\_params ====================================================================== `MLEResults.normalized_cov_params()` statsmodels statsmodels.tsa.statespace.sarimax.SARIMAX.filter statsmodels.tsa.statespace.sarimax.SARIMAX.filter ================================================= `SARIMAX.filter(params, transformed=True, complex_step=False, cov_type=None, cov_kwds=None, return_ssm=False, results_class=None, results_wrapper_class=None, **kwargs)` Kalman filtering | Parameters: | * **params** (*array\_like*) – Array of parameters at which to evaluate the loglikelihood function. * **transformed** (*boolean**,* *optional*) – Whether or not `params` is already transformed. Default is True. * **return\_ssm** (*boolean**,**optional*) – Whether or not to return only the state space output or a full results object. Default is to return a full results object. * **cov\_type** (*str**,* *optional*) – See `MLEResults.fit` for a description of covariance matrix types for results object. * **cov\_kwds** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)") *or* *None**,* *optional*) – See `MLEResults.get_robustcov_results` for a description required keywords for alternative covariance estimators * **\*\*kwargs** – Additional keyword arguments to pass to the Kalman filter. See `KalmanFilter.filter` for more details. |
programming_docs
statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.predict statsmodels.tsa.statespace.dynamic\_factor.DynamicFactorResults.predict ======================================================================= `DynamicFactorResults.predict(start=None, end=None, dynamic=False, **kwargs)` In-sample prediction and out-of-sample forecasting | Parameters: | * **start** (*int**,* *str**, or* *datetime**,* *optional*) – Zero-indexed observation number at which to start forecasting, i.e., the first forecast is start. Can also be a date string to parse or a datetime type. Default is the the zeroth observation. * **end** (*int**,* *str**, or* *datetime**,* *optional*) – Zero-indexed observation number at which to end forecasting, i.e., the last forecast is end. Can also be a date string to parse or a datetime type. However, if the dates index does not have a fixed frequency, end must be an integer index if you want out of sample prediction. Default is the last observation in the sample. * **dynamic** (*boolean**,* *int**,* *str**, or* *datetime**,* *optional*) – Integer offset relative to `start` at which to begin dynamic prediction. Can also be an absolute date string to parse or a datetime type (these are not interpreted as offsets). Prior to this observation, true endogenous values will be used for prediction; starting with this observation and continuing through the end of prediction, forecasted endogenous values will be used instead. * **\*\*kwargs** – Additional arguments may required for forecasting beyond the end of the sample. See `FilterResults.predict` for more details. | | Returns: | **forecast** – Array of out of in-sample predictions and / or out-of-sample forecasts. An (npredict x k\_endog) array. | | Return type: | array | statsmodels statsmodels.robust.norms.Hampel.psi_deriv statsmodels.robust.norms.Hampel.psi\_deriv ========================================== `Hampel.psi_deriv(z)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/norms.html#Hampel.psi_deriv) Deriative of psi. Used to obtain robust covariance matrix. See statsmodels.rlm for more information. Abstract method: psi\_derive = psi’ statsmodels statsmodels.sandbox.regression.gmm.LinearIVGMM.fit statsmodels.sandbox.regression.gmm.LinearIVGMM.fit ================================================== `LinearIVGMM.fit(start_params=None, maxiter=10, inv_weights=None, weights_method='cov', wargs=(), has_optimal_weights=True, optim_method='bfgs', optim_args=None)` Estimate parameters using GMM and return GMMResults TODO: weight and covariance arguments still need to be made consistent with similar options in other models, see RegressionResult.get\_robustcov\_results | Parameters: | * **start\_params** (*array* *(**optional**)*) – starting value for parameters ub minimization. If None then fitstart method is called for the starting values. * **maxiter** (*int* *or* *'cue'*) – Number of iterations in iterated GMM. The onestep estimate can be obtained with maxiter=0 or 1. If maxiter is large, then the iteration will stop either at maxiter or on convergence of the parameters (TODO: no options for convergence criteria yet.) If `maxiter == ‘cue’`, the the continuously updated GMM is calculated which updates the weight matrix during the minimization of the GMM objective function. The CUE estimation uses the onestep parameters as starting values. * **inv\_weights** (*None* *or* *ndarray*) – inverse of the starting weighting matrix. If inv\_weights are not given then the method `start_weights` is used which depends on the subclass, for IV subclasses `inv_weights = z’z` where `z` are the instruments, otherwise an identity matrix is used. * **weights\_method** (*string**,* *defines method for robust*) – Options here are similar to `statsmodels.stats.robust_covariance` default is heteroscedasticity consistent, HC0 currently available methods are + `cov` : HC0, optionally with degrees of freedom correction + `hac` : + `iid` : untested, only for Z\*u case, IV cases with u as error indep of Z + `ac` : not available yet + `cluster` : not connected yet + others from robust\_covariance * **wargs`** (*tuple* *or* [dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")*,*) – required and optional arguments for weights\_method + `centered` : bool, indicates whether moments are centered for the calculation of the weights and covariance matrix, applies to all weight\_methods + `ddof` : int degrees of freedom correction, applies currently only to `cov` + `maxlag` : int number of lags to include in HAC calculation , applies only to `hac` + others not yet, e.g. groups for cluster robust * **has\_optimal\_weights** (*If true**,* *then the calculation of the covariance*) – matrix assumes that we have optimal GMM with \(W = S^{-1}\). Default is True. TODO: do we want to have a different default after `onestep`? * **optim\_method** (*string**,* *default is 'bfgs'*) – numerical optimization method. Currently not all optimizers that are available in LikelihoodModels are connected. * **optim\_args** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")) – keyword arguments for the numerical optimizer. | | Returns: | **results** – this is also attached as attribute results | | Return type: | instance of GMMResults | #### Notes Warning: One-step estimation, `maxiter` either 0 or 1, still has problems (at least compared to Stata’s gmm). By default it uses a heteroscedasticity robust covariance matrix, but uses the assumption that the weight matrix is optimal. See options for cov\_params in the results instance. The same options as for weight matrix also apply to the calculation of the estimate of the covariance matrix of the parameter estimates. statsmodels statsmodels.tsa.statespace.mlemodel.MLEResults.llf_obs statsmodels.tsa.statespace.mlemodel.MLEResults.llf\_obs ======================================================= `MLEResults.llf_obs()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEResults.llf_obs) (float) The value of the log-likelihood function evaluated at `params`. statsmodels statsmodels.genmod.bayes_mixed_glm.BinomialBayesMixedGLM.fit_vb statsmodels.genmod.bayes\_mixed\_glm.BinomialBayesMixedGLM.fit\_vb ================================================================== `BinomialBayesMixedGLM.fit_vb(mean=None, sd=None, fit_method='BFGS', minim_opts=None, verbose=False)` Fit a model using the variational Bayes mean field approximation. | Parameters: | * **mean** (*array-like*) – Starting value for VB mean vector * **sd** (*array-like*) – Starting value for VB standard deviation vector * **fit\_method** (*string*) – Algorithm for scipy.minimize * **minim\_opts** (*dict-like*) – Options passed to scipy.minimize * **verbose** (*bool*) – If True, print the gradient norm to the screen each time it is calculated. | #### Notes The goal is to find a factored Gaussian approximation q1\*q2\*… to the posterior distribution, approximately minimizing the KL divergence from the factored approximation to the actual posterior. The KL divergence, or ELBO function has the form E\* log p(y, fe, vcp, vc) - E\* log q where E\* is expectation with respect to the product of qj. #### References Blei, Kucukelbir, McAuliffe (2017). Variational Inference: A review for Statisticians <https://arxiv.org/pdf/1601.00670.pdf> statsmodels statsmodels.regression.linear_model.RegressionResults.bse statsmodels.regression.linear\_model.RegressionResults.bse ========================================================== `RegressionResults.bse()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#RegressionResults.bse) statsmodels statsmodels.discrete.discrete_model.BinaryResults.set_null_options statsmodels.discrete.discrete\_model.BinaryResults.set\_null\_options ===================================================================== `BinaryResults.set_null_options(llnull=None, attach_results=True, **kwds)` set fit options for Null (constant-only) model This resets the cache for related attributes which is potentially fragile. This only sets the option, the null model is estimated when llnull is accessed, if llnull is not yet in cache. | Parameters: | * **llnull** (*None* *or* *float*) – If llnull is not None, then the value will be directly assigned to the cached attribute “llnull”. * **attach\_results** (*bool*) – Sets an internal flag whether the results instance of the null model should be attached. By default without calling this method, thenull model results are not attached and only the loglikelihood value llnull is stored. * **kwds** (*keyword arguments*) – `kwds` are directly used as fit keyword arguments for the null model, overriding any provided defaults. | | Returns: | | | Return type: | no returns, modifies attributes of this instance | statsmodels statsmodels.sandbox.distributions.transformed.TransfTwo_gen.expect statsmodels.sandbox.distributions.transformed.TransfTwo\_gen.expect =================================================================== `TransfTwo_gen.expect(func=None, args=(), loc=0, scale=1, lb=None, ub=None, conditional=False, **kwds)` Calculate expected value of a function with respect to the distribution. The expected value of a function `f(x)` with respect to a distribution `dist` is defined as: ``` ubound E[x] = Integral(f(x) * dist.pdf(x)) lbound ``` | Parameters: | * **func** (*callable**,* *optional*) – Function for which integral is calculated. Takes only one argument. The default is the identity mapping f(x) = x. * **args** (*tuple**,* *optional*) – Shape parameters of the distribution. * **loc** (*float**,* *optional*) – Location parameter (default=0). * **scale** (*float**,* *optional*) – Scale parameter (default=1). * **ub** (*lb**,*) – Lower and upper bound for integration. Default is set to the support of the distribution. * **conditional** (*bool**,* *optional*) – If True, the integral is corrected by the conditional probability of the integration interval. The return value is the expectation of the function, conditional on being in the given interval. Default is False. * **keyword arguments are passed to the integration routine.** (*Additional*) – | | Returns: | **expect** – The calculated expected value. | | Return type: | float | #### Notes The integration behavior of this function is inherited from `integrate.quad`. statsmodels statsmodels.regression.quantile_regression.QuantRegResults.ess statsmodels.regression.quantile\_regression.QuantRegResults.ess =============================================================== `QuantRegResults.ess()` statsmodels statsmodels.regression.quantile_regression.QuantRegResults.predict statsmodels.regression.quantile\_regression.QuantRegResults.predict =================================================================== `QuantRegResults.predict(exog=None, transform=True, *args, **kwargs)` Call self.model.predict with self.params as the first argument. | Parameters: | * **exog** (*array-like**,* *optional*) – The values for which you want to predict. see Notes below. * **transform** (*bool**,* *optional*) – If the model was fit via a formula, do you want to pass exog through the formula. Default is True. E.g., if you fit a model y ~ log(x1) + log(x2), and transform is True, then you can pass a data structure that contains x1 and x2 in their original form. Otherwise, you’d need to log the data first. * **kwargs** (*args**,*) – Some models can take additional arguments or keywords, see the predict method of the model for the details. | | Returns: | **prediction** – See self.model.predict | | Return type: | ndarray, [pandas.Series](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html#pandas.Series "(in pandas v0.22.0)") or [pandas.DataFrame](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html#pandas.DataFrame "(in pandas v0.22.0)") | #### Notes The types of exog that are supported depends on whether a formula was used in the specification of the model. If a formula was used, then exog is processed in the same way as the original data. This transformation needs to have key access to the same variable names, and can be a pandas DataFrame or a dict like object. If no formula was used, then the provided exog needs to have the same number of columns as the original exog in the model. No transformation of the data is performed except converting it to a numpy array. Row indices as in pandas data frames are supported, and added to the returned prediction. statsmodels statsmodels.regression.linear_model.WLS statsmodels.regression.linear\_model.WLS ======================================== `class statsmodels.regression.linear_model.WLS(endog, exog, weights=1.0, missing='none', hasconst=None, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#WLS) A regression model with diagonal but non-identity covariance structure. The weights are presumed to be (proportional to) the inverse of the variance of the observations. That is, if the variables are to be transformed by 1/sqrt(W) you must supply weights = 1/W. | Parameters: | * **endog** (*array-like*) – 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 `statsmodels.tools.add_constant`. * **weights** (*array-like**,* *optional*) – 1d array of weights. If you supply 1/W then the variables are pre- multiplied by 1/sqrt(W). If no weights are supplied the default value is 1 and WLS results are the same as OLS. * **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. | `weights` *array* – The stored weights supplied as an argument. `See regression.GLS` #### Examples ``` >>> import numpy as np >>> import statsmodels.api as sm >>> Y = [1,3,4,5,2,3,4] >>> X = range(1,8) >>> X = sm.add_constant(X) >>> wls_model = sm.WLS(Y,X, weights=list(range(1,8))) >>> results = wls_model.fit() >>> results.params array([ 2.91666667, 0.0952381 ]) >>> results.tvalues array([ 2.0652652 , 0.35684428]) >>> print(results.t_test([1, 0])) <T test: effect=array([ 2.91666667]), sd=array([[ 1.41224801]]), t=array([[ 2.0652652]]), p=array([[ 0.04690139]]), df_denom=5> >>> print(results.f_test([0, 1])) <F test: F=array([[ 0.12733784]]), p=[[ 0.73577409]], df_denom=5, df_num=1> ``` #### Notes If the weights are a function of the data, then the post estimation statistics such as fvalue and mse\_model might not be correct, as the package does not yet support no-constant regression. #### Methods | | | | --- | --- | | [`fit`](statsmodels.regression.linear_model.wls.fit#statsmodels.regression.linear_model.WLS.fit "statsmodels.regression.linear_model.WLS.fit")([method, cov\_type, cov\_kwds, use\_t]) | Full fit of the model. | | [`fit_regularized`](statsmodels.regression.linear_model.wls.fit_regularized#statsmodels.regression.linear_model.WLS.fit_regularized "statsmodels.regression.linear_model.WLS.fit_regularized")([method, alpha, L1\_wt, …]) | Return a regularized fit to a linear regression model. | | [`from_formula`](statsmodels.regression.linear_model.wls.from_formula#statsmodels.regression.linear_model.WLS.from_formula "statsmodels.regression.linear_model.WLS.from_formula")(formula, data[, subset, drop\_cols]) | Create a Model from a formula and dataframe. | | [`get_distribution`](statsmodels.regression.linear_model.wls.get_distribution#statsmodels.regression.linear_model.WLS.get_distribution "statsmodels.regression.linear_model.WLS.get_distribution")(params, scale[, exog, …]) | Returns a random number generator for the predictive distribution. | | [`hessian`](statsmodels.regression.linear_model.wls.hessian#statsmodels.regression.linear_model.WLS.hessian "statsmodels.regression.linear_model.WLS.hessian")(params) | The Hessian matrix of the model | | [`hessian_factor`](statsmodels.regression.linear_model.wls.hessian_factor#statsmodels.regression.linear_model.WLS.hessian_factor "statsmodels.regression.linear_model.WLS.hessian_factor")(params[, scale, observed]) | Weights for calculating Hessian | | [`information`](statsmodels.regression.linear_model.wls.information#statsmodels.regression.linear_model.WLS.information "statsmodels.regression.linear_model.WLS.information")(params) | Fisher information matrix of model | | [`initialize`](statsmodels.regression.linear_model.wls.initialize#statsmodels.regression.linear_model.WLS.initialize "statsmodels.regression.linear_model.WLS.initialize")() | Initialize (possibly re-initialize) a Model instance. | | [`loglike`](statsmodels.regression.linear_model.wls.loglike#statsmodels.regression.linear_model.WLS.loglike "statsmodels.regression.linear_model.WLS.loglike")(params) | Returns the value of the gaussian log-likelihood function at params. | | [`predict`](statsmodels.regression.linear_model.wls.predict#statsmodels.regression.linear_model.WLS.predict "statsmodels.regression.linear_model.WLS.predict")(params[, exog]) | Return linear predicted values from a design matrix. | | [`score`](statsmodels.regression.linear_model.wls.score#statsmodels.regression.linear_model.WLS.score "statsmodels.regression.linear_model.WLS.score")(params) | Score vector of model. | | [`whiten`](statsmodels.regression.linear_model.wls.whiten#statsmodels.regression.linear_model.WLS.whiten "statsmodels.regression.linear_model.WLS.whiten")(X) | Whitener for WLS model, multiplies each column by sqrt(self.weights) | #### Attributes | | | | --- | --- | | `df_model` | The model degree of freedom, defined as the rank of the regressor matrix minus 1 if a constant is included. | | `df_resid` | The residual degree of freedom, defined as the number of observations minus the rank of the regressor matrix. | | `endog_names` | Names of endogenous variables | | `exog_names` | Names of exogenous variables | statsmodels statsmodels.genmod.generalized_estimating_equations.GEEResults.llf statsmodels.genmod.generalized\_estimating\_equations.GEEResults.llf ==================================================================== `GEEResults.llf()` statsmodels statsmodels.regression.mixed_linear_model.MixedLMResults.resid statsmodels.regression.mixed\_linear\_model.MixedLMResults.resid ================================================================ `MixedLMResults.resid()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/mixed_linear_model.html#MixedLMResults.resid) Returns the residuals for the model. The residuals reflect the mean structure specified by the fixed effects and the predicted random effects. statsmodels statsmodels.regression.linear_model.PredictionResults.summary_frame statsmodels.regression.linear\_model.PredictionResults.summary\_frame ===================================================================== `PredictionResults.summary_frame(what='all', alpha=0.05)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/_prediction.html#PredictionResults.summary_frame) statsmodels statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialResults.bse statsmodels.discrete.count\_model.ZeroInflatedNegativeBinomialResults.bse ========================================================================= `ZeroInflatedNegativeBinomialResults.bse()`
programming_docs
statsmodels statsmodels.tsa.vector_ar.var_model.VARResults.sample_acov statsmodels.tsa.vector\_ar.var\_model.VARResults.sample\_acov ============================================================= `VARResults.sample_acov(nlags=1)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/var_model.html#VARResults.sample_acov) statsmodels statsmodels.sandbox.sysreg.Sem2SLS.whiten statsmodels.sandbox.sysreg.Sem2SLS.whiten ========================================= `Sem2SLS.whiten(Y)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/sysreg.html#Sem2SLS.whiten) Runs the first stage of the 2SLS. Returns the RHS variables that include the instruments. statsmodels statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.score_obs statsmodels.tsa.regime\_switching.markov\_regression.MarkovRegression.score\_obs ================================================================================ `MarkovRegression.score_obs(params, transformed=True)` Compute the score per observation, evaluated at params | Parameters: | * **params** (*array\_like*) – Array of parameters at which to evaluate the score function. * **transformed** (*boolean**,* *optional*) – Whether or not `params` is already transformed. Default is True. | statsmodels statsmodels.sandbox.distributions.extras.SkewNorm_gen.var statsmodels.sandbox.distributions.extras.SkewNorm\_gen.var ========================================================== `SkewNorm_gen.var(*args, **kwds)` Variance of the distribution. | Parameters: | * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **var** – the variance of the distribution | | Return type: | float | statsmodels statsmodels.iolib.foreign.StataReader statsmodels.iolib.foreign.StataReader ===================================== `class statsmodels.iolib.foreign.StataReader(fname, missing_values=False, encoding=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/iolib/foreign.html#StataReader) Stata .dta file reader. Provides methods to return the metadata of a Stata .dta file and a generator for the data itself. | Parameters: | * **file** (*file-like*) – A file-like object representing a Stata .dta file. * **missing\_values** (*bool*) – If missing\_values is True, parse missing\_values and return a Missing Values object instead of None. * **encoding** (*string**,* *optional*) – Used for Python 3 only. Encoding to use when reading the .dta file. Defaults to `locale.getpreferredencoding` | See also [`statsmodels.iolib.foreign.genfromdta`](statsmodels.iolib.foreign.genfromdta#statsmodels.iolib.foreign.genfromdta "statsmodels.iolib.foreign.genfromdta"), `pandas.read_stata`, `pandas.io.stata.StataReader` #### Notes This is known only to work on file formats 113 (Stata 8/9), 114 (Stata 10/11), and 115 (Stata 12). Needs to be tested on older versions. Known not to work on format 104, 108. If you have the documentation for older formats, please contact the developers. For more information about the .dta format see <http://www.stata.com/help.cgi?dta> <http://www.stata.com/help.cgi?dta_113> #### Methods | | | | --- | --- | | [`dataset`](statsmodels.iolib.foreign.statareader.dataset#statsmodels.iolib.foreign.StataReader.dataset "statsmodels.iolib.foreign.StataReader.dataset")([as\_dict]) | Returns a Python generator object for iterating over the dataset. | | [`file_format`](statsmodels.iolib.foreign.statareader.file_format#statsmodels.iolib.foreign.StataReader.file_format "statsmodels.iolib.foreign.StataReader.file_format")() | Returns the file format. | | [`file_headers`](statsmodels.iolib.foreign.statareader.file_headers#statsmodels.iolib.foreign.StataReader.file_headers "statsmodels.iolib.foreign.StataReader.file_headers")() | Returns all .dta file headers. | | [`file_label`](statsmodels.iolib.foreign.statareader.file_label#statsmodels.iolib.foreign.StataReader.file_label "statsmodels.iolib.foreign.StataReader.file_label")() | Returns the dataset’s label. | | [`file_timestamp`](statsmodels.iolib.foreign.statareader.file_timestamp#statsmodels.iolib.foreign.StataReader.file_timestamp "statsmodels.iolib.foreign.StataReader.file_timestamp")() | Returns the date and time Stata recorded on last file save. | | [`variables`](statsmodels.iolib.foreign.statareader.variables#statsmodels.iolib.foreign.StataReader.variables "statsmodels.iolib.foreign.StataReader.variables")() | Returns a list of the dataset’s StataVariables objects. | #### Attributes | | | | --- | --- | | `DTYPE_MAP` | | | `MISSING_VALUES` | | | `TYPE_MAP` | | statsmodels statsmodels.discrete.discrete_model.BinaryResults.fittedvalues statsmodels.discrete.discrete\_model.BinaryResults.fittedvalues =============================================================== `BinaryResults.fittedvalues()` statsmodels statsmodels.tools.tools.isestimable statsmodels.tools.tools.isestimable =================================== `statsmodels.tools.tools.isestimable(C, D)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tools/tools.html#isestimable) True if (Q, P) contrast `C` is estimable for (N, P) design `D` From an Q x P contrast matrix `C` and an N x P design matrix `D`, checks if the contrast `C` is estimable by looking at the rank of `vstack([C,D])` and verifying it is the same as the rank of `D`. | Parameters: | * **C** (*(**Q**,* *P**)* *array-like*) – contrast matrix. If `C` has is 1 dimensional assume shape (1, P) * **D** (*(**N**,* *P**)* *array-like*) – design matrix | | Returns: | **tf** – True if the contrast `C` is estimable on design `D` | | Return type: | bool | #### Examples ``` >>> D = np.array([[1, 1, 1, 0, 0, 0], ... [0, 0, 0, 1, 1, 1], ... [1, 1, 1, 1, 1, 1]]).T >>> isestimable([1, 0, 0], D) False >>> isestimable([1, -1, 0], D) True ``` statsmodels statsmodels.discrete.discrete_model.DiscreteResults.aic statsmodels.discrete.discrete\_model.DiscreteResults.aic ======================================================== `DiscreteResults.aic()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#DiscreteResults.aic) statsmodels statsmodels.genmod.families.links.CDFLink statsmodels.genmod.families.links.CDFLink ========================================= `class statsmodels.genmod.families.links.CDFLink(dbn=<scipy.stats._continuous_distns.norm_gen object>)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/links.html#CDFLink) The use the CDF of a scipy.stats distribution CDFLink is a subclass of logit in order to use its \_clean method for the link and its derivative. | Parameters: | **dbn** (*scipy.stats distribution*) – Default is dbn=scipy.stats.norm | #### Notes The CDF link is untested. #### Methods | | | | --- | --- | | [`deriv`](statsmodels.genmod.families.links.cdflink.deriv#statsmodels.genmod.families.links.CDFLink.deriv "statsmodels.genmod.families.links.CDFLink.deriv")(p) | Derivative of CDF link | | [`deriv2`](statsmodels.genmod.families.links.cdflink.deriv2#statsmodels.genmod.families.links.CDFLink.deriv2 "statsmodels.genmod.families.links.CDFLink.deriv2")(p) | Second derivative of the link function g’‘(p) | | [`inverse`](statsmodels.genmod.families.links.cdflink.inverse#statsmodels.genmod.families.links.CDFLink.inverse "statsmodels.genmod.families.links.CDFLink.inverse")(z) | The inverse of the CDF link | | [`inverse_deriv`](statsmodels.genmod.families.links.cdflink.inverse_deriv#statsmodels.genmod.families.links.CDFLink.inverse_deriv "statsmodels.genmod.families.links.CDFLink.inverse_deriv")(z) | Derivative of the inverse of the CDF transformation link function | statsmodels statsmodels.sandbox.stats.multicomp.StepDown.get_crit statsmodels.sandbox.stats.multicomp.StepDown.get\_crit ====================================================== `StepDown.get_crit(alpha)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/multicomp.html#StepDown.get_crit) statsmodels statsmodels.sandbox.regression.gmm.GMM statsmodels.sandbox.regression.gmm.GMM ====================================== `class statsmodels.sandbox.regression.gmm.GMM(endog, exog, instrument, k_moms=None, k_params=None, missing='none', **kwds)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#GMM) Class for estimation by Generalized Method of Moments needs to be subclassed, where the subclass defined the moment conditions `momcond` | Parameters: | * **endog** (*array*) – endogenous variable, see notes * **exog** (*array*) – array of exogenous variables, see notes * **instrument** (*array*) – array of instruments, see notes * **nmoms** (*None* *or* *int*) – number of moment conditions, if None then it is set equal to the number of columns of instruments. Mainly needed to determin the shape or size of start parameters and starting weighting matrix. * **kwds** (*anything*) – this is mainly if additional variables need to be stored for the calculations of the moment conditions | | Returns: | * *\*Attributes\** * **results** (*instance of GMMResults*) – currently just a storage class for params and cov\_params without it’s own methods * **bse** (*property*) – return bse | #### Notes The GMM class only uses the moment conditions and does not use any data directly. endog, exog, instrument and kwds in the creation of the class instance are only used to store them for access in the moment conditions. Which of this are required and how they are used depends on the moment conditions of the subclass. Warning: Options for various methods have not been fully implemented and are still missing in several methods. TODO: currently onestep (maxiter=0) still produces an updated estimate of bse and cov\_params. #### Methods | | | | --- | --- | | [`calc_weightmatrix`](statsmodels.sandbox.regression.gmm.gmm.calc_weightmatrix#statsmodels.sandbox.regression.gmm.GMM.calc_weightmatrix "statsmodels.sandbox.regression.gmm.GMM.calc_weightmatrix")(moms[, weights\_method, …]) | calculate omega or the weighting matrix | | [`fit`](statsmodels.sandbox.regression.gmm.gmm.fit#statsmodels.sandbox.regression.gmm.GMM.fit "statsmodels.sandbox.regression.gmm.GMM.fit")([start\_params, maxiter, inv\_weights, …]) | Estimate parameters using GMM and return GMMResults | | [`fitgmm`](statsmodels.sandbox.regression.gmm.gmm.fitgmm#statsmodels.sandbox.regression.gmm.GMM.fitgmm "statsmodels.sandbox.regression.gmm.GMM.fitgmm")(start[, weights, optim\_method, …]) | estimate parameters using GMM | | [`fitgmm_cu`](statsmodels.sandbox.regression.gmm.gmm.fitgmm_cu#statsmodels.sandbox.regression.gmm.GMM.fitgmm_cu "statsmodels.sandbox.regression.gmm.GMM.fitgmm_cu")(start[, optim\_method, optim\_args]) | estimate parameters using continuously updating GMM | | [`fititer`](statsmodels.sandbox.regression.gmm.gmm.fititer#statsmodels.sandbox.regression.gmm.GMM.fititer "statsmodels.sandbox.regression.gmm.GMM.fititer")(start[, maxiter, start\_invweights, …]) | iterative estimation with updating of optimal weighting matrix | | [`from_formula`](statsmodels.sandbox.regression.gmm.gmm.from_formula#statsmodels.sandbox.regression.gmm.GMM.from_formula "statsmodels.sandbox.regression.gmm.GMM.from_formula")(formula, data[, subset, drop\_cols]) | Create a Model from a formula and dataframe. | | [`gmmobjective`](statsmodels.sandbox.regression.gmm.gmm.gmmobjective#statsmodels.sandbox.regression.gmm.GMM.gmmobjective "statsmodels.sandbox.regression.gmm.GMM.gmmobjective")(params, weights) | objective function for GMM minimization | | [`gmmobjective_cu`](statsmodels.sandbox.regression.gmm.gmm.gmmobjective_cu#statsmodels.sandbox.regression.gmm.GMM.gmmobjective_cu "statsmodels.sandbox.regression.gmm.GMM.gmmobjective_cu")(params[, weights\_method, wargs]) | objective function for continuously updating GMM minimization | | [`gradient_momcond`](statsmodels.sandbox.regression.gmm.gmm.gradient_momcond#statsmodels.sandbox.regression.gmm.GMM.gradient_momcond "statsmodels.sandbox.regression.gmm.GMM.gradient_momcond")(params[, epsilon, centered]) | gradient of moment conditions | | [`momcond_mean`](statsmodels.sandbox.regression.gmm.gmm.momcond_mean#statsmodels.sandbox.regression.gmm.GMM.momcond_mean "statsmodels.sandbox.regression.gmm.GMM.momcond_mean")(params) | mean of moment conditions, | | [`predict`](statsmodels.sandbox.regression.gmm.gmm.predict#statsmodels.sandbox.regression.gmm.GMM.predict "statsmodels.sandbox.regression.gmm.GMM.predict")(params[, exog]) | After a model has been fit predict returns the fitted values. | | [`score`](statsmodels.sandbox.regression.gmm.gmm.score#statsmodels.sandbox.regression.gmm.GMM.score "statsmodels.sandbox.regression.gmm.GMM.score")(params, weights[, epsilon, centered]) | | | [`score_cu`](statsmodels.sandbox.regression.gmm.gmm.score_cu#statsmodels.sandbox.regression.gmm.GMM.score_cu "statsmodels.sandbox.regression.gmm.GMM.score_cu")(params[, epsilon, centered]) | | | [`set_param_names`](statsmodels.sandbox.regression.gmm.gmm.set_param_names#statsmodels.sandbox.regression.gmm.GMM.set_param_names "statsmodels.sandbox.regression.gmm.GMM.set_param_names")(param\_names[, k\_params]) | set the parameter names in the model | | [`start_weights`](statsmodels.sandbox.regression.gmm.gmm.start_weights#statsmodels.sandbox.regression.gmm.GMM.start_weights "statsmodels.sandbox.regression.gmm.GMM.start_weights")([inv]) | | #### Attributes | | | | --- | --- | | `endog_names` | Names of endogenous variables | | `exog_names` | Names of exogenous variables | | `results_class` | | statsmodels statsmodels.regression.linear_model.RegressionResults.load statsmodels.regression.linear\_model.RegressionResults.load =========================================================== `classmethod RegressionResults.load(fname)` load a pickle, (class method) | Parameters: | **fname** (*string* *or* *filehandle*) – fname can be a string to a file path or filename, or a filehandle. | | Returns: | | | Return type: | unpickled instance | statsmodels statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.initial_probabilities statsmodels.tsa.regime\_switching.markov\_regression.MarkovRegression.initial\_probabilities ============================================================================================ `MarkovRegression.initial_probabilities(params, regime_transition=None)` Retrieve initial probabilities statsmodels statsmodels.discrete.discrete_model.BinaryModel.loglike statsmodels.discrete.discrete\_model.BinaryModel.loglike ======================================================== `BinaryModel.loglike(params)` Log-likelihood of model. statsmodels statsmodels.discrete.discrete_model.LogitResults.bic statsmodels.discrete.discrete\_model.LogitResults.bic ===================================================== `LogitResults.bic()` statsmodels statsmodels.multivariate.multivariate_ols._MultivariateOLSResults.mv_test statsmodels.multivariate.multivariate\_ols.\_MultivariateOLSResults.mv\_test ============================================================================ `_MultivariateOLSResults.mv_test(hypotheses=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/multivariate/multivariate_ols.html#_MultivariateOLSResults.mv_test) Linear hypotheses testing | Parameters: | **hypotheses** (*A list of tuples*) – Hypothesis `L*B*M = C` to be tested where B is the parameters in regression Y = X\*B. Each element is a tuple of length 2, 3, or 4:* (name, contrast\_L) * (name, contrast\_L, transform\_M) * (name, contrast\_L, transform\_M, constant\_C) containing a string `name`, the contrast matrix L, the transform matrix M (for transforming dependent variables), and right-hand side constant matrix constant\_C, respectively. `contrast_L : 2D array or an array of strings` Left-hand side contrast matrix for hypotheses testing. If 2D array, each row is an hypotheses and each column is an independent variable. At least 1 row (1 by k\_exog, the number of independent variables) is required. If an array of strings, it will be passed to patsy.DesignInfo().linear\_constraint. `transform_M : 2D array or an array of strings or None, optional` Left hand side transform matrix. If `None` or left out, it is set to a k\_endog by k\_endog identity matrix (i.e. do not transform y matrix). If an array of strings, it will be passed to patsy.DesignInfo().linear\_constraint. `constant_C : 2D array or None, optional` Right-hand side constant matrix. if `None` or left out it is set to a matrix of zeros Must has the same number of rows as contrast\_L and the same number of columns as transform\_M If `hypotheses` is None: 1) the effect of each independent variable on the dependent variables will be tested. Or 2) if model is created using a formula, `hypotheses` will be created according to `design_info`. 1) and 2) is equivalent if no additional variables are created by the formula (e.g. dummy variables for categorical variables and interaction terms) | | Returns: | **results** | | Return type: | [\_MultivariateOLSResults](statsmodels.multivariate.multivariate_ols._multivariateolsresults#statsmodels.multivariate.multivariate_ols._MultivariateOLSResults "statsmodels.multivariate.multivariate_ols._MultivariateOLSResults") | #### Notes Tests hypotheses of the form L \* params \* M = C where `params` is the regression coefficient matrix for the linear model y = x \* params, `L` is the contrast matrix, `M` is the dependent variable transform matrix and C is the constant matrix. statsmodels statsmodels.sandbox.distributions.extras.SkewNorm_gen.entropy statsmodels.sandbox.distributions.extras.SkewNorm\_gen.entropy ============================================================== `SkewNorm_gen.entropy(*args, **kwds)` Differential entropy of the RV. | Parameters: | * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information). * **loc** (*array\_like**,* *optional*) – Location parameter (default=0). * **scale** (*array\_like**,* *optional* *(**continuous distributions only**)*) – Scale parameter (default=1). | #### Notes Entropy is defined base `e`: ``` >>> drv = rv_discrete(values=((0, 1), (0.5, 0.5))) >>> np.allclose(drv.entropy(), np.log(2.0)) True ``` statsmodels statsmodels.discrete.discrete_model.Probit.pdf statsmodels.discrete.discrete\_model.Probit.pdf =============================================== `Probit.pdf(X)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#Probit.pdf) Probit (Normal) probability density function | Parameters: | **X** (*array-like*) – The linear predictor of the model (XB). | | Returns: | **pdf** – The value of the normal density function for each point of X. | | Return type: | ndarray | #### Notes This function is just an alias for scipy.stats.norm.pdf statsmodels statsmodels.sandbox.regression.gmm.GMMResults.jval statsmodels.sandbox.regression.gmm.GMMResults.jval ================================================== `GMMResults.jval()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#GMMResults.jval) statsmodels statsmodels.stats.inter_rater.aggregate_raters statsmodels.stats.inter\_rater.aggregate\_raters ================================================ `statsmodels.stats.inter_rater.aggregate_raters(data, n_cat=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/inter_rater.html#aggregate_raters) convert raw data with shape (subject, rater) to (subject, cat\_counts) brings data into correct format for fleiss\_kappa bincount will raise exception if data cannot be converted to integer. | Parameters: | * **data** (*array\_like**,* *2-Dim*) – data containing category assignment with subjects in rows and raters in columns. * **n\_cat** (*None* *or* *int*) – If None, then the data is converted to integer categories, 0,1,2,…,n\_cat-1. Because of the relabeling only category levels with non-zero counts are included. If this is an integer, then the category levels in the data are already assumed to be in integers, 0,1,2,…,n\_cat-1. In this case, the returned array may contain columns with zero count, if no subject has been categorized with this level. | | Returns: | **arr** – Contains counts of raters that assigned a category level to individuals. Subjects are in rows, category levels in columns. | | Return type: | nd\_array, (n\_rows, n\_cat) |
programming_docs
statsmodels statsmodels.tsa.statespace.mlemodel.MLEResults.cov_params_oim statsmodels.tsa.statespace.mlemodel.MLEResults.cov\_params\_oim =============================================================== `MLEResults.cov_params_oim()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEResults.cov_params_oim) (array) The variance / covariance matrix. Computed using the method from Harvey (1989). statsmodels statsmodels.sandbox.regression.gmm.IVGMMResults.wald_test_terms statsmodels.sandbox.regression.gmm.IVGMMResults.wald\_test\_terms ================================================================= `IVGMMResults.wald_test_terms(skip_single=False, extra_constraints=None, combine_terms=None)` Compute a sequence of Wald tests for terms over multiple columns This computes joined Wald tests for the hypothesis that all coefficients corresponding to a `term` are zero. `Terms` are defined by the underlying formula or by string matching. | Parameters: | * **skip\_single** (*boolean*) – If true, then terms that consist only of a single column and, therefore, refers only to a single parameter is skipped. If false, then all terms are included. * **extra\_constraints** (*ndarray*) – not tested yet * **combine\_terms** (*None* *or* *list of strings*) – Each string in this list is matched to the name of the terms or the name of the exogenous variables. All columns whose name includes that string are combined in one joint test. | | Returns: | **test\_result** – The result instance contains `table` which is a pandas DataFrame with the test results: test statistic, degrees of freedom and pvalues. | | Return type: | result instance | #### Examples ``` >>> res_ols = ols("np.log(Days+1) ~ C(Duration, Sum)*C(Weight, Sum)", data).fit() >>> res_ols.wald_test_terms() <class 'statsmodels.stats.contrast.WaldTestResults'> F P>F df constraint df denom Intercept 279.754525 2.37985521351e-22 1 51 C(Duration, Sum) 5.367071 0.0245738436636 1 51 C(Weight, Sum) 12.432445 3.99943118767e-05 2 51 C(Duration, Sum):C(Weight, Sum) 0.176002 0.83912310946 2 51 ``` ``` >>> res_poi = Poisson.from_formula("Days ~ C(Weight) * C(Duration)", data).fit(cov_type='HC0') >>> wt = res_poi.wald_test_terms(skip_single=False, combine_terms=['Duration', 'Weight']) >>> print(wt) chi2 P>chi2 df constraint Intercept 15.695625 7.43960374424e-05 1 C(Weight) 16.132616 0.000313940174705 2 C(Duration) 1.009147 0.315107378931 1 C(Weight):C(Duration) 0.216694 0.897315972824 2 Duration 11.187849 0.010752286833 3 Weight 30.263368 4.32586407145e-06 4 ``` statsmodels statsmodels.regression.quantile_regression.QuantRegResults.ssr statsmodels.regression.quantile\_regression.QuantRegResults.ssr =============================================================== `QuantRegResults.ssr()` statsmodels statsmodels.sandbox.regression.gmm.GMMResults.save statsmodels.sandbox.regression.gmm.GMMResults.save ================================================== `GMMResults.save(fname, remove_data=False)` save a pickle of this instance | Parameters: | * **fname** (*string* *or* *filehandle*) – fname can be a string to a file path or filename, or a filehandle. * **remove\_data** (*bool*) – If False (default), then the instance is pickled without changes. If True, then all arrays with length nobs are set to None before pickling. See the remove\_data method. In some cases not all arrays will be set to None. | #### Notes If remove\_data is true and the model result does not implement a remove\_data method then this will raise an exception. statsmodels statsmodels.regression.quantile_regression.QuantRegResults.load statsmodels.regression.quantile\_regression.QuantRegResults.load ================================================================ `classmethod QuantRegResults.load(fname)` load a pickle, (class method) | Parameters: | **fname** (*string* *or* *filehandle*) – fname can be a string to a file path or filename, or a filehandle. | | Returns: | | | Return type: | unpickled instance | statsmodels statsmodels.discrete.discrete_model.ProbitResults.llr statsmodels.discrete.discrete\_model.ProbitResults.llr ====================================================== `ProbitResults.llr()` statsmodels statsmodels.sandbox.distributions.extras.NormExpan_gen.mean statsmodels.sandbox.distributions.extras.NormExpan\_gen.mean ============================================================ `NormExpan_gen.mean(*args, **kwds)` Mean of the distribution. | Parameters: | * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **mean** – the mean of the distribution | | Return type: | float | statsmodels statsmodels.tsa.statespace.kalman_filter.PredictionResults.update_representation statsmodels.tsa.statespace.kalman\_filter.PredictionResults.update\_representation ================================================================================== `PredictionResults.update_representation(model, only_options=False)` Update the results to match a given model | Parameters: | * **model** ([Representation](statsmodels.tsa.statespace.representation.representation#statsmodels.tsa.statespace.representation.Representation "statsmodels.tsa.statespace.representation.Representation")) – The model object from which to take the updated values. * **only\_options** (*boolean**,* *optional*) – If set to true, only the filter options are updated, and the state space representation is not updated. Default is False. | #### Notes This method is rarely required except for internal usage. statsmodels statsmodels.tsa.vector_ar.vecm.VECMResults.pvalues_det_coef_coint statsmodels.tsa.vector\_ar.vecm.VECMResults.pvalues\_det\_coef\_coint ===================================================================== `VECMResults.pvalues_det_coef_coint()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/vecm.html#VECMResults.pvalues_det_coef_coint) statsmodels statsmodels.tsa.vector_ar.irf.IRAnalysis.lr_effect_stderr statsmodels.tsa.vector\_ar.irf.IRAnalysis.lr\_effect\_stderr ============================================================ `IRAnalysis.lr_effect_stderr(orth=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/irf.html#IRAnalysis.lr_effect_stderr) statsmodels statsmodels.stats.contingency_tables.StratifiedTable.logodds_pooled statsmodels.stats.contingency\_tables.StratifiedTable.logodds\_pooled ===================================================================== `StratifiedTable.logodds_pooled()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#StratifiedTable.logodds_pooled) statsmodels statsmodels.miscmodels.tmodel.TLinearModel.information statsmodels.miscmodels.tmodel.TLinearModel.information ====================================================== `TLinearModel.information(params)` Fisher information matrix of model Returns -Hessian of loglike evaluated at params. statsmodels statsmodels.robust.robust_linear_model.RLM.deviance statsmodels.robust.robust\_linear\_model.RLM.deviance ===================================================== `RLM.deviance(tmp_results)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/robust_linear_model.html#RLM.deviance) Returns the (unnormalized) log-likelihood from the M estimator. statsmodels statsmodels.duration.hazard_regression.PHReg.breslow_loglike statsmodels.duration.hazard\_regression.PHReg.breslow\_loglike ============================================================== `PHReg.breslow_loglike(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/duration/hazard_regression.html#PHReg.breslow_loglike) Returns the value of the log partial likelihood function evaluated at `params`, using the Breslow method to handle tied times. statsmodels statsmodels.tsa.statespace.sarimax.SARIMAX.score statsmodels.tsa.statespace.sarimax.SARIMAX.score ================================================ `SARIMAX.score(params, *args, **kwargs)` Compute the score function at params. | Parameters: | * **params** (*array\_like*) – Array of parameters at which to evaluate the score. * **args** – Additional positional arguments to the `loglike` method. * **kwargs** – Additional keyword arguments to the `loglike` method. | | Returns: | **score** – Score, evaluated at `params`. | | Return type: | array | #### Notes This is a numerical approximation, calculated using first-order complex step differentiation on the `loglike` method. Both \*args and \*\*kwargs are necessary because the optimizer from `fit` must call this function and only supports passing arguments via \*args (for example `scipy.optimize.fmin_l_bfgs`). statsmodels statsmodels.genmod.cov_struct.Nested.initialize statsmodels.genmod.cov\_struct.Nested.initialize ================================================ `Nested.initialize(model)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/cov_struct.html#Nested.initialize) Called on the first call to update `ilabels` is a list of n\_i x n\_i matrices containing integer labels that correspond to specific correlation parameters. Two elements of ilabels[i] with the same label share identical variance components. `designx` is a matrix, with each row containing dummy variables indicating which variance components are associated with the corresponding element of QY. statsmodels statsmodels.tsa.statespace.varmax.VARMAXResults.plot_diagnostics statsmodels.tsa.statespace.varmax.VARMAXResults.plot\_diagnostics ================================================================= `VARMAXResults.plot_diagnostics(variable=0, lags=10, fig=None, figsize=None)` Diagnostic plots for standardized residuals of one endogenous variable | Parameters: | * **variable** (*integer**,* *optional*) – Index of the endogenous variable for which the diagnostic plots should be created. Default is 0. * **lags** (*integer**,* *optional*) – Number of lags to include in the correlogram. Default is 10. * **fig** (*Matplotlib Figure instance**,* *optional*) – If given, subplots are created in this figure instead of in a new figure. Note that the 2x2 grid will be created in the provided figure using `fig.add_subplot()`. * **figsize** (*tuple**,* *optional*) – If a figure is created, this argument allows specifying a size. The tuple is (width, height). | #### Notes Produces a 2x2 plot grid with the following plots (ordered clockwise from top left): 1. Standardized residuals over time 2. Histogram plus estimated density of standardized residulas, along with a Normal(0,1) density plotted for reference. 3. Normal Q-Q plot, with Normal reference line. 4. Correlogram See also [`statsmodels.graphics.gofplots.qqplot`](statsmodels.graphics.gofplots.qqplot#statsmodels.graphics.gofplots.qqplot "statsmodels.graphics.gofplots.qqplot"), [`statsmodels.graphics.tsaplots.plot_acf`](statsmodels.graphics.tsaplots.plot_acf#statsmodels.graphics.tsaplots.plot_acf "statsmodels.graphics.tsaplots.plot_acf") statsmodels statsmodels.tsa.arima_process.ArmaProcess.from_estimation statsmodels.tsa.arima\_process.ArmaProcess.from\_estimation =========================================================== `classmethod ArmaProcess.from_estimation(model_results, nobs=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_process.html#ArmaProcess.from_estimation) Convenience function to create an ArmaProcess from the results of an ARMA estimation | Parameters: | * **model\_results** (*ARMAResults instance*) – A fitted model * **nobs** (*int**,* *optional*) – If None, nobs is taken from the results | statsmodels statsmodels.discrete.discrete_model.LogitResults.summary2 statsmodels.discrete.discrete\_model.LogitResults.summary2 ========================================================== `LogitResults.summary2(yname=None, xname=None, title=None, alpha=0.05, float_format='%.4f')` Experimental function to summarize regression results | Parameters: | * **xname** (*List of strings of length equal to the number of parameters*) – Names of the independent variables (optional) * **yname** (*string*) – Name of the dependent variable (optional) * **title** (*string**,* *optional*) – Title for the top table. If not None, then this replaces the default title * **alpha** (*float*) – significance level for the confidence intervals * **float\_format** (*string*) – print format for floats in parameters summary | | Returns: | **smry** – this holds the summary tables and text, which can be printed or converted to various output formats. | | Return type: | Summary instance | See also [`statsmodels.iolib.summary.Summary`](statsmodels.iolib.summary.summary#statsmodels.iolib.summary.Summary "statsmodels.iolib.summary.Summary") class to hold summary results statsmodels statsmodels.stats.proportion.proportions_ztest statsmodels.stats.proportion.proportions\_ztest =============================================== `statsmodels.stats.proportion.proportions_ztest(count, nobs, value=None, alternative='two-sided', prop_var=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/proportion.html#proportions_ztest) Test for proportions based on normal (z) test | Parameters: | * **count** (*integer* *or* *array\_like*) – the number of successes in nobs trials. If this is array\_like, then the assumption is that this represents the number of successes for each independent sample * **nobs** (*integer* *or* *array-like*) – the number of trials or observations, with the same length as count. * **value** (*float**,* *array\_like* *or* *None**,* *optional*) – This is the value of the null hypothesis equal to the proportion in the case of a one sample test. In the case of a two-sample test, the null hypothesis is that prop[0] - prop[1] = value, where prop is the proportion in the two samples. If not provided value = 0 and the null is prop[0] = prop[1] * **alternative** (*string in* *[**'two-sided'**,* *'smaller'**,* *'larger'**]*) – The alternative hypothesis can be either two-sided or one of the one- sided tests, smaller means that the alternative hypothesis is `prop < value` and larger means `prop > value`. In the two sample test, smaller means that the alternative hypothesis is `p1 < p2` and larger means `p1 > p2` where `p1` is the proportion of the first sample and `p2` of the second one. * **prop\_var** (*False* *or* *float in* *(**0**,* *1**)*) – If prop\_var is false, then the variance of the proportion estimate is calculated based on the sample proportion. Alternatively, a proportion can be specified to calculate this variance. Common use case is to use the proportion under the Null hypothesis to specify the variance of the proportion estimate. | | Returns: | * **zstat** (*float*) – test statistic for the z-test * **p-value** (*float*) – p-value for the z-test | #### Examples ``` >>> count = 5 >>> nobs = 83 >>> value = .05 >>> stat, pval = proportions_ztest(count, nobs, value) >>> print('{0:0.3f}'.format(pval)) 0.695 ``` ``` >>> import numpy as np >>> from statsmodels.stats.proportion import proportions_ztest >>> count = np.array([5, 12]) >>> nobs = np.array([83, 99]) >>> stat, pval = proportions_ztest(counts, nobs) >>> print('{0:0.3f}'.format(pval)) 0.159 ``` #### Notes This uses a simple normal test for proportions. It should be the same as running the mean z-test on the data encoded 1 for event and 0 for no event so that the sum corresponds to the count. In the one and two sample cases with two-sided alternative, this test produces the same p-value as `proportions_chisquare`, since the chisquare is the distribution of the square of a standard normal distribution. statsmodels statsmodels.genmod.families.family.Poisson.loglike statsmodels.genmod.families.family.Poisson.loglike ================================================== `Poisson.loglike(endog, mu, var_weights=1.0, freq_weights=1.0, scale=1.0)` The log-likelihood function in terms of the fitted mean response. | Parameters: | * **endog** (*array*) – Usually the endogenous response variable. * **mu** (*array*) – Usually but not always the fitted mean response variable. * **var\_weights** (*array-like*) – 1d array of variance (analytic) weights. The default is 1. * **freq\_weights** (*array-like*) – 1d array of frequency weights. The default is 1. * **scale** (*float*) – The scale parameter. The default is 1. | | Returns: | **ll** – The value of the loglikelihood evaluated at (endog, mu, var\_weights, freq\_weights, scale) as defined below. | | Return type: | float | #### Notes Where \(ll\_i\) is the by-observation log-likelihood: \[ll = \sum(ll\_i \* freq\\_weights\_i)\] `ll_i` is defined for each family. endog and mu are not restricted to `endog` and `mu` respectively. For instance, you could call both `loglike(endog, endog)` and `loglike(endog, mu)` to get the log-likelihood ratio. statsmodels statsmodels.discrete.discrete_model.CountModel.information statsmodels.discrete.discrete\_model.CountModel.information =========================================================== `CountModel.information(params)` Fisher information matrix of model Returns -Hessian of loglike evaluated at params. statsmodels statsmodels.discrete.discrete_model.GeneralizedPoisson.cov_params_func_l1 statsmodels.discrete.discrete\_model.GeneralizedPoisson.cov\_params\_func\_l1 ============================================================================= `GeneralizedPoisson.cov_params_func_l1(likelihood_model, xopt, retvals)` Computes cov\_params on a reduced parameter space corresponding to the nonzero parameters resulting from the l1 regularized fit. Returns a full cov\_params matrix, with entries corresponding to zero’d values set to np.nan. statsmodels statsmodels.tsa.statespace.sarimax.SARIMAXResults.hqic statsmodels.tsa.statespace.sarimax.SARIMAXResults.hqic ====================================================== `SARIMAXResults.hqic()` (float) Hannan-Quinn Information Criterion statsmodels statsmodels.sandbox.distributions.extras.SkewNorm2_gen.std statsmodels.sandbox.distributions.extras.SkewNorm2\_gen.std =========================================================== `SkewNorm2_gen.std(*args, **kwds)` Standard deviation of the distribution. | Parameters: | * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **std** – standard deviation of the distribution | | Return type: | float | statsmodels statsmodels.sandbox.distributions.extras.SkewNorm_gen.pdf statsmodels.sandbox.distributions.extras.SkewNorm\_gen.pdf ========================================================== `SkewNorm_gen.pdf(x, *args, **kwds)` Probability density function at x of the given RV. | Parameters: | * **x** (*array\_like*) – quantiles * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **pdf** – Probability density function evaluated at x | | Return type: | ndarray |
programming_docs
statsmodels statsmodels.stats.contingency_tables.Table2x2.log_riskratio_pvalue statsmodels.stats.contingency\_tables.Table2x2.log\_riskratio\_pvalue ===================================================================== `Table2x2.log_riskratio_pvalue(null=0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table2x2.log_riskratio_pvalue) p-value for a hypothesis test about the log risk ratio. | Parameters: | **null** (*float*) – The null value of the log risk ratio. | statsmodels statsmodels.stats.contingency_tables.SquareTable.standardized_resids statsmodels.stats.contingency\_tables.SquareTable.standardized\_resids ====================================================================== `SquareTable.standardized_resids()` statsmodels statsmodels.discrete.discrete_model.LogitResults.bse statsmodels.discrete.discrete\_model.LogitResults.bse ===================================================== `LogitResults.bse()` statsmodels statsmodels.tsa.varma_process.VarmaPoly.vstack statsmodels.tsa.varma\_process.VarmaPoly.vstack =============================================== `VarmaPoly.vstack(a=None, name='ar')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/varma_process.html#VarmaPoly.vstack) stack lagpolynomial vertically in 2d array statsmodels statsmodels.genmod.cov_struct.Exchangeable.covariance_matrix_solve statsmodels.genmod.cov\_struct.Exchangeable.covariance\_matrix\_solve ===================================================================== `Exchangeable.covariance_matrix_solve(expval, index, stdev, rhs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/cov_struct.html#Exchangeable.covariance_matrix_solve) Solves matrix equations of the form `covmat * soln = rhs` and returns the values of `soln`, where `covmat` is the covariance matrix represented by this class. | Parameters: | * **expval** (*array-like*) – The expected value of endog for each observed value in the group. * **index** (*integer*) – The group index. * **stdev** (*array-like*) – The standard deviation of endog for each observation in the group. * **rhs** (*list/tuple of array-like*) – A set of right-hand sides; each defines a matrix equation to be solved. | | Returns: | **soln** – The solutions to the matrix equations. | | Return type: | list/tuple of array-like | #### Notes Returns None if the solver fails. Some dependence structures do not use `expval` and/or `index` to determine the correlation matrix. Some families (e.g. binomial) do not use the `stdev` parameter when forming the covariance matrix. If the covariance matrix is singular or not SPD, it is projected to the nearest such matrix. These projection events are recorded in the fit\_history member of the GEE model. Systems of linear equations with the covariance matrix as the left hand side (LHS) are solved for different right hand sides (RHS); the LHS is only factorized once to save time. This is a default implementation, it can be reimplemented in subclasses to optimize the linear algebra according to the struture of the covariance matrix. statsmodels statsmodels.genmod.generalized_linear_model.GLMResults.wald_test statsmodels.genmod.generalized\_linear\_model.GLMResults.wald\_test =================================================================== `GLMResults.wald_test(r_matrix, cov_p=None, scale=1.0, invcov=None, use_f=None)` Compute a Wald-test for a joint linear hypothesis. | Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) – + array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length p row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – Default is 1.0 for no scaling. * **invcov** (*array-like**,* *optional*) – A q x q array to specify an inverse covariance matrix based on a restrictions matrix. * **use\_f** (*bool*) – If True, then the F-distribution is used. If False, then the asymptotic distribution, chisquare is used. If use\_f is None, then the F distribution is used if the model specifies that use\_t is True. The test statistic is proportionally adjusted for the distribution by the number of constraints in the hypothesis. | | Returns: | **res** – The results for the test are attributes of this results instance. | | Return type: | ContrastResults instance | See also [`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`f_test`](statsmodels.genmod.generalized_linear_model.glmresults.f_test#statsmodels.genmod.generalized_linear_model.GLMResults.f_test "statsmodels.genmod.generalized_linear_model.GLMResults.f_test"), [`t_test`](statsmodels.genmod.generalized_linear_model.glmresults.t_test#statsmodels.genmod.generalized_linear_model.GLMResults.t_test "statsmodels.genmod.generalized_linear_model.GLMResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") #### Notes The matrix `r_matrix` is assumed to be non-singular. More precisely, r\_matrix (pX pX.T) r\_matrix.T is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full. statsmodels statsmodels.discrete.discrete_model.Poisson.loglikeobs statsmodels.discrete.discrete\_model.Poisson.loglikeobs ======================================================= `Poisson.loglikeobs(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#Poisson.loglikeobs) Loglikelihood for observations of Poisson model | Parameters: | **params** (*array-like*) – The parameters of the model. | | Returns: | **loglike** – The log likelihood for each observation of the model evaluated at `params`. See Notes | | Return type: | array-like | #### Notes \[\ln L\_{i}=\left[-\lambda\_{i}+y\_{i}x\_{i}^{\prime}\beta-\ln y\_{i}!\right]\] for observations \(i=1,...,n\) statsmodels statsmodels.robust.robust_linear_model.RLMResults.load statsmodels.robust.robust\_linear\_model.RLMResults.load ======================================================== `classmethod RLMResults.load(fname)` load a pickle, (class method) | Parameters: | **fname** (*string* *or* *filehandle*) – fname can be a string to a file path or filename, or a filehandle. | | Returns: | | | Return type: | unpickled instance | statsmodels statsmodels.robust.norms.RamsayE.psi_deriv statsmodels.robust.norms.RamsayE.psi\_deriv =========================================== `RamsayE.psi_deriv(z)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/norms.html#RamsayE.psi_deriv) The derivative of Ramsay’s Ea psi function. #### Notes Used to estimate the robust covariance matrix. statsmodels statsmodels.sandbox.descstats.sign_test statsmodels.sandbox.descstats.sign\_test ======================================== `statsmodels.sandbox.descstats.sign_test(samp, mu0=0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/descriptivestats.html#sign_test) Signs test. | Parameters: | * **samp** (*array-like*) – 1d array. The sample for which you want to perform the signs test. * **mu0** (*float*) – See Notes for the definition of the sign test. mu0 is 0 by default, but it is common to set it to the median. | | Returns: | | | Return type: | M, p-value | #### Notes The signs test returns M = (N(+) - N(-))/2 where N(+) is the number of values above `mu0`, N(-) is the number of values below. Values equal to `mu0` are discarded. The p-value for M is calculated using the binomial distrubution and can be intrepreted the same as for a t-test. The test-statistic is distributed Binom(min(N(+), N(-)), n\_trials, .5) where n\_trials equals N(+) + N(-). See also `scipy.stats.wilcoxon` statsmodels statsmodels.tsa.statespace.structural.UnobservedComponentsResults.cov_params_robust statsmodels.tsa.statespace.structural.UnobservedComponentsResults.cov\_params\_robust ===================================================================================== `UnobservedComponentsResults.cov_params_robust()` (array) The QMLE variance / covariance matrix. Alias for `cov_params_robust_oim` statsmodels statsmodels.miscmodels.count.PoissonOffsetGMLE.loglikeobs statsmodels.miscmodels.count.PoissonOffsetGMLE.loglikeobs ========================================================= `PoissonOffsetGMLE.loglikeobs(params)` statsmodels statsmodels.duration.survfunc.SurvfuncRight statsmodels.duration.survfunc.SurvfuncRight =========================================== `class statsmodels.duration.survfunc.SurvfuncRight(time, status, entry=None, title=None, freq_weights=None, exog=None, bw_factor=1.0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/duration/survfunc.html#SurvfuncRight) Estimation and inference for a survival function. The survival function S(t) = P(T > t) is the probability that an event time T is greater than t. This class currently only supports right censoring. | Parameters: | * **time** (*array-like*) – An array of times (censoring times or event times) * **status** (*array-like*) – Status at the event time, status==1 is the ‘event’ (e.g. death, failure), meaning that the event occurs at the given value in `time`; status==0 indicates that censoring has occured, meaning that the event occurs after the given value in `time`. * **entry** (*array-like**,* *optional An array of entry times for handling*) – left truncation (the subject is not in the risk set on or before the entry time) * **title** (*string*) – Optional title used for plots and summary output. * **freq\_weights** (*array-like*) – Optional frequency weights * **exog** (*array-like*) – Optional, if present used to account for violation of independent censoring. * **bw\_factor** (*float*) – Band-width multiplier for kernel-based estimation. Only used if exog is provided. | `surv_prob` *array-like* – The estimated value of the survivor function at each time point in `surv_times`. `surv_prob_se` *array-like* – The standard errors for the values in `surv_prob`. Not available if exog is provided. `surv_times` *array-like* – The points where the survival function changes. `n_risk` *array-like* – The number of subjects at risk just before each time value in `surv_times`. Not available if exog is provided. `n_events` *array-like* – The number of events (e.g. deaths) that occur at each point in `surv_times`. Not available if exog is provided. #### Notes If exog is None, the standard Kaplan-Meier estimator is used. If exog is not None, a local estimate of the marginal survival function around each point is constructed, and these are then averaged. This procedure gives an estimate of the marginal survival function that accounts for dependent censoring as long as the censoring becomes independent when conditioning on the covariates in exog. See Zeng et al. (2004) for details. #### References D. Zeng (2004). Estimating marginal survival function by adjusting for dependent censoring using many covariates. Annals of Statistics 32:4. <http://arxiv.org/pdf/math/0409180.pdf> #### Methods | | | | --- | --- | | [`plot`](statsmodels.duration.survfunc.survfuncright.plot#statsmodels.duration.survfunc.SurvfuncRight.plot "statsmodels.duration.survfunc.SurvfuncRight.plot")([ax]) | Plot the survival function. | | [`quantile`](statsmodels.duration.survfunc.survfuncright.quantile#statsmodels.duration.survfunc.SurvfuncRight.quantile "statsmodels.duration.survfunc.SurvfuncRight.quantile")(p) | Estimated quantile of a survival distribution. | | [`quantile_ci`](statsmodels.duration.survfunc.survfuncright.quantile_ci#statsmodels.duration.survfunc.SurvfuncRight.quantile_ci "statsmodels.duration.survfunc.SurvfuncRight.quantile_ci")(p[, alpha, method]) | Returns a confidence interval for a survival quantile. | | [`simultaneous_cb`](statsmodels.duration.survfunc.survfuncright.simultaneous_cb#statsmodels.duration.survfunc.SurvfuncRight.simultaneous_cb "statsmodels.duration.survfunc.SurvfuncRight.simultaneous_cb")([alpha, method, transform]) | Returns a simultaneous confidence band for the survival function. | | [`summary`](statsmodels.duration.survfunc.survfuncright.summary#statsmodels.duration.survfunc.SurvfuncRight.summary "statsmodels.duration.survfunc.SurvfuncRight.summary")() | Return a summary of the estimated survival function. | statsmodels statsmodels.sandbox.distributions.transformed.TransfTwo_gen.logcdf statsmodels.sandbox.distributions.transformed.TransfTwo\_gen.logcdf =================================================================== `TransfTwo_gen.logcdf(x, *args, **kwds)` Log of the cumulative distribution function at x of the given RV. | Parameters: | * **x** (*array\_like*) – quantiles * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **logcdf** – Log of the cumulative distribution function evaluated at x | | Return type: | array\_like | statsmodels statsmodels.genmod.generalized_estimating_equations.GEEResults.sensitivity_params statsmodels.genmod.generalized\_estimating\_equations.GEEResults.sensitivity\_params ==================================================================================== `GEEResults.sensitivity_params(dep_params_first, dep_params_last, num_steps)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_estimating_equations.html#GEEResults.sensitivity_params) Refits the GEE model using a sequence of values for the dependence parameters. | Parameters: | * **dep\_params\_first** (*array-like*) – The first dep\_params in the sequence * **dep\_params\_last** (*array-like*) – The last dep\_params in the sequence * **num\_steps** (*int*) – The number of dep\_params in the sequence | | Returns: | **results** – The GEEResults objects resulting from the fits. | | Return type: | array-like | statsmodels statsmodels.stats.correlation_tools.FactoredPSDMatrix.to_matrix statsmodels.stats.correlation\_tools.FactoredPSDMatrix.to\_matrix ================================================================= `FactoredPSDMatrix.to_matrix()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/correlation_tools.html#FactoredPSDMatrix.to_matrix) Returns the PSD matrix represented by this instance as a full (square) matrix. statsmodels statsmodels.sandbox.distributions.extras.NormExpan_gen.fit_loc_scale statsmodels.sandbox.distributions.extras.NormExpan\_gen.fit\_loc\_scale ======================================================================= `NormExpan_gen.fit_loc_scale(data, *args)` Estimate loc and scale parameters from data using 1st and 2nd moments. | Parameters: | * **data** (*array\_like*) – Data to fit. * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information). | | Returns: | * **Lhat** (*float*) – Estimated location parameter for the data. * **Shat** (*float*) – Estimated scale parameter for the data. | statsmodels statsmodels.discrete.discrete_model.CountResults.f_test statsmodels.discrete.discrete\_model.CountResults.f\_test ========================================================= `CountResults.f_test(r_matrix, cov_p=None, scale=1.0, invcov=None)` Compute the F-test for a joint linear hypothesis. This is a special case of `wald_test` that always uses the F distribution. | Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) – + array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length k row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – Default is 1.0 for no scaling. * **invcov** (*array-like**,* *optional*) – A q x q array to specify an inverse covariance matrix based on a restrictions matrix. | | Returns: | **res** – The results for the test are attributes of this results instance. | | Return type: | ContrastResults instance | #### Examples ``` >>> import numpy as np >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> A = np.identity(len(results.params)) >>> A = A[1:,:] ``` This tests that each coefficient is jointly statistically significantly different from zero. ``` >>> print(results.f_test(A)) <F test: F=array([[ 330.28533923]]), p=4.984030528700946e-10, df_denom=9, df_num=6> ``` Compare this to ``` >>> results.fvalue 330.2853392346658 >>> results.f_pvalue 4.98403096572e-10 ``` ``` >>> B = np.array(([0,0,1,-1,0,0,0],[0,0,0,0,0,1,-1])) ``` This tests that the coefficient on the 2nd and 3rd regressors are equal and jointly that the coefficient on the 5th and 6th regressors are equal. ``` >>> print(results.f_test(B)) <F test: F=array([[ 9.74046187]]), p=0.005605288531708235, df_denom=9, df_num=2> ``` Alternatively, you can specify the hypothesis tests using a string ``` >>> from statsmodels.datasets import longley >>> from statsmodels.formula.api import ols >>> dta = longley.load_pandas().data >>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' >>> results = ols(formula, dta).fit() >>> hypotheses = '(GNPDEFL = GNP), (UNEMP = 2), (YEAR/1829 = 1)' >>> f_test = results.f_test(hypotheses) >>> print(f_test) <F test: F=array([[ 144.17976065]]), p=6.322026217355609e-08, df_denom=9, df_num=3> ``` See also [`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`wald_test`](statsmodels.discrete.discrete_model.countresults.wald_test#statsmodels.discrete.discrete_model.CountResults.wald_test "statsmodels.discrete.discrete_model.CountResults.wald_test"), [`t_test`](statsmodels.discrete.discrete_model.countresults.t_test#statsmodels.discrete.discrete_model.CountResults.t_test "statsmodels.discrete.discrete_model.CountResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") #### Notes The matrix `r_matrix` is assumed to be non-singular. More precisely, r\_matrix (pX pX.T) r\_matrix.T is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full. statsmodels statsmodels.tsa.statespace.varmax.VARMAXResults.t_test statsmodels.tsa.statespace.varmax.VARMAXResults.t\_test ======================================================= `VARMAXResults.t_test(r_matrix, cov_p=None, scale=None, use_t=None)` Compute a t-test for a each linear hypothesis of the form Rb = q | Parameters: | * **r\_matrix** (*array-like**,* *str**,* *tuple*) – + array : If an array is given, a p x k 2d array or length k 1d array specifying the linear restrictions. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q). If q is given, can be either a scalar or a length p row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – An optional `scale` to use. Default is the scale specified by the model fit. * **use\_t** (*bool**,* *optional*) – If use\_t is None, then the default of the model is used. If use\_t is True, then the p-values are based on the t distribution. If use\_t is False, then the p-values are based on the normal distribution. | | Returns: | **res** – The results for the test are attributes of this results instance. The available results have the same elements as the parameter table in `summary()`. | | Return type: | ContrastResults instance | #### Examples ``` >>> import numpy as np >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> r = np.zeros_like(results.params) >>> r[5:] = [1,-1] >>> print(r) [ 0. 0. 0. 0. 0. 1. -1.] ``` r tests that the coefficients on the 5th and 6th independent variable are the same. ``` >>> T_test = results.t_test(r) >>> print(T_test) Test for Constraints ============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------ c0 -1829.2026 455.391 -4.017 0.003 -2859.368 -799.037 ============================================================================== >>> T_test.effect -1829.2025687192481 >>> T_test.sd 455.39079425193762 >>> T_test.tvalue -4.0167754636411717 >>> T_test.pvalue 0.0015163772380899498 ``` Alternatively, you can specify the hypothesis tests using a string ``` >>> from statsmodels.formula.api import ols >>> dta = sm.datasets.longley.load_pandas().data >>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' >>> results = ols(formula, dta).fit() >>> hypotheses = 'GNPDEFL = GNP, UNEMP = 2, YEAR/1829 = 1' >>> t_test = results.t_test(hypotheses) >>> print(t_test) Test for Constraints ============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------ c0 15.0977 84.937 0.178 0.863 -177.042 207.238 c1 -2.0202 0.488 -8.231 0.000 -3.125 -0.915 c2 1.0001 0.249 0.000 1.000 0.437 1.563 ============================================================================== ``` See also [`tvalues`](statsmodels.tsa.statespace.varmax.varmaxresults.tvalues#statsmodels.tsa.statespace.varmax.VARMAXResults.tvalues "statsmodels.tsa.statespace.varmax.VARMAXResults.tvalues") individual t statistics [`f_test`](statsmodels.tsa.statespace.varmax.varmaxresults.f_test#statsmodels.tsa.statespace.varmax.VARMAXResults.f_test "statsmodels.tsa.statespace.varmax.VARMAXResults.f_test") for F tests [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)")
programming_docs
statsmodels statsmodels.regression.linear_model.RegressionResults.bic statsmodels.regression.linear\_model.RegressionResults.bic ========================================================== `RegressionResults.bic()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#RegressionResults.bic) statsmodels statsmodels.tsa.statespace.varmax.VARMAX.loglike statsmodels.tsa.statespace.varmax.VARMAX.loglike ================================================ `VARMAX.loglike(params, *args, **kwargs)` Loglikelihood evaluation | Parameters: | * **params** (*array\_like*) – Array of parameters at which to evaluate the loglikelihood function. * **transformed** (*boolean**,* *optional*) – Whether or not `params` is already transformed. Default is True. * **kwargs** – Additional keyword arguments to pass to the Kalman filter. See `KalmanFilter.filter` for more details. | #### Notes [[1]](#id2) recommend maximizing the average likelihood to avoid scale issues; this is done automatically by the base Model fit method. #### References | | | | --- | --- | | [[1]](#id1) | Koopman, Siem Jan, Neil Shephard, and Jurgen A. Doornik. 1999. Statistical Algorithms for Models in State Space Using SsfPack 2.2. Econometrics Journal 2 (1): 107-60. doi:10.1111/1368-423X.00023. | See also [`update`](statsmodels.tsa.statespace.varmax.varmax.update#statsmodels.tsa.statespace.varmax.VARMAX.update "statsmodels.tsa.statespace.varmax.VARMAX.update") modifies the internal state of the state space model to reflect new params statsmodels statsmodels.iolib.summary2.Summary.as_text statsmodels.iolib.summary2.Summary.as\_text =========================================== `Summary.as_text()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/iolib/summary2.html#Summary.as_text) Generate ASCII Summary Table statsmodels statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialResults.bic statsmodels.discrete.count\_model.ZeroInflatedNegativeBinomialResults.bic ========================================================================= `ZeroInflatedNegativeBinomialResults.bic()` statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.simulate statsmodels.tsa.statespace.dynamic\_factor.DynamicFactor.simulate ================================================================= `DynamicFactor.simulate(params, nsimulations, measurement_shocks=None, state_shocks=None, initial_state=None)` Simulate a new time series following the state space model | Parameters: | * **params** (*array\_like*) – Array of model parameters. * **nsimulations** (*int*) – The number of observations to simulate. If the model is time-invariant this can be any number. If the model is time-varying, then this number must be less than or equal to the number * **measurement\_shocks** (*array\_like**,* *optional*) – If specified, these are the shocks to the measurement equation, \(\varepsilon\_t\). If unspecified, these are automatically generated using a pseudo-random number generator. If specified, must be shaped `nsimulations` x `k_endog`, where `k_endog` is the same as in the state space model. * **state\_shocks** (*array\_like**,* *optional*) – If specified, these are the shocks to the state equation, \(\eta\_t\). If unspecified, these are automatically generated using a pseudo-random number generator. If specified, must be shaped `nsimulations` x `k_posdef` where `k_posdef` is the same as in the state space model. * **initial\_state** (*array\_like**,* *optional*) – If specified, this is the state vector at time zero, which should be shaped (`k_states` x 1), where `k_states` is the same as in the state space model. If unspecified, but the model has been initialized, then that initialization is used. If unspecified and the model has not been initialized, then a vector of zeros is used. Note that this is not included in the returned `simulated_states` array. | | Returns: | **simulated\_obs** – An (nsimulations x k\_endog) array of simulated observations. | | Return type: | array | statsmodels statsmodels.sandbox.regression.gmm.LinearIVGMM.momcond_mean statsmodels.sandbox.regression.gmm.LinearIVGMM.momcond\_mean ============================================================ `LinearIVGMM.momcond_mean(params)` mean of moment conditions, statsmodels statsmodels.sandbox.distributions.transformed.ExpTransf_gen.std statsmodels.sandbox.distributions.transformed.ExpTransf\_gen.std ================================================================ `ExpTransf_gen.std(*args, **kwds)` Standard deviation of the distribution. | Parameters: | * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **std** – standard deviation of the distribution | | Return type: | float | statsmodels statsmodels.discrete.discrete_model.CountResults.initialize statsmodels.discrete.discrete\_model.CountResults.initialize ============================================================ `CountResults.initialize(model, params, **kwd)` statsmodels statsmodels.tsa.vector_ar.var_model.VARResults.cov_ybar statsmodels.tsa.vector\_ar.var\_model.VARResults.cov\_ybar ========================================================== `VARResults.cov_ybar()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/var_model.html#VARResults.cov_ybar) Asymptotically consistent estimate of covariance of the sample mean \[ \begin{align}\begin{aligned}\begin{split}\sqrt(T) (\bar{y} - \mu) \rightarrow {\cal N}(0, \Sigma\_{\bar{y}})\\\end{split}\\\Sigma\_{\bar{y}} = B \Sigma\_u B^\prime, \text{where } B = (I\_K - A\_1 - \cdots - A\_p)^{-1}\end{aligned}\end{align} \] #### Notes Lütkepohl Proposition 3.3 statsmodels statsmodels.tsa.statespace.varmax.VARMAX.filter statsmodels.tsa.statespace.varmax.VARMAX.filter =============================================== `VARMAX.filter(params, transformed=True, complex_step=False, cov_type=None, cov_kwds=None, return_ssm=False, results_class=None, results_wrapper_class=None, **kwargs)` Kalman filtering | Parameters: | * **params** (*array\_like*) – Array of parameters at which to evaluate the loglikelihood function. * **transformed** (*boolean**,* *optional*) – Whether or not `params` is already transformed. Default is True. * **return\_ssm** (*boolean**,**optional*) – Whether or not to return only the state space output or a full results object. Default is to return a full results object. * **cov\_type** (*str**,* *optional*) – See `MLEResults.fit` for a description of covariance matrix types for results object. * **cov\_kwds** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)") *or* *None**,* *optional*) – See `MLEResults.get_robustcov_results` for a description required keywords for alternative covariance estimators * **\*\*kwargs** – Additional keyword arguments to pass to the Kalman filter. See `KalmanFilter.filter` for more details. | statsmodels statsmodels.genmod.generalized_linear_model.GLM.estimate_tweedie_power statsmodels.genmod.generalized\_linear\_model.GLM.estimate\_tweedie\_power ========================================================================== `GLM.estimate_tweedie_power(mu, method='brentq', low=1.01, high=5.0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_linear_model.html#GLM.estimate_tweedie_power) Tweedie specific function to estimate scale and the variance parameter. The variance parameter is also referred to as p, xi, or shape. | Parameters: | * **mu** (*array-like*) – Fitted mean response variable * **method** (*str**,* *defaults to 'brentq'*) – Scipy optimizer used to solve the Pearson equation. Only brentq currently supported. * **low** (*float**,* *optional*) – Low end of the bracketing interval [a,b] to be used in the search for the power. Defaults to 1.01. * **high** (*float**,* *optional*) – High end of the bracketing interval [a,b] to be used in the search for the power. Defaults to 5. | | Returns: | **power** – The estimated shape or power | | Return type: | float | statsmodels statsmodels.regression.linear_model.OLSResults.remove_data statsmodels.regression.linear\_model.OLSResults.remove\_data ============================================================ `OLSResults.remove_data()` remove data arrays, all nobs arrays from result and model This reduces the size of the instance, so it can be pickled with less memory. Currently tested for use with predict from an unpickled results and model instance. Warning Since data and some intermediate results have been removed calculating new statistics that require them will raise exceptions. The exception will occur the first time an attribute is accessed that has been set to None. Not fully tested for time series models, tsa, and might delete too much for prediction or not all that would be possible. The lists of arrays to delete are maintained as attributes of the result and model instance, except for cached values. These lists could be changed before calling remove\_data. The attributes to remove are named in: `model._data_attr : arrays attached to both the model instance` and the results instance with the same attribute name. `result.data_in_cache : arrays that may exist as values in` result.\_cache (TODO : should privatize name) `result._data_attr_model : arrays attached to the model` instance but not to the results instance statsmodels statsmodels.stats.correlation_tools.FactoredPSDMatrix.logdet statsmodels.stats.correlation\_tools.FactoredPSDMatrix.logdet ============================================================= `FactoredPSDMatrix.logdet()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/correlation_tools.html#FactoredPSDMatrix.logdet) Returns the logarithm of the determinant of a factor-structured matrix. statsmodels statsmodels.duration.hazard_regression.PHRegResults.f_test statsmodels.duration.hazard\_regression.PHRegResults.f\_test ============================================================ `PHRegResults.f_test(r_matrix, cov_p=None, scale=1.0, invcov=None)` Compute the F-test for a joint linear hypothesis. This is a special case of `wald_test` that always uses the F distribution. | Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) – + array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length k row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – Default is 1.0 for no scaling. * **invcov** (*array-like**,* *optional*) – A q x q array to specify an inverse covariance matrix based on a restrictions matrix. | | Returns: | **res** – The results for the test are attributes of this results instance. | | Return type: | ContrastResults instance | #### Examples ``` >>> import numpy as np >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> A = np.identity(len(results.params)) >>> A = A[1:,:] ``` This tests that each coefficient is jointly statistically significantly different from zero. ``` >>> print(results.f_test(A)) <F test: F=array([[ 330.28533923]]), p=4.984030528700946e-10, df_denom=9, df_num=6> ``` Compare this to ``` >>> results.fvalue 330.2853392346658 >>> results.f_pvalue 4.98403096572e-10 ``` ``` >>> B = np.array(([0,0,1,-1,0,0,0],[0,0,0,0,0,1,-1])) ``` This tests that the coefficient on the 2nd and 3rd regressors are equal and jointly that the coefficient on the 5th and 6th regressors are equal. ``` >>> print(results.f_test(B)) <F test: F=array([[ 9.74046187]]), p=0.005605288531708235, df_denom=9, df_num=2> ``` Alternatively, you can specify the hypothesis tests using a string ``` >>> from statsmodels.datasets import longley >>> from statsmodels.formula.api import ols >>> dta = longley.load_pandas().data >>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' >>> results = ols(formula, dta).fit() >>> hypotheses = '(GNPDEFL = GNP), (UNEMP = 2), (YEAR/1829 = 1)' >>> f_test = results.f_test(hypotheses) >>> print(f_test) <F test: F=array([[ 144.17976065]]), p=6.322026217355609e-08, df_denom=9, df_num=3> ``` See also [`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`wald_test`](statsmodels.duration.hazard_regression.phregresults.wald_test#statsmodels.duration.hazard_regression.PHRegResults.wald_test "statsmodels.duration.hazard_regression.PHRegResults.wald_test"), [`t_test`](statsmodels.duration.hazard_regression.phregresults.t_test#statsmodels.duration.hazard_regression.PHRegResults.t_test "statsmodels.duration.hazard_regression.PHRegResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") #### Notes The matrix `r_matrix` is assumed to be non-singular. More precisely, r\_matrix (pX pX.T) r\_matrix.T is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full. statsmodels statsmodels.sandbox.distributions.transformed.LogTransf_gen.median statsmodels.sandbox.distributions.transformed.LogTransf\_gen.median =================================================================== `LogTransf_gen.median(*args, **kwds)` Median of the distribution. | Parameters: | * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – Location parameter, Default is 0. * **scale** (*array\_like**,* *optional*) – Scale parameter, Default is 1. | | Returns: | **median** – The median of the distribution. | | Return type: | float | See also `stats.distributions.rv_discrete.ppf` Inverse of the CDF statsmodels statsmodels.discrete.discrete_model.ProbitResults.prsquared statsmodels.discrete.discrete\_model.ProbitResults.prsquared ============================================================ `ProbitResults.prsquared()` statsmodels statsmodels.sandbox.stats.multicomp.StepDown statsmodels.sandbox.stats.multicomp.StepDown ============================================ `class statsmodels.sandbox.stats.multicomp.StepDown(vals, nobs_all, var_all, df=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/multicomp.html#StepDown) a class for step down methods This is currently for simple tree subset descend, similar to homogeneous\_subsets, but checks all leave-one-out subsets instead of assuming an ordered set. Comment in SAS manual: SAS only uses interval subsets of the sorted list, which is sufficient for range tests (maybe also equal variance and balanced sample sizes are required). For F-test based critical distances, the restriction to intervals is not sufficient. This version uses a single critical value of the studentized range distribution for all comparisons, and is therefore a step-down version of Tukey HSD. The class is written so it can be subclassed, where the get\_distance\_matrix and get\_crit are overwritten to obtain other step-down procedures such as REGW. iter\_subsets can be overwritten, to get a recursion as in the many to one comparison with a control such as in Dunnet’s test. A one-sided right tail test is not covered because the direction of the inequality is hard coded in check\_set. Also Peritz’s check of partitions is not possible, but I have not seen it mentioned in any more recent references. I have only partially read the step-down procedure for closed tests by Westfall. One change to make it more flexible, is to separate out the decision on a subset, also because the F-based tests, FREGW in SPSS, take information from all elements of a set and not just pairwise comparisons. I haven’t looked at the details of the F-based tests such as Sheffe yet. It looks like running an F-test on equality of means in each subset. This would also outsource how pairwise conditions are combined, any larger or max. This would also imply that the distance matrix cannot be calculated in advance for tests like the F-based ones. #### Methods | | | | --- | --- | | [`check_set`](statsmodels.sandbox.stats.multicomp.stepdown.check_set#statsmodels.sandbox.stats.multicomp.StepDown.check_set "statsmodels.sandbox.stats.multicomp.StepDown.check_set")(indices) | check whether pairwise distances of indices satisfy condition | | [`get_crit`](statsmodels.sandbox.stats.multicomp.stepdown.get_crit#statsmodels.sandbox.stats.multicomp.StepDown.get_crit "statsmodels.sandbox.stats.multicomp.StepDown.get_crit")(alpha) | | | [`get_distance_matrix`](statsmodels.sandbox.stats.multicomp.stepdown.get_distance_matrix#statsmodels.sandbox.stats.multicomp.StepDown.get_distance_matrix "statsmodels.sandbox.stats.multicomp.StepDown.get_distance_matrix")() | studentized range statistic | | [`iter_subsets`](statsmodels.sandbox.stats.multicomp.stepdown.iter_subsets#statsmodels.sandbox.stats.multicomp.StepDown.iter_subsets "statsmodels.sandbox.stats.multicomp.StepDown.iter_subsets")(indices) | | | [`run`](statsmodels.sandbox.stats.multicomp.stepdown.run#statsmodels.sandbox.stats.multicomp.StepDown.run "statsmodels.sandbox.stats.multicomp.StepDown.run")(alpha) | main function to run the test, | | [`stepdown`](statsmodels.sandbox.stats.multicomp.stepdown.stepdown#statsmodels.sandbox.stats.multicomp.StepDown.stepdown "statsmodels.sandbox.stats.multicomp.StepDown.stepdown")(indices) | | statsmodels statsmodels.sandbox.regression.gmm.NonlinearIVGMM.gmmobjective statsmodels.sandbox.regression.gmm.NonlinearIVGMM.gmmobjective ============================================================== `NonlinearIVGMM.gmmobjective(params, weights)` objective function for GMM minimization | Parameters: | * **params** (*array*) – parameter values at which objective is evaluated * **weights** (*array*) – weighting matrix | | Returns: | **jval** – value of objective function | | Return type: | float | statsmodels statsmodels.stats.outliers_influence.OLSInfluence.summary_table statsmodels.stats.outliers\_influence.OLSInfluence.summary\_table ================================================================= `OLSInfluence.summary_table(float_fmt='%6.3f')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/outliers_influence.html#OLSInfluence.summary_table) create a summary table with all influence and outlier measures This does currently not distinguish between statistics that can be calculated from the original regression results and for which a leave-one-observation-out loop is needed | Returns: | **res** – SimpleTable instance with the results, can be printed | | Return type: | SimpleTable instance | #### Notes This also attaches table\_data to the instance. statsmodels statsmodels.discrete.discrete_model.Logit.predict statsmodels.discrete.discrete\_model.Logit.predict ================================================== `Logit.predict(params, exog=None, linear=False)` Predict response variable of a model given exogenous variables. | Parameters: | * **params** (*array-like*) – Fitted parameters of the model. * **exog** (*array-like*) – 1d or 2d array of exogenous values. If not supplied, the whole exog attribute of the model is used. * **linear** (*bool**,* *optional*) – If True, returns the linear predictor dot(exog,params). Else, returns the value of the cdf at the linear predictor. | | Returns: | Fitted values at exog. | | Return type: | array |
programming_docs
statsmodels statsmodels.graphics.regressionplots.plot_partregress statsmodels.graphics.regressionplots.plot\_partregress ====================================================== `statsmodels.graphics.regressionplots.plot_partregress(endog, exog_i, exog_others, data=None, title_kwargs={}, obs_labels=True, label_kwargs={}, ax=None, ret_coords=False, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/graphics/regressionplots.html#plot_partregress) Plot partial regression for a single regressor. | Parameters: | * **endog** (*ndarray* *or* *string*) – endogenous or response variable. If string is given, you can use a arbitrary translations as with a formula. * **exog\_i** (*ndarray* *or* *string*) – exogenous, explanatory variable. If string is given, you can use a arbitrary translations as with a formula. * **exog\_others** (*ndarray* *or* *list of strings*) – other exogenous, explanatory variables. If a list of strings is given, each item is a term in formula. You can use a arbitrary translations as with a formula. The effect of these variables will be removed by OLS regression. * **data** (*DataFrame**,* [dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")*, or* *recarray*) – Some kind of data structure with names if the other variables are given as strings. * **title\_kwargs** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")) – Keyword arguments to pass on for the title. The key to control the fonts is fontdict. * **obs\_labels** (*bool* *or* *array-like*) – Whether or not to annotate the plot points with their observation labels. If obs\_labels is a boolean, the point labels will try to do the right thing. First it will try to use the index of data, then fall back to the index of exog\_i. Alternatively, you may give an array-like object corresponding to the obseveration numbers. * **labels\_kwargs** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")) – Keyword arguments that control annotate for the observation labels. * **ax** (*Matplotlib AxesSubplot instance**,* *optional*) – If given, this subplot is used to plot in instead of a new figure being created. * **ret\_coords** (*bool*) – If True will return the coordinates of the points in the plot. You can use this to add your own annotations. * **kwargs** – The keyword arguments passed to plot for the points. | | Returns: | * **fig** (*Matplotlib figure instance*) – If `ax` is None, the created figure. Otherwise the figure to which `ax` is connected. * **coords** (*list, optional*) – If ret\_coords is True, return a tuple of arrays (x\_coords, y\_coords). | #### Notes The slope of the fitted line is the that of `exog_i` in the full multiple regression. The individual points can be used to assess the influence of points on the estimated coefficient. See also `plot_partregress_grid` Plot partial regression for a set of regressors. statsmodels statsmodels.tsa.statespace.structural.UnobservedComponentsResults.test_heteroskedasticity statsmodels.tsa.statespace.structural.UnobservedComponentsResults.test\_heteroskedasticity ========================================================================================== `UnobservedComponentsResults.test_heteroskedasticity(method, alternative='two-sided', use_f=True)` Test for heteroskedasticity of standardized residuals Tests whether the sum-of-squares in the first third of the sample is significantly different than the sum-of-squares in the last third of the sample. Analogous to a Goldfeld-Quandt test. The null hypothesis is of no heteroskedasticity. | Parameters: | * **method** (*string {'breakvar'}* *or* *None*) – The statistical test for heteroskedasticity. Must be ‘breakvar’ for test of a break in the variance. If None, an attempt is made to select an appropriate test. * **alternative** (*string**,* *'increasing'**,* *'decreasing'* *or* *'two-sided'*) – This specifies the alternative for the p-value calculation. Default is two-sided. * **use\_f** (*boolean**,* *optional*) – Whether or not to compare against the asymptotic distribution (chi-squared) or the approximate small-sample distribution (F). Default is True (i.e. default is to compare against an F distribution). | | Returns: | **output** – An array with `(test_statistic, pvalue)` for each endogenous variable. The array is then sized `(k_endog, 2)`. If the method is called as `het = res.test_heteroskedasticity()`, then `het[0]` is an array of size 2 corresponding to the first endogenous variable, where `het[0][0]` is the test statistic, and `het[0][1]` is the p-value. | | Return type: | array | #### Notes The null hypothesis is of no heteroskedasticity. That means different things depending on which alternative is selected: * Increasing: Null hypothesis is that the variance is not increasing throughout the sample; that the sum-of-squares in the later subsample is *not* greater than the sum-of-squares in the earlier subsample. * Decreasing: Null hypothesis is that the variance is not decreasing throughout the sample; that the sum-of-squares in the earlier subsample is *not* greater than the sum-of-squares in the later subsample. * Two-sided: Null hypothesis is that the variance is not changing throughout the sample. Both that the sum-of-squares in the earlier subsample is not greater than the sum-of-squares in the later subsample *and* that the sum-of-squares in the later subsample is not greater than the sum-of-squares in the earlier subsample. For \(h = [T/3]\), the test statistic is: \[H(h) = \sum\_{t=T-h+1}^T \tilde v\_t^2 \Bigg / \sum\_{t=d+1}^{d+1+h} \tilde v\_t^2\] where \(d\) is the number of periods in which the loglikelihood was burned in the parent model (usually corresponding to diffuse initialization). This statistic can be tested against an \(F(h,h)\) distribution. Alternatively, \(h H(h)\) is asymptotically distributed according to \(\chi\_h^2\); this second test can be applied by passing `asymptotic=True` as an argument. See section 5.4 of [[1]](#id2) for the above formula and discussion, as well as additional details. TODO * Allow specification of \(h\) #### References | | | | --- | --- | | [[1]](#id1) | Harvey, Andrew C. 1990. *Forecasting, Structural Time Series* *Models and the Kalman Filter.* Cambridge University Press. | statsmodels statsmodels.iolib.table.SimpleTable.insert_header_row statsmodels.iolib.table.SimpleTable.insert\_header\_row ======================================================= `SimpleTable.insert_header_row(rownum, headers, dec_below='header_dec_below')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/iolib/table.html#SimpleTable.insert_header_row) Return None. Insert a row of headers, where `headers` is a sequence of strings. (The strings may contain newlines, to indicated multiline headers.) statsmodels statsmodels.genmod.generalized_linear_model.GLM.estimate_scale statsmodels.genmod.generalized\_linear\_model.GLM.estimate\_scale ================================================================= `GLM.estimate_scale(mu)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_linear_model.html#GLM.estimate_scale) Estimates the dispersion/scale. Type of scale can be chose in the fit method. | Parameters: | **mu** (*array*) – mu is the mean response estimate | | Returns: | | | Return type: | Estimate of scale | #### Notes The default scale for Binomial and Poisson families is 1. The default for the other families is Pearson’s Chi-Square estimate. See also [`statsmodels.genmod.generalized_linear_model.GLM.fit`](statsmodels.genmod.generalized_linear_model.glm.fit#statsmodels.genmod.generalized_linear_model.GLM.fit "statsmodels.genmod.generalized_linear_model.GLM.fit"), [`information`](statsmodels.genmod.generalized_linear_model.glm.information#statsmodels.genmod.generalized_linear_model.GLM.information "statsmodels.genmod.generalized_linear_model.GLM.information") statsmodels statsmodels.discrete.discrete_model.NegativeBinomial statsmodels.discrete.discrete\_model.NegativeBinomial ===================================================== `class statsmodels.discrete.discrete_model.NegativeBinomial(endog, exog, loglike_method='nb2', offset=None, exposure=None, missing='none', **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#NegativeBinomial) Negative Binomial Model for count data | Parameters: | * **endog** (*array-like*) – 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 `statsmodels.tools.add_constant`. * **loglike\_method** (*string*) – Log-likelihood type. ‘nb2’,’nb1’, or ‘geometric’. Fitted value \(\mu\) Heterogeneity parameter \(\alpha\) + nb2: Variance equal to \(\mu + \alpha\mu^2\) (most common) + nb1: Variance equal to \(\mu + \alpha\mu\) + geometric: Variance equal to \(\mu + \mu^2\) * **offset** (*array\_like*) – Offset is added to the linear prediction with coefficient equal to 1. * **exposure** (*array\_like*) – Log(exposure) 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.’ | `endog` *array* – A reference to the endogenous response variable `exog` *array* – A reference to the exogenous design. #### References References: Greene, W. 2008. “Functional forms for the negtive binomial model for count data”. Economics Letters. Volume 99, Number 3, pp.585-590. Hilbe, J.M. 2011. “Negative binomial regression”. Cambridge University Press. #### Methods | | | | --- | --- | | [`cdf`](statsmodels.discrete.discrete_model.negativebinomial.cdf#statsmodels.discrete.discrete_model.NegativeBinomial.cdf "statsmodels.discrete.discrete_model.NegativeBinomial.cdf")(X) | The cumulative distribution function of the model. | | [`cov_params_func_l1`](statsmodels.discrete.discrete_model.negativebinomial.cov_params_func_l1#statsmodels.discrete.discrete_model.NegativeBinomial.cov_params_func_l1 "statsmodels.discrete.discrete_model.NegativeBinomial.cov_params_func_l1")(likelihood\_model, xopt, …) | Computes cov\_params on a reduced parameter space corresponding to the nonzero parameters resulting from the l1 regularized fit. | | [`fit`](statsmodels.discrete.discrete_model.negativebinomial.fit#statsmodels.discrete.discrete_model.NegativeBinomial.fit "statsmodels.discrete.discrete_model.NegativeBinomial.fit")([start\_params, method, maxiter, …]) | Fit the model using maximum likelihood. | | [`fit_regularized`](statsmodels.discrete.discrete_model.negativebinomial.fit_regularized#statsmodels.discrete.discrete_model.NegativeBinomial.fit_regularized "statsmodels.discrete.discrete_model.NegativeBinomial.fit_regularized")([start\_params, method, …]) | Fit the model using a regularized maximum likelihood. | | [`from_formula`](statsmodels.discrete.discrete_model.negativebinomial.from_formula#statsmodels.discrete.discrete_model.NegativeBinomial.from_formula "statsmodels.discrete.discrete_model.NegativeBinomial.from_formula")(formula, data[, subset, drop\_cols]) | Create a Model from a formula and dataframe. | | [`hessian`](statsmodels.discrete.discrete_model.negativebinomial.hessian#statsmodels.discrete.discrete_model.NegativeBinomial.hessian "statsmodels.discrete.discrete_model.NegativeBinomial.hessian")(params) | The Hessian matrix of the model | | [`information`](statsmodels.discrete.discrete_model.negativebinomial.information#statsmodels.discrete.discrete_model.NegativeBinomial.information "statsmodels.discrete.discrete_model.NegativeBinomial.information")(params) | Fisher information matrix of model | | [`initialize`](statsmodels.discrete.discrete_model.negativebinomial.initialize#statsmodels.discrete.discrete_model.NegativeBinomial.initialize "statsmodels.discrete.discrete_model.NegativeBinomial.initialize")() | Initialize is called by statsmodels.model.LikelihoodModel.\_\_init\_\_ and should contain any preprocessing that needs to be done for a model. | | [`loglike`](statsmodels.discrete.discrete_model.negativebinomial.loglike#statsmodels.discrete.discrete_model.NegativeBinomial.loglike "statsmodels.discrete.discrete_model.NegativeBinomial.loglike")(params) | Loglikelihood for negative binomial model | | [`pdf`](statsmodels.discrete.discrete_model.negativebinomial.pdf#statsmodels.discrete.discrete_model.NegativeBinomial.pdf "statsmodels.discrete.discrete_model.NegativeBinomial.pdf")(X) | The probability density (mass) function of the model. | | [`predict`](statsmodels.discrete.discrete_model.negativebinomial.predict#statsmodels.discrete.discrete_model.NegativeBinomial.predict "statsmodels.discrete.discrete_model.NegativeBinomial.predict")(params[, exog, exposure, offset, linear]) | Predict response variable of a count model given exogenous variables. | | [`score`](statsmodels.discrete.discrete_model.negativebinomial.score#statsmodels.discrete.discrete_model.NegativeBinomial.score "statsmodels.discrete.discrete_model.NegativeBinomial.score")(params) | Score vector of model. | | [`score_obs`](statsmodels.discrete.discrete_model.negativebinomial.score_obs#statsmodels.discrete.discrete_model.NegativeBinomial.score_obs "statsmodels.discrete.discrete_model.NegativeBinomial.score_obs")(params) | | #### Attributes | | | | --- | --- | | `endog_names` | Names of endogenous variables | | `exog_names` | Names of exogenous variables | statsmodels statsmodels.sandbox.tsa.fftarma.ArmaFft.arma2ma statsmodels.sandbox.tsa.fftarma.ArmaFft.arma2ma =============================================== `ArmaFft.arma2ma(lags=None)` statsmodels statsmodels.discrete.discrete_model.MultinomialResults.normalized_cov_params statsmodels.discrete.discrete\_model.MultinomialResults.normalized\_cov\_params =============================================================================== `MultinomialResults.normalized_cov_params()` statsmodels statsmodels.sandbox.regression.try_ols_anova.data2dummy statsmodels.sandbox.regression.try\_ols\_anova.data2dummy ========================================================= `statsmodels.sandbox.regression.try_ols_anova.data2dummy(x, returnall=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/try_ols_anova.html#data2dummy) convert array of categories to dummy variables by default drops dummy variable for last category uses ravel, 1d only statsmodels statsmodels.sandbox.regression.gmm.GMMResults.jtest statsmodels.sandbox.regression.gmm.GMMResults.jtest =================================================== `GMMResults.jtest()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#GMMResults.jtest) overidentification test I guess this is missing a division by nobs, what’s the normalization in jval ? statsmodels statsmodels.sandbox.stats.multicomp.MultiComparison statsmodels.sandbox.stats.multicomp.MultiComparison =================================================== `class statsmodels.sandbox.stats.multicomp.MultiComparison(data, groups, group_order=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/multicomp.html#MultiComparison) Tests for multiple comparisons | Parameters: | * **data** (*array*) – independent data samples * **groups** (*array*) – group labels corresponding to each data point * **group\_order** (*list of strings**,* *optional*) – the desired order for the group mean results to be reported in. If not specified, results are reported in increasing order. If group\_order does not contain all labels that are in groups, then only those observations are kept that have a label in group\_order. | #### Methods | | | | --- | --- | | [`allpairtest`](statsmodels.sandbox.stats.multicomp.multicomparison.allpairtest#statsmodels.sandbox.stats.multicomp.MultiComparison.allpairtest "statsmodels.sandbox.stats.multicomp.MultiComparison.allpairtest")(testfunc[, alpha, method, pvalidx]) | run a pairwise test on all pairs with multiple test correction | | [`getranks`](statsmodels.sandbox.stats.multicomp.multicomparison.getranks#statsmodels.sandbox.stats.multicomp.MultiComparison.getranks "statsmodels.sandbox.stats.multicomp.MultiComparison.getranks")() | convert data to rankdata and attach | | [`kruskal`](statsmodels.sandbox.stats.multicomp.multicomparison.kruskal#statsmodels.sandbox.stats.multicomp.MultiComparison.kruskal "statsmodels.sandbox.stats.multicomp.MultiComparison.kruskal")([pairs, multimethod]) | pairwise comparison for kruskal-wallis test | | [`tukeyhsd`](statsmodels.sandbox.stats.multicomp.multicomparison.tukeyhsd#statsmodels.sandbox.stats.multicomp.MultiComparison.tukeyhsd "statsmodels.sandbox.stats.multicomp.MultiComparison.tukeyhsd")([alpha]) | Tukey’s range test to compare means of all pairs of groups | statsmodels statsmodels.robust.robust_linear_model.RLMResults.llf statsmodels.robust.robust\_linear\_model.RLMResults.llf ======================================================= `RLMResults.llf()` statsmodels statsmodels.genmod.families.family.Binomial.resid_dev statsmodels.genmod.families.family.Binomial.resid\_dev ====================================================== `Binomial.resid_dev(endog, mu, var_weights=1.0, scale=1.0)` The deviance residuals | Parameters: | * **endog** (*array-like*) – The endogenous response variable * **mu** (*array-like*) – The inverse of the link function at the linear predicted values. * **var\_weights** (*array-like*) – 1d array of variance (analytic) weights. The default is 1. * **scale** (*float**,* *optional*) – An optional scale argument. The default is 1. | | Returns: | **resid\_dev** – Deviance residuals as defined below. | | Return type: | float | #### Notes The deviance residuals are defined by the contribution D\_i of observation i to the deviance as \[resid\\_dev\_i = sign(y\_i-\mu\_i) \sqrt{D\_i}\] D\_i is calculated from the \_resid\_dev method in each family. Distribution-specific documentation of the calculation is available there. statsmodels statsmodels.discrete.discrete_model.MNLogit statsmodels.discrete.discrete\_model.MNLogit ============================================ `class statsmodels.discrete.discrete_model.MNLogit(endog, exog, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#MNLogit) Multinomial logit model | Parameters: | * **endog** (*array-like*) – `endog` is an 1-d vector of the endogenous response. `endog` can contain strings, ints, or floats. Note that if it contains strings, every distinct string will be a category. No stripping of whitespace is done. * **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 `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.’ | `endog` *array* – A reference to the endogenous response variable `exog` *array* – A reference to the exogenous design. `J` *float* – The number of choices for the endogenous variable. Note that this is zero-indexed. `K` *float* – The actual number of parameters for the exogenous design. Includes the constant if the design has one. `names` *dict* – A dictionary mapping the column number in `wendog` to the variables in `endog`. `wendog` *array* – An n x j array where j is the number of unique categories in `endog`. Each column of j is a dummy variable indicating the category of each observation. See `names` for a dictionary mapping each column to its category. #### Notes See developer notes for further information on `MNLogit` internals. #### Methods | | | | --- | --- | | [`cdf`](statsmodels.discrete.discrete_model.mnlogit.cdf#statsmodels.discrete.discrete_model.MNLogit.cdf "statsmodels.discrete.discrete_model.MNLogit.cdf")(X) | Multinomial logit cumulative distribution function. | | [`cov_params_func_l1`](statsmodels.discrete.discrete_model.mnlogit.cov_params_func_l1#statsmodels.discrete.discrete_model.MNLogit.cov_params_func_l1 "statsmodels.discrete.discrete_model.MNLogit.cov_params_func_l1")(likelihood\_model, xopt, …) | Computes cov\_params on a reduced parameter space corresponding to the nonzero parameters resulting from the l1 regularized fit. | | [`fit`](statsmodels.discrete.discrete_model.mnlogit.fit#statsmodels.discrete.discrete_model.MNLogit.fit "statsmodels.discrete.discrete_model.MNLogit.fit")([start\_params, method, maxiter, …]) | Fit the model using maximum likelihood. | | [`fit_regularized`](statsmodels.discrete.discrete_model.mnlogit.fit_regularized#statsmodels.discrete.discrete_model.MNLogit.fit_regularized "statsmodels.discrete.discrete_model.MNLogit.fit_regularized")([start\_params, method, …]) | Fit the model using a regularized maximum likelihood. | | [`from_formula`](statsmodels.discrete.discrete_model.mnlogit.from_formula#statsmodels.discrete.discrete_model.MNLogit.from_formula "statsmodels.discrete.discrete_model.MNLogit.from_formula")(formula, data[, subset, drop\_cols]) | Create a Model from a formula and dataframe. | | [`hessian`](statsmodels.discrete.discrete_model.mnlogit.hessian#statsmodels.discrete.discrete_model.MNLogit.hessian "statsmodels.discrete.discrete_model.MNLogit.hessian")(params) | Multinomial logit Hessian matrix of the log-likelihood | | [`information`](statsmodels.discrete.discrete_model.mnlogit.information#statsmodels.discrete.discrete_model.MNLogit.information "statsmodels.discrete.discrete_model.MNLogit.information")(params) | Fisher information matrix of model | | [`initialize`](statsmodels.discrete.discrete_model.mnlogit.initialize#statsmodels.discrete.discrete_model.MNLogit.initialize "statsmodels.discrete.discrete_model.MNLogit.initialize")() | Preprocesses the data for MNLogit. | | [`loglike`](statsmodels.discrete.discrete_model.mnlogit.loglike#statsmodels.discrete.discrete_model.MNLogit.loglike "statsmodels.discrete.discrete_model.MNLogit.loglike")(params) | Log-likelihood of the multinomial logit model. | | [`loglike_and_score`](statsmodels.discrete.discrete_model.mnlogit.loglike_and_score#statsmodels.discrete.discrete_model.MNLogit.loglike_and_score "statsmodels.discrete.discrete_model.MNLogit.loglike_and_score")(params) | Returns log likelihood and score, efficiently reusing calculations. | | [`loglikeobs`](statsmodels.discrete.discrete_model.mnlogit.loglikeobs#statsmodels.discrete.discrete_model.MNLogit.loglikeobs "statsmodels.discrete.discrete_model.MNLogit.loglikeobs")(params) | Log-likelihood of the multinomial logit model for each observation. | | [`pdf`](statsmodels.discrete.discrete_model.mnlogit.pdf#statsmodels.discrete.discrete_model.MNLogit.pdf "statsmodels.discrete.discrete_model.MNLogit.pdf")(eXB) | NotImplemented | | [`predict`](statsmodels.discrete.discrete_model.mnlogit.predict#statsmodels.discrete.discrete_model.MNLogit.predict "statsmodels.discrete.discrete_model.MNLogit.predict")(params[, exog, linear]) | Predict response variable of a model given exogenous variables. | | [`score`](statsmodels.discrete.discrete_model.mnlogit.score#statsmodels.discrete.discrete_model.MNLogit.score "statsmodels.discrete.discrete_model.MNLogit.score")(params) | Score matrix for multinomial logit model log-likelihood | | [`score_obs`](statsmodels.discrete.discrete_model.mnlogit.score_obs#statsmodels.discrete.discrete_model.MNLogit.score_obs "statsmodels.discrete.discrete_model.MNLogit.score_obs")(params) | Jacobian matrix for multinomial logit model log-likelihood | #### Attributes | | | | --- | --- | | `endog_names` | Names of endogenous variables | | `exog_names` | Names of exogenous variables |
programming_docs
statsmodels statsmodels.discrete.discrete_model.MultinomialResults.wald_test statsmodels.discrete.discrete\_model.MultinomialResults.wald\_test ================================================================== `MultinomialResults.wald_test(r_matrix, cov_p=None, scale=1.0, invcov=None, use_f=None)` Compute a Wald-test for a joint linear hypothesis. | Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) – + array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length p row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – Default is 1.0 for no scaling. * **invcov** (*array-like**,* *optional*) – A q x q array to specify an inverse covariance matrix based on a restrictions matrix. * **use\_f** (*bool*) – If True, then the F-distribution is used. If False, then the asymptotic distribution, chisquare is used. If use\_f is None, then the F distribution is used if the model specifies that use\_t is True. The test statistic is proportionally adjusted for the distribution by the number of constraints in the hypothesis. | | Returns: | **res** – The results for the test are attributes of this results instance. | | Return type: | ContrastResults instance | See also [`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`f_test`](statsmodels.discrete.discrete_model.multinomialresults.f_test#statsmodels.discrete.discrete_model.MultinomialResults.f_test "statsmodels.discrete.discrete_model.MultinomialResults.f_test"), [`t_test`](statsmodels.discrete.discrete_model.multinomialresults.t_test#statsmodels.discrete.discrete_model.MultinomialResults.t_test "statsmodels.discrete.discrete_model.MultinomialResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") #### Notes The matrix `r_matrix` is assumed to be non-singular. More precisely, r\_matrix (pX pX.T) r\_matrix.T is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full. statsmodels statsmodels.tools.tools.clean0 statsmodels.tools.tools.clean0 ============================== `statsmodels.tools.tools.clean0(matrix)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tools/tools.html#clean0) Erase columns of zeros: can save some time in pseudoinverse. statsmodels statsmodels.multivariate.factor.FactorResults.rotate statsmodels.multivariate.factor.FactorResults.rotate ==================================================== `FactorResults.rotate(method)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/multivariate/factor.html#FactorResults.rotate) Apply rotation, inplace modification of this Results instance | Parameters: | **method** (*string*) – Rotation to be applied. Allowed methods are varimax, quartimax, biquartimax, equamax, oblimin, parsimax, parsimony, biquartimin, promax. | | Returns: | **None** | | Return type: | nothing returned, modifications are inplace | #### Notes Warning: ‘varimax’, ‘quartimax’ and ‘oblimin’ are verified against R or Stata. Some rotation methods such as promax do not produce the same results as the R or Stata default functions. See also `factor_rotation` subpackage that implements rotation methods statsmodels statsmodels.tsa.statespace.structural.UnobservedComponentsResults.simulate statsmodels.tsa.statespace.structural.UnobservedComponentsResults.simulate ========================================================================== `UnobservedComponentsResults.simulate(nsimulations, measurement_shocks=None, state_shocks=None, initial_state=None)` Simulate a new time series following the state space model | Parameters: | * **nsimulations** (*int*) – The number of observations to simulate. If the model is time-invariant this can be any number. If the model is time-varying, then this number must be less than or equal to the number * **measurement\_shocks** (*array\_like**,* *optional*) – If specified, these are the shocks to the measurement equation, \(\varepsilon\_t\). If unspecified, these are automatically generated using a pseudo-random number generator. If specified, must be shaped `nsimulations` x `k_endog`, where `k_endog` is the same as in the state space model. * **state\_shocks** (*array\_like**,* *optional*) – If specified, these are the shocks to the state equation, \(\eta\_t\). If unspecified, these are automatically generated using a pseudo-random number generator. If specified, must be shaped `nsimulations` x `k_posdef` where `k_posdef` is the same as in the state space model. * **initial\_state** (*array\_like**,* *optional*) – If specified, this is the state vector at time zero, which should be shaped (`k_states` x 1), where `k_states` is the same as in the state space model. If unspecified, but the model has been initialized, then that initialization is used. If unspecified and the model has not been initialized, then a vector of zeros is used. Note that this is not included in the returned `simulated_states` array. | | Returns: | **simulated\_obs** – An (nsimulations x k\_endog) array of simulated observations. | | Return type: | array | statsmodels statsmodels.robust.robust_linear_model.RLM.score statsmodels.robust.robust\_linear\_model.RLM.score ================================================== `RLM.score(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/robust_linear_model.html#RLM.score) Score vector of model. The gradient of logL with respect to each parameter. statsmodels statsmodels.discrete.discrete_model.NegativeBinomialResults.fittedvalues statsmodels.discrete.discrete\_model.NegativeBinomialResults.fittedvalues ========================================================================= `NegativeBinomialResults.fittedvalues()` statsmodels statsmodels.discrete.discrete_model.CountResults.resid statsmodels.discrete.discrete\_model.CountResults.resid ======================================================= `CountResults.resid()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#CountResults.resid) Residuals #### Notes The residuals for Count models are defined as \[y - p\] where \(p = \exp(X\beta)\). Any exposure and offset variables are also handled. statsmodels statsmodels.regression.mixed_linear_model.MixedLM.information statsmodels.regression.mixed\_linear\_model.MixedLM.information =============================================================== `MixedLM.information(params)` Fisher information matrix of model Returns -Hessian of loglike evaluated at params. statsmodels statsmodels.discrete.discrete_model.DiscreteResults.llnull statsmodels.discrete.discrete\_model.DiscreteResults.llnull =========================================================== `DiscreteResults.llnull()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#DiscreteResults.llnull) statsmodels statsmodels.genmod.generalized_estimating_equations.GEEResults.resid_centered_split statsmodels.genmod.generalized\_estimating\_equations.GEEResults.resid\_centered\_split ======================================================================================= `GEEResults.resid_centered_split()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_estimating_equations.html#GEEResults.resid_centered_split) Returns the residuals centered within each group. The residuals are returned as a list of arrays containing the centered residuals for each cluster. statsmodels statsmodels.sandbox.stats.multicomp.TukeyHSDResults statsmodels.sandbox.stats.multicomp.TukeyHSDResults =================================================== `class statsmodels.sandbox.stats.multicomp.TukeyHSDResults(mc_object, results_table, q_crit, reject=None, meandiffs=None, std_pairs=None, confint=None, df_total=None, reject2=None, variance=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/multicomp.html#TukeyHSDResults) Results from Tukey HSD test, with additional plot methods Can also compute and plot additional post-hoc evaluations using this results class. `reject` *array of boolean, True if we reject Null for group pair* `meandiffs` *pairwise mean differences* `confint` *confidence interval for pairwise mean differences* `std_pairs` *standard deviation of pairwise mean differences* `q_crit` *critical value of studentized range statistic at given alpha* `halfwidths` *half widths of simultaneous confidence interval* #### Notes halfwidths is only available after call to `plot_simultaneous`. Other attributes contain information about the data from the MultiComparison instance: data, df\_total, groups, groupsunique, variance. #### Methods | | | | --- | --- | | [`plot_simultaneous`](statsmodels.sandbox.stats.multicomp.tukeyhsdresults.plot_simultaneous#statsmodels.sandbox.stats.multicomp.TukeyHSDResults.plot_simultaneous "statsmodels.sandbox.stats.multicomp.TukeyHSDResults.plot_simultaneous")([comparison\_name, ax, …]) | Plot a universal confidence interval of each group mean | | [`summary`](statsmodels.sandbox.stats.multicomp.tukeyhsdresults.summary#statsmodels.sandbox.stats.multicomp.TukeyHSDResults.summary "statsmodels.sandbox.stats.multicomp.TukeyHSDResults.summary")() | Summary table that can be printed | statsmodels statsmodels.sandbox.stats.multicomp.maxzerodown statsmodels.sandbox.stats.multicomp.maxzerodown =============================================== `statsmodels.sandbox.stats.multicomp.maxzerodown(x)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/multicomp.html#maxzerodown) find all up zero crossings and return the index of the highest Not used anymore ``` >>> np.random.seed(12345) >>> x = np.random.randn(8) >>> x array([-0.20470766, 0.47894334, -0.51943872, -0.5557303 , 1.96578057, 1.39340583, 0.09290788, 0.28174615]) >>> maxzero(x) (4, array([1, 4])) ``` no up-zero-crossing at end ``` >>> np.random.seed(0) >>> x = np.random.randn(8) >>> x array([ 1.76405235, 0.40015721, 0.97873798, 2.2408932 , 1.86755799, -0.97727788, 0.95008842, -0.15135721]) >>> maxzero(x) (None, array([6])) ``` statsmodels statsmodels.tsa.vector_ar.var_model.VARResults.to_vecm statsmodels.tsa.vector\_ar.var\_model.VARResults.to\_vecm ========================================================= `VARResults.to_vecm()` statsmodels statsmodels.tsa.vector_ar.var_model.VARResults.acf statsmodels.tsa.vector\_ar.var\_model.VARResults.acf ==================================================== `VARResults.acf(nlags=None)` Compute theoretical autocovariance function | Returns: | **acf** | | Return type: | ndarray (p x k x k) | statsmodels statsmodels.stats.power.FTestPower.plot_power statsmodels.stats.power.FTestPower.plot\_power ============================================== `FTestPower.plot_power(dep_var='nobs', nobs=None, effect_size=None, alpha=0.05, ax=None, title=None, plt_kwds=None, **kwds)` plot power with number of observations or effect size on x-axis | Parameters: | * **dep\_var** (*string in* *[**'nobs'**,* *'effect\_size'**,* *'alpha'**]*) – This specifies which variable is used for the horizontal axis. If dep\_var=’nobs’ (default), then one curve is created for each value of `effect_size`. If dep\_var=’effect\_size’ or alpha, then one curve is created for each value of `nobs`. * **nobs** (*scalar* *or* *array\_like*) – specifies the values of the number of observations in the plot * **effect\_size** (*scalar* *or* *array\_like*) – specifies the values of the effect\_size in the plot * **alpha** (*float* *or* *array\_like*) – The significance level (type I error) used in the power calculation. Can only be more than a scalar, if `dep_var='alpha'` * **ax** (*None* *or* *axis instance*) – If ax is None, than a matplotlib figure is created. If ax is a matplotlib axis instance, then it is reused, and the plot elements are created with it. * **title** (*string*) – title for the axis. Use an empty string, `''`, to avoid a title. * **plt\_kwds** (*None* *or* [dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")) – not used yet * **kwds** (*optional keywords for power function*) – These remaining keyword arguments are used as arguments to the power function. Many power function support `alternative` as a keyword argument, two-sample test support `ratio`. | | Returns: | **fig** | | Return type: | matplotlib figure instance | #### Notes This works only for classes where the `power` method has `effect_size`, `nobs` and `alpha` as the first three arguments. If the second argument is `nobs1`, then the number of observations in the plot are those for the first sample. TODO: fix this for FTestPower and GofChisquarePower TODO: maybe add line variable, if we want more than nobs and effectsize statsmodels statsmodels.graphics.gofplots.ProbPlot.theoretical_percentiles statsmodels.graphics.gofplots.ProbPlot.theoretical\_percentiles =============================================================== `ProbPlot.theoretical_percentiles()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/graphics/gofplots.html#ProbPlot.theoretical_percentiles) statsmodels statsmodels.tsa.statespace.varmax.VARMAXResults.cov_params_robust_approx statsmodels.tsa.statespace.varmax.VARMAXResults.cov\_params\_robust\_approx =========================================================================== `VARMAXResults.cov_params_robust_approx()` (array) The QMLE variance / covariance matrix. Computed using the numerical Hessian as the evaluated hessian. statsmodels statsmodels.discrete.discrete_model.NegativeBinomialResults.load statsmodels.discrete.discrete\_model.NegativeBinomialResults.load ================================================================= `classmethod NegativeBinomialResults.load(fname)` load a pickle, (class method) | Parameters: | **fname** (*string* *or* *filehandle*) – fname can be a string to a file path or filename, or a filehandle. | | Returns: | | | Return type: | unpickled instance | statsmodels statsmodels.stats.contingency_tables.Table statsmodels.stats.contingency\_tables.Table =========================================== `class statsmodels.stats.contingency_tables.Table(table, shift_zeros=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table) A two-way contingency table. | Parameters: | * **table** (*array-like*) – A contingency table. * **shift\_zeros** (*boolean*) – If True and any cell count is zero, add 0.5 to all values in the table. | `table_orig` *array-like* – The original table is cached as `table_orig`. `marginal_probabilities` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table.marginal_probabilities) *tuple of two ndarrays* – The estimated row and column marginal distributions. `independence_probabilities` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table.independence_probabilities) *ndarray* – Estimated cell probabilities under row/column independence. `fittedvalues` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table.fittedvalues) *ndarray* – Fitted values under independence. `resid_pearson` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table.resid_pearson) *ndarray* – The Pearson residuals under row/column independence. `standardized_resids` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table.standardized_resids) *ndarray* – Residuals for the independent row/column model with approximate unit variance. `chi2_contribs` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table.chi2_contribs) *ndarray* – The contribution of each cell to the chi^2 statistic. `local_logodds_ratios` *ndarray* – The local log odds ratios are calculated for each 2x2 subtable formed from adjacent rows and columns. `local_oddsratios` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table.local_oddsratios) *ndarray* – The local odds ratios are calculated from each 2x2 subtable formed from adjacent rows and columns. `cumulative_log_oddsratios` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table.cumulative_log_oddsratios) *ndarray* – The cumulative log odds ratio at a given pair of thresholds is calculated by reducing the table to a 2x2 table based on dichotomizing the rows and columns at the given thresholds. The table of cumulative log odds ratios presents all possible cumulative log odds ratios that can be formed from a given table. `cumulative_oddsratios` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table.cumulative_oddsratios) *ndarray* – The cumulative odds ratios are calculated by reducing the table to a 2x2 table based on cutting the rows and columns at a given point. The table of cumulative odds ratios presents all possible cumulative odds ratios that can be formed from a given table. See also [`statsmodels.graphics.mosaicplot.mosaic`](statsmodels.graphics.mosaicplot.mosaic#statsmodels.graphics.mosaicplot.mosaic "statsmodels.graphics.mosaicplot.mosaic"), `scipy.stats.chi2_contingency` #### Notes The inference procedures used here are all based on a sampling model in which the units are independent and identically distributed, with each unit being classified with respect to two categorical variables. #### References Definitions of residuals: <https://onlinecourses.science.psu.edu/stat504/node/86> #### Methods | | | | --- | --- | | [`chi2_contribs`](statsmodels.stats.contingency_tables.table.chi2_contribs#statsmodels.stats.contingency_tables.Table.chi2_contribs "statsmodels.stats.contingency_tables.Table.chi2_contribs")() | | | [`cumulative_log_oddsratios`](statsmodels.stats.contingency_tables.table.cumulative_log_oddsratios#statsmodels.stats.contingency_tables.Table.cumulative_log_oddsratios "statsmodels.stats.contingency_tables.Table.cumulative_log_oddsratios")() | | | [`cumulative_oddsratios`](statsmodels.stats.contingency_tables.table.cumulative_oddsratios#statsmodels.stats.contingency_tables.Table.cumulative_oddsratios "statsmodels.stats.contingency_tables.Table.cumulative_oddsratios")() | | | [`fittedvalues`](statsmodels.stats.contingency_tables.table.fittedvalues#statsmodels.stats.contingency_tables.Table.fittedvalues "statsmodels.stats.contingency_tables.Table.fittedvalues")() | | | [`from_data`](statsmodels.stats.contingency_tables.table.from_data#statsmodels.stats.contingency_tables.Table.from_data "statsmodels.stats.contingency_tables.Table.from_data")(data[, shift\_zeros]) | Construct a Table object from data. | | [`independence_probabilities`](statsmodels.stats.contingency_tables.table.independence_probabilities#statsmodels.stats.contingency_tables.Table.independence_probabilities "statsmodels.stats.contingency_tables.Table.independence_probabilities")() | | | [`local_log_oddsratios`](statsmodels.stats.contingency_tables.table.local_log_oddsratios#statsmodels.stats.contingency_tables.Table.local_log_oddsratios "statsmodels.stats.contingency_tables.Table.local_log_oddsratios")() | | | [`local_oddsratios`](statsmodels.stats.contingency_tables.table.local_oddsratios#statsmodels.stats.contingency_tables.Table.local_oddsratios "statsmodels.stats.contingency_tables.Table.local_oddsratios")() | | | [`marginal_probabilities`](statsmodels.stats.contingency_tables.table.marginal_probabilities#statsmodels.stats.contingency_tables.Table.marginal_probabilities "statsmodels.stats.contingency_tables.Table.marginal_probabilities")() | | | [`resid_pearson`](statsmodels.stats.contingency_tables.table.resid_pearson#statsmodels.stats.contingency_tables.Table.resid_pearson "statsmodels.stats.contingency_tables.Table.resid_pearson")() | | | [`standardized_resids`](statsmodels.stats.contingency_tables.table.standardized_resids#statsmodels.stats.contingency_tables.Table.standardized_resids "statsmodels.stats.contingency_tables.Table.standardized_resids")() | | | [`test_nominal_association`](statsmodels.stats.contingency_tables.table.test_nominal_association#statsmodels.stats.contingency_tables.Table.test_nominal_association "statsmodels.stats.contingency_tables.Table.test_nominal_association")() | Assess independence for nominal factors. | | [`test_ordinal_association`](statsmodels.stats.contingency_tables.table.test_ordinal_association#statsmodels.stats.contingency_tables.Table.test_ordinal_association "statsmodels.stats.contingency_tables.Table.test_ordinal_association")([row\_scores, …]) | Assess independence between two ordinal variables. |
programming_docs
statsmodels statsmodels.tsa.holtwinters.Holt.fit statsmodels.tsa.holtwinters.Holt.fit ==================================== `Holt.fit(smoothing_level=None, smoothing_slope=None, damping_slope=None, optimized=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/holtwinters.html#Holt.fit) fit Holt’s Exponential Smoothing wrapper(…) | Parameters: | * **smoothing\_level** (*float**,* *optional*) – The alpha value of the simple exponential smoothing, if the value is set then this value will be used as the value. * **smoothing\_slope** (*float**,* *optional*) – The beta value of the holts trend method, if the value is set then this value will be used as the value. * **damping\_slope** (*float**,* *optional*) – The phi value of the damped method, if the value is set then this value will be used as the value. * **optimized** (*bool**,* *optional*) – Should the values that have not been set above be optimized automatically? | | Returns: | **results** – See statsmodels.tsa.holtwinters.HoltWintersResults | | Return type: | HoltWintersResults class | #### Notes This is a full implementation of the holts exponential smoothing as per [1]. #### References [1] Hyndman, Rob J., and George Athanasopoulos. Forecasting: principles and practice. OTexts, 2014. statsmodels statsmodels.discrete.discrete_model.MultinomialResults.llf statsmodels.discrete.discrete\_model.MultinomialResults.llf =========================================================== `MultinomialResults.llf()` statsmodels statsmodels.discrete.discrete_model.BinaryModel.from_formula statsmodels.discrete.discrete\_model.BinaryModel.from\_formula ============================================================== `classmethod BinaryModel.from_formula(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** (*extra arguments*) – These are passed to the model * **kwargs** (*extra keyword arguments*) – These are passed to the model with one exception. The `eval_env` keyword is passed to patsy. It can be either a [`patsy.EvalEnvironment`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.EvalEnvironment "(in patsy v0.5.0+dev)") 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** | | Return type: | 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 statsmodels.genmod.families.links.Logit.inverse_deriv statsmodels.genmod.families.links.Logit.inverse\_deriv ====================================================== `Logit.inverse_deriv(z)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/links.html#Logit.inverse_deriv) Derivative of the inverse of the logit transform | Parameters: | **z** (*array-like*) – `z` is usually the linear predictor for a GLM or GEE model. | | Returns: | **g’^(-1)(z)** – The value of the derivative of the inverse of the logit function | | Return type: | array | statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.scale statsmodels.sandbox.regression.gmm.IVRegressionResults.scale ============================================================ `IVRegressionResults.scale()` statsmodels statsmodels.regression.quantile_regression.QuantReg.hessian statsmodels.regression.quantile\_regression.QuantReg.hessian ============================================================ `QuantReg.hessian(params)` The Hessian matrix of the model statsmodels statsmodels.discrete.discrete_model.ProbitResults.set_null_options statsmodels.discrete.discrete\_model.ProbitResults.set\_null\_options ===================================================================== `ProbitResults.set_null_options(llnull=None, attach_results=True, **kwds)` set fit options for Null (constant-only) model This resets the cache for related attributes which is potentially fragile. This only sets the option, the null model is estimated when llnull is accessed, if llnull is not yet in cache. | Parameters: | * **llnull** (*None* *or* *float*) – If llnull is not None, then the value will be directly assigned to the cached attribute “llnull”. * **attach\_results** (*bool*) – Sets an internal flag whether the results instance of the null model should be attached. By default without calling this method, thenull model results are not attached and only the loglikelihood value llnull is stored. * **kwds** (*keyword arguments*) – `kwds` are directly used as fit keyword arguments for the null model, overriding any provided defaults. | | Returns: | | | Return type: | no returns, modifies attributes of this instance | statsmodels statsmodels.regression.linear_model.RegressionResults.tvalues statsmodels.regression.linear\_model.RegressionResults.tvalues ============================================================== `RegressionResults.tvalues()` Return the t-statistic for a given parameter estimate. statsmodels statsmodels.emplike.descriptive.DescStatUV.plot_contour statsmodels.emplike.descriptive.DescStatUV.plot\_contour ======================================================== `DescStatUV.plot_contour(mu_low, mu_high, var_low, var_high, mu_step, var_step, levs=[0.2, 0.1, 0.05, 0.01, 0.001])` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/emplike/descriptive.html#DescStatUV.plot_contour) Returns a plot of the confidence region for a univariate mean and variance. | Parameters: | * **mu\_low** (*float*) – Lowest value of the mean to plot * **mu\_high** (*float*) – Highest value of the mean to plot * **var\_low** (*float*) – Lowest value of the variance to plot * **var\_high** (*float*) – Highest value of the variance to plot * **mu\_step** (*float*) – Increments to evaluate the mean * **var\_step** (*float*) – Increments to evaluate the mean * **levs** (*list*) – Which values of significance the contour lines will be drawn. Default is [.2, .1, .05, .01, .001] | | Returns: | **fig** – The contour plot | | Return type: | matplotlib figure instance | statsmodels statsmodels.tsa.statespace.sarimax.SARIMAX.initialize_approximate_diffuse statsmodels.tsa.statespace.sarimax.SARIMAX.initialize\_approximate\_diffuse =========================================================================== `SARIMAX.initialize_approximate_diffuse(variance=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/sarimax.html#SARIMAX.initialize_approximate_diffuse) Initialize the statespace model with approximate diffuse values. Rather than following the exact diffuse treatment (which is developed for the case that the variance becomes infinitely large), this assigns an arbitrary large number for the variance. | Parameters: | **variance** (*float**,* *optional*) – The variance for approximating diffuse initial conditions. Default is 1e6. | statsmodels statsmodels.tsa.statespace.mlemodel.MLEResults.get_forecast statsmodels.tsa.statespace.mlemodel.MLEResults.get\_forecast ============================================================ `MLEResults.get_forecast(steps=1, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEResults.get_forecast) Out-of-sample forecasts | Parameters: | * **steps** (*int**,* *str**, or* *datetime**,* *optional*) – If an integer, the number of steps to forecast from the end of the sample. Can also be a date string to parse or a datetime type. However, if the dates index does not have a fixed frequency, steps must be an integer. Default * **\*\*kwargs** – Additional arguments may required for forecasting beyond the end of the sample. See `FilterResults.predict` for more details. | | Returns: | **forecast** – Array of out of sample forecasts. A (steps x k\_endog) array. | | Return type: | array | statsmodels statsmodels.regression.linear_model.GLSAR.iterative_fit statsmodels.regression.linear\_model.GLSAR.iterative\_fit ========================================================= `GLSAR.iterative_fit(maxiter=3, rtol=0.0001, **kwds)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#GLSAR.iterative_fit) Perform an iterative two-stage procedure to estimate a GLS model. The model is assumed to have AR(p) errors, AR(p) parameters and regression coefficients are estimated iteratively. | Parameters: | * **maxiter** (*integer**,* *optional*) – the number of iterations * **rtol** (*float**,* *optional*) – Relative tolerance between estimated coefficients to stop the estimation. Stops if max(abs(last - current) / abs(last)) < rtol | statsmodels statsmodels.discrete.discrete_model.LogitResults.initialize statsmodels.discrete.discrete\_model.LogitResults.initialize ============================================================ `LogitResults.initialize(model, params, **kwd)` statsmodels statsmodels.robust.robust_linear_model.RLMResults.t_test statsmodels.robust.robust\_linear\_model.RLMResults.t\_test =========================================================== `RLMResults.t_test(r_matrix, cov_p=None, scale=None, use_t=None)` Compute a t-test for a each linear hypothesis of the form Rb = q | Parameters: | * **r\_matrix** (*array-like**,* *str**,* *tuple*) – + array : If an array is given, a p x k 2d array or length k 1d array specifying the linear restrictions. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q). If q is given, can be either a scalar or a length p row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – An optional `scale` to use. Default is the scale specified by the model fit. * **use\_t** (*bool**,* *optional*) – If use\_t is None, then the default of the model is used. If use\_t is True, then the p-values are based on the t distribution. If use\_t is False, then the p-values are based on the normal distribution. | | Returns: | **res** – The results for the test are attributes of this results instance. The available results have the same elements as the parameter table in `summary()`. | | Return type: | ContrastResults instance | #### Examples ``` >>> import numpy as np >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> r = np.zeros_like(results.params) >>> r[5:] = [1,-1] >>> print(r) [ 0. 0. 0. 0. 0. 1. -1.] ``` r tests that the coefficients on the 5th and 6th independent variable are the same. ``` >>> T_test = results.t_test(r) >>> print(T_test) Test for Constraints ============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------ c0 -1829.2026 455.391 -4.017 0.003 -2859.368 -799.037 ============================================================================== >>> T_test.effect -1829.2025687192481 >>> T_test.sd 455.39079425193762 >>> T_test.tvalue -4.0167754636411717 >>> T_test.pvalue 0.0015163772380899498 ``` Alternatively, you can specify the hypothesis tests using a string ``` >>> from statsmodels.formula.api import ols >>> dta = sm.datasets.longley.load_pandas().data >>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' >>> results = ols(formula, dta).fit() >>> hypotheses = 'GNPDEFL = GNP, UNEMP = 2, YEAR/1829 = 1' >>> t_test = results.t_test(hypotheses) >>> print(t_test) Test for Constraints ============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------ c0 15.0977 84.937 0.178 0.863 -177.042 207.238 c1 -2.0202 0.488 -8.231 0.000 -3.125 -0.915 c2 1.0001 0.249 0.000 1.000 0.437 1.563 ============================================================================== ``` See also [`tvalues`](statsmodels.robust.robust_linear_model.rlmresults.tvalues#statsmodels.robust.robust_linear_model.RLMResults.tvalues "statsmodels.robust.robust_linear_model.RLMResults.tvalues") individual t statistics [`f_test`](statsmodels.robust.robust_linear_model.rlmresults.f_test#statsmodels.robust.robust_linear_model.RLMResults.f_test "statsmodels.robust.robust_linear_model.RLMResults.f_test") for F tests [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") statsmodels statsmodels.regression.quantile_regression.QuantRegResults.cov_HC0 statsmodels.regression.quantile\_regression.QuantRegResults.cov\_HC0 ==================================================================== `QuantRegResults.cov_HC0()` See statsmodels.RegressionResults statsmodels statsmodels.sandbox.regression.gmm.NonlinearIVGMM.momcond statsmodels.sandbox.regression.gmm.NonlinearIVGMM.momcond ========================================================= `NonlinearIVGMM.momcond(params)` statsmodels statsmodels.stats.diagnostic.linear_lm statsmodels.stats.diagnostic.linear\_lm ======================================= `statsmodels.stats.diagnostic.linear_lm(resid, exog, func=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/diagnostic.html#linear_lm) Lagrange multiplier test for linearity against functional alternative limitations: Assumes currently that the first column is integer. Currently it doesn’t check whether the transformed variables contain NaNs, for example log of negative number. | Parameters: | * **resid** (*ndarray*) – residuals of a regression * **exog** (*ndarray*) – exogenous variables for which linearity is tested * **func** (*callable*) – If func is None, then squares are used. func needs to take an array of exog and return an array of transformed variables. | | Returns: | * **lm** (*float*) – Lagrange multiplier test statistic * **lm\_pval** (*float*) – p-value of Lagrange multiplier tes * **ftest** (*ContrastResult instance*) – the results from the F test variant of this test | #### Notes written to match Gretl’s linearity test. The test runs an auxilliary regression of the residuals on the combined original and transformed regressors. The Null hypothesis is that the linear specification is correct. statsmodels statsmodels.genmod.cov_struct.GlobalOddsRatio.covariance_matrix statsmodels.genmod.cov\_struct.GlobalOddsRatio.covariance\_matrix ================================================================= `GlobalOddsRatio.covariance_matrix(expected_value, index)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/cov_struct.html#GlobalOddsRatio.covariance_matrix) Returns the working covariance or correlation matrix for a given cluster of data. | Parameters: | * **endog\_expval** (*array-like*) – The expected values of endog for the cluster for which the covariance or correlation matrix will be returned * **index** (*integer*) – The index of the cluster for which the covariane or correlation matrix will be returned | | Returns: | * **M** (*matrix*) – The covariance or correlation matrix of endog * **is\_cor** (*bool*) – True if M is a correlation matrix, False if M is a covariance matrix | statsmodels statsmodels.genmod.generalized_linear_model.GLM.loglike statsmodels.genmod.generalized\_linear\_model.GLM.loglike ========================================================= `GLM.loglike(params, scale=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_linear_model.html#GLM.loglike) Evaluate the log-likelihood for a generalized linear model. statsmodels statsmodels.tsa.ar_model.ARResults.t_test statsmodels.tsa.ar\_model.ARResults.t\_test =========================================== `ARResults.t_test(r_matrix, cov_p=None, scale=None, use_t=None)` Compute a t-test for a each linear hypothesis of the form Rb = q | Parameters: | * **r\_matrix** (*array-like**,* *str**,* *tuple*) – + array : If an array is given, a p x k 2d array or length k 1d array specifying the linear restrictions. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q). If q is given, can be either a scalar or a length p row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – An optional `scale` to use. Default is the scale specified by the model fit. * **use\_t** (*bool**,* *optional*) – If use\_t is None, then the default of the model is used. If use\_t is True, then the p-values are based on the t distribution. If use\_t is False, then the p-values are based on the normal distribution. | | Returns: | **res** – The results for the test are attributes of this results instance. The available results have the same elements as the parameter table in `summary()`. | | Return type: | ContrastResults instance | #### Examples ``` >>> import numpy as np >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> r = np.zeros_like(results.params) >>> r[5:] = [1,-1] >>> print(r) [ 0. 0. 0. 0. 0. 1. -1.] ``` r tests that the coefficients on the 5th and 6th independent variable are the same. ``` >>> T_test = results.t_test(r) >>> print(T_test) Test for Constraints ============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------ c0 -1829.2026 455.391 -4.017 0.003 -2859.368 -799.037 ============================================================================== >>> T_test.effect -1829.2025687192481 >>> T_test.sd 455.39079425193762 >>> T_test.tvalue -4.0167754636411717 >>> T_test.pvalue 0.0015163772380899498 ``` Alternatively, you can specify the hypothesis tests using a string ``` >>> from statsmodels.formula.api import ols >>> dta = sm.datasets.longley.load_pandas().data >>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' >>> results = ols(formula, dta).fit() >>> hypotheses = 'GNPDEFL = GNP, UNEMP = 2, YEAR/1829 = 1' >>> t_test = results.t_test(hypotheses) >>> print(t_test) Test for Constraints ============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------ c0 15.0977 84.937 0.178 0.863 -177.042 207.238 c1 -2.0202 0.488 -8.231 0.000 -3.125 -0.915 c2 1.0001 0.249 0.000 1.000 0.437 1.563 ============================================================================== ``` See also [`tvalues`](statsmodels.tsa.ar_model.arresults.tvalues#statsmodels.tsa.ar_model.ARResults.tvalues "statsmodels.tsa.ar_model.ARResults.tvalues") individual t statistics [`f_test`](statsmodels.tsa.ar_model.arresults.f_test#statsmodels.tsa.ar_model.ARResults.f_test "statsmodels.tsa.ar_model.ARResults.f_test") for F tests [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)")
programming_docs
statsmodels statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.untransform_params statsmodels.tsa.regime\_switching.markov\_regression.MarkovRegression.untransform\_params ========================================================================================= `MarkovRegression.untransform_params(constrained)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/regime_switching/markov_regression.html#MarkovRegression.untransform_params) Transform constrained parameters used in likelihood evaluation to unconstrained parameters used by the optimizer | Parameters: | **constrained** (*array\_like*) – Array of constrained parameters used in likelihood evalution, to be transformed. | | Returns: | **unconstrained** – Array of unconstrained parameters used by the optimizer. | | Return type: | array\_like | statsmodels statsmodels.multivariate.factor.Factor.fit statsmodels.multivariate.factor.Factor.fit ========================================== `Factor.fit(maxiter=50, tol=1e-08, start=None, opt_method='BFGS', opt=None, em_iter=3)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/multivariate/factor.html#Factor.fit) Estimate factor model parameters. | Parameters: | * **maxiter** (*int*) – Maximum number of iterations for iterative estimation algorithms * **tol** (*float*) – Stopping critera (error tolerance) for iterative estimation algorithms * **start** (*array-like*) – Starting values, currently only used for ML estimation * **opt\_method** (*string*) – Optimization method for ML estimation * **opt** (*dict-like*) – Keyword arguments passed to optimizer, only used for ML estimation * **em\_iter** (*int*) – The number of EM iterations before starting gradient optimization, only used for ML estimation. | | Returns: | **results** | | Return type: | [FactorResults](statsmodels.multivariate.factor.factorresults#statsmodels.multivariate.factor.FactorResults "statsmodels.multivariate.factor.FactorResults") | statsmodels statsmodels.tsa.statespace.sarimax.SARIMAXResults.seasonalmaparams statsmodels.tsa.statespace.sarimax.SARIMAXResults.seasonalmaparams ================================================================== `SARIMAXResults.seasonalmaparams()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/sarimax.html#SARIMAXResults.seasonalmaparams) (array) Seasonal moving average parameters actually estimated in the model. Does not include nonseasonal moving average parameters (see `maparams`) or parameters whose values are constrained to be zero. statsmodels statsmodels.tsa.arima_model.ARMA.fit statsmodels.tsa.arima\_model.ARMA.fit ===================================== `ARMA.fit(start_params=None, trend='c', method='css-mle', transparams=True, solver='lbfgs', maxiter=500, full_output=1, disp=5, callback=None, start_ar_lags=None, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_model.html#ARMA.fit) Fits ARMA(p,q) model using exact maximum likelihood via Kalman filter. | Parameters: | * **start\_params** (*array-like**,* *optional*) – Starting parameters for ARMA(p,q). If None, the default is given by ARMA.\_fit\_start\_params. See there for more information. * **transparams** (*bool**,* *optional*) – Whehter or not to transform the parameters to ensure stationarity. Uses the transformation suggested in Jones (1980). If False, no checking for stationarity or invertibility is done. * **method** (*str {'css-mle'**,**'mle'**,**'css'}*) – This is the loglikelihood to maximize. If “css-mle”, the conditional sum of squares likelihood is maximized and its values are used as starting values for the computation of the exact likelihood via the Kalman filter. If “mle”, the exact likelihood is maximized via the Kalman Filter. If “css” the conditional sum of squares likelihood is maximized. All three methods use `start_params` as starting parameters. See above for more information. * **trend** (*str {'c'**,**'nc'}*) – Whether to include a constant or not. ‘c’ includes constant, ‘nc’ no constant. * **solver** (*str* *or* *None**,* *optional*) – Solver to be used. The default is ‘lbfgs’ (limited memory Broyden-Fletcher-Goldfarb-Shanno). Other choices are ‘bfgs’, ‘newton’ (Newton-Raphson), ‘nm’ (Nelder-Mead), ‘cg’ - (conjugate gradient), ‘ncg’ (non-conjugate gradient), and ‘powell’. By default, the limited memory BFGS uses m=12 to approximate the Hessian, projected gradient tolerance of 1e-8 and factr = 1e2. You can change these by using kwargs. * **maxiter** (*int**,* *optional*) – The maximum number of function evaluations. Default is 500. * **tol** (*float*) – The convergence tolerance. Default is 1e-08. * **full\_output** (*bool**,* *optional*) – If True, all output from solver will be available in the Results object’s mle\_retvals attribute. Output is dependent on the solver. See Notes for more information. * **disp** (*int**,* *optional*) – If True, convergence information is printed. For the default l\_bfgs\_b solver, disp controls the frequency of the output during the iterations. disp < 0 means no output in this case. * **callback** (*function**,* *optional*) – Called after each iteration as callback(xk) where xk is the current parameter vector. * **start\_ar\_lags** (*int**,* *optional*) – Parameter for fitting start\_params. When fitting start\_params, residuals are obtained from an AR fit, then an ARMA(p,q) model is fit via OLS using these residuals. If start\_ar\_lags is None, fit an AR process according to best BIC. If start\_ar\_lags is not None, fits an AR process with a lag length equal to start\_ar\_lags. See ARMA.\_fit\_start\_params\_hr for more information. * **kwargs** – See Notes for keyword arguments that can be passed to fit. | | Returns: | | | Return type: | statsmodels.tsa.arima\_model.ARMAResults class | See also [`statsmodels.base.model.LikelihoodModel.fit`](http://www.statsmodels.org/stable/dev/generated/statsmodels.base.model.LikelihoodModel.fit.html#statsmodels.base.model.LikelihoodModel.fit "statsmodels.base.model.LikelihoodModel.fit") for more information on using the solvers. [`ARMAResults`](statsmodels.tsa.arima_model.armaresults#statsmodels.tsa.arima_model.ARMAResults "statsmodels.tsa.arima_model.ARMAResults") results class returned by fit #### Notes If fit by ‘mle’, it is assumed for the Kalman Filter that the initial unkown state is zero, and that the inital variance is P = dot(inv(identity(m\*\*2)-kron(T,T)),dot(R,R.T).ravel(‘F’)).reshape(r, r, order = ‘F’) statsmodels statsmodels.tsa.statespace.sarimax.SARIMAX.transform_jacobian statsmodels.tsa.statespace.sarimax.SARIMAX.transform\_jacobian ============================================================== `SARIMAX.transform_jacobian(unconstrained, approx_centered=False)` Jacobian matrix for the parameter transformation function | Parameters: | **unconstrained** (*array\_like*) – Array of unconstrained parameters used by the optimizer. | | Returns: | **jacobian** – Jacobian matrix of the transformation, evaluated at `unconstrained` | | Return type: | array | #### Notes This is a numerical approximation using finite differences. Note that in general complex step methods cannot be used because it is not guaranteed that the `transform_params` method is a real function (e.g. if Cholesky decomposition is used). See also [`transform_params`](statsmodels.tsa.statespace.sarimax.sarimax.transform_params#statsmodels.tsa.statespace.sarimax.SARIMAX.transform_params "statsmodels.tsa.statespace.sarimax.SARIMAX.transform_params") statsmodels statsmodels.sandbox.regression.gmm.IVGMMResults.normalized_cov_params statsmodels.sandbox.regression.gmm.IVGMMResults.normalized\_cov\_params ======================================================================= `IVGMMResults.normalized_cov_params()` statsmodels statsmodels.discrete.discrete_model.MultinomialModel.initialize statsmodels.discrete.discrete\_model.MultinomialModel.initialize ================================================================ `MultinomialModel.initialize()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#MultinomialModel.initialize) Preprocesses the data for MNLogit. statsmodels statsmodels.stats.contingency_tables.Table2x2.independence_probabilities statsmodels.stats.contingency\_tables.Table2x2.independence\_probabilities ========================================================================== `Table2x2.independence_probabilities()` statsmodels statsmodels.genmod.families.family.Family.weights statsmodels.genmod.families.family.Family.weights ================================================= `Family.weights(mu)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/family.html#Family.weights) Weights for IRLS steps | Parameters: | **mu** (*array-like*) – The transformed mean response variable in the exponential family | | Returns: | **w** – The weights for the IRLS steps | | Return type: | array | #### Notes \[w = 1 / (g'(\mu)^2 \* Var(\mu))\] statsmodels statsmodels.tsa.ar_model.ARResults.bse statsmodels.tsa.ar\_model.ARResults.bse ======================================= `ARResults.bse()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/ar_model.html#ARResults.bse) statsmodels statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialResults.summary statsmodels.discrete.count\_model.ZeroInflatedNegativeBinomialResults.summary ============================================================================= `ZeroInflatedNegativeBinomialResults.summary(yname=None, xname=None, title=None, alpha=0.05, yname_list=None)` Summarize the Regression Results | Parameters: | * **yname** (*string**,* *optional*) – Default is `y` * **xname** (*list of strings**,* *optional*) – Default is `var_##` for ## in p the number of regressors * **title** (*string**,* *optional*) – Title for the top table. If not None, then this replaces the default title * **alpha** (*float*) – significance level for the confidence intervals | | Returns: | **smry** – this holds the summary tables and text, which can be printed or converted to various output formats. | | Return type: | Summary instance | See also [`statsmodels.iolib.summary.Summary`](statsmodels.iolib.summary.summary#statsmodels.iolib.summary.Summary "statsmodels.iolib.summary.Summary") class to hold summary results statsmodels statsmodels.stats.proportion.proportions_chisquare statsmodels.stats.proportion.proportions\_chisquare =================================================== `statsmodels.stats.proportion.proportions_chisquare(count, nobs, value=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/proportion.html#proportions_chisquare) test for proportions based on chisquare test | Parameters: | * **count** (*integer* *or* *array\_like*) – the number of successes in nobs trials. If this is array\_like, then the assumption is that this represents the number of successes for each independent sample * **nobs** (*integer*) – the number of trials or observations, with the same length as count. * **value** (*None* *or* *float* *or* *array\_like*) – | | Returns: | * **chi2stat** (*float*) – test statistic for the chisquare test * **p-value** (*float*) – p-value for the chisquare test * *(table, expected)* – table is a (k, 2) contingency table, `expected` is the corresponding table of counts that are expected under independence with given margins | #### Notes Recent version of scipy.stats have a chisquare test for independence in contingency tables. This function provides a similar interface to chisquare tests as `prop.test` in R, however without the option for Yates continuity correction. count can be the count for the number of events for a single proportion, or the counts for several independent proportions. If value is given, then all proportions are jointly tested against this value. If value is not given and count and nobs are not scalar, then the null hypothesis is that all samples have the same proportion. statsmodels statsmodels.tsa.statespace.kalman_filter.KalmanFilter.initialize_approximate_diffuse statsmodels.tsa.statespace.kalman\_filter.KalmanFilter.initialize\_approximate\_diffuse ======================================================================================= `KalmanFilter.initialize_approximate_diffuse(variance=None)` Initialize the statespace model with approximate diffuse values. Rather than following the exact diffuse treatment (which is developed for the case that the variance becomes infinitely large), this assigns an arbitrary large number for the variance. | Parameters: | **variance** (*float**,* *optional*) – The variance for approximating diffuse initial conditions. Default is 1e6. | statsmodels statsmodels.genmod.bayes_mixed_glm.PoissonBayesMixedGLM.predict statsmodels.genmod.bayes\_mixed\_glm.PoissonBayesMixedGLM.predict ================================================================= `PoissonBayesMixedGLM.predict(params, exog=None, *args, **kwargs)` After a model has been fit predict returns the fitted values. This is a placeholder intended to be overwritten by individual models. statsmodels statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.initialize statsmodels.tsa.regime\_switching.markov\_regression.MarkovRegression.initialize ================================================================================ `MarkovRegression.initialize()` Initialize (possibly re-initialize) a Model instance. For instance, the design matrix of a linear model may change and some things must be recomputed. statsmodels statsmodels.stats.power.GofChisquarePower.plot_power statsmodels.stats.power.GofChisquarePower.plot\_power ===================================================== `GofChisquarePower.plot_power(dep_var='nobs', nobs=None, effect_size=None, alpha=0.05, ax=None, title=None, plt_kwds=None, **kwds)` plot power with number of observations or effect size on x-axis | Parameters: | * **dep\_var** (*string in* *[**'nobs'**,* *'effect\_size'**,* *'alpha'**]*) – This specifies which variable is used for the horizontal axis. If dep\_var=’nobs’ (default), then one curve is created for each value of `effect_size`. If dep\_var=’effect\_size’ or alpha, then one curve is created for each value of `nobs`. * **nobs** (*scalar* *or* *array\_like*) – specifies the values of the number of observations in the plot * **effect\_size** (*scalar* *or* *array\_like*) – specifies the values of the effect\_size in the plot * **alpha** (*float* *or* *array\_like*) – The significance level (type I error) used in the power calculation. Can only be more than a scalar, if `dep_var='alpha'` * **ax** (*None* *or* *axis instance*) – If ax is None, than a matplotlib figure is created. If ax is a matplotlib axis instance, then it is reused, and the plot elements are created with it. * **title** (*string*) – title for the axis. Use an empty string, `''`, to avoid a title. * **plt\_kwds** (*None* *or* [dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")) – not used yet * **kwds** (*optional keywords for power function*) – These remaining keyword arguments are used as arguments to the power function. Many power function support `alternative` as a keyword argument, two-sample test support `ratio`. | | Returns: | **fig** | | Return type: | matplotlib figure instance | #### Notes This works only for classes where the `power` method has `effect_size`, `nobs` and `alpha` as the first three arguments. If the second argument is `nobs1`, then the number of observations in the plot are those for the first sample. TODO: fix this for FTestPower and GofChisquarePower TODO: maybe add line variable, if we want more than nobs and effectsize statsmodels statsmodels.tsa.statespace.sarimax.SARIMAX.simulate statsmodels.tsa.statespace.sarimax.SARIMAX.simulate =================================================== `SARIMAX.simulate(params, nsimulations, measurement_shocks=None, state_shocks=None, initial_state=None)` Simulate a new time series following the state space model | Parameters: | * **params** (*array\_like*) – Array of model parameters. * **nsimulations** (*int*) – The number of observations to simulate. If the model is time-invariant this can be any number. If the model is time-varying, then this number must be less than or equal to the number * **measurement\_shocks** (*array\_like**,* *optional*) – If specified, these are the shocks to the measurement equation, \(\varepsilon\_t\). If unspecified, these are automatically generated using a pseudo-random number generator. If specified, must be shaped `nsimulations` x `k_endog`, where `k_endog` is the same as in the state space model. * **state\_shocks** (*array\_like**,* *optional*) – If specified, these are the shocks to the state equation, \(\eta\_t\). If unspecified, these are automatically generated using a pseudo-random number generator. If specified, must be shaped `nsimulations` x `k_posdef` where `k_posdef` is the same as in the state space model. * **initial\_state** (*array\_like**,* *optional*) – If specified, this is the state vector at time zero, which should be shaped (`k_states` x 1), where `k_states` is the same as in the state space model. If unspecified, but the model has been initialized, then that initialization is used. If unspecified and the model has not been initialized, then a vector of zeros is used. Note that this is not included in the returned `simulated_states` array. | | Returns: | **simulated\_obs** – An (nsimulations x k\_endog) array of simulated observations. | | Return type: | array | statsmodels statsmodels.tsa.vector_ar.vecm.VECMResults.tvalues_alpha statsmodels.tsa.vector\_ar.vecm.VECMResults.tvalues\_alpha ========================================================== `VECMResults.tvalues_alpha()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/vecm.html#VECMResults.tvalues_alpha) statsmodels statsmodels.regression.recursive_ls.RecursiveLS.set_conserve_memory statsmodels.regression.recursive\_ls.RecursiveLS.set\_conserve\_memory ====================================================================== `RecursiveLS.set_conserve_memory(conserve_memory=None, **kwargs)` Set the memory conservation method By default, the Kalman filter computes a number of intermediate matrices at each iteration. The memory conservation options control which of those matrices are stored. | Parameters: | * **conserve\_memory** (*integer**,* *optional*) – Bitmask value to set the memory conservation method to. See notes for details. * **\*\*kwargs** – Keyword arguments may be used to influence the memory conservation method by setting individual boolean flags. | #### Notes This method is rarely used. See the corresponding function in the `KalmanFilter` class for details. statsmodels statsmodels.regression.linear_model.OLSResults.tvalues statsmodels.regression.linear\_model.OLSResults.tvalues ======================================================= `OLSResults.tvalues()` Return the t-statistic for a given parameter estimate. statsmodels statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.wald_test statsmodels.discrete.count\_model.ZeroInflatedGeneralizedPoissonResults.wald\_test ================================================================================== `ZeroInflatedGeneralizedPoissonResults.wald_test(r_matrix, cov_p=None, scale=1.0, invcov=None, use_f=None)` Compute a Wald-test for a joint linear hypothesis. | Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) – + array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length p row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – Default is 1.0 for no scaling. * **invcov** (*array-like**,* *optional*) – A q x q array to specify an inverse covariance matrix based on a restrictions matrix. * **use\_f** (*bool*) – If True, then the F-distribution is used. If False, then the asymptotic distribution, chisquare is used. If use\_f is None, then the F distribution is used if the model specifies that use\_t is True. The test statistic is proportionally adjusted for the distribution by the number of constraints in the hypothesis. | | Returns: | **res** – The results for the test are attributes of this results instance. | | Return type: | ContrastResults instance | See also [`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`f_test`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoissonresults.f_test#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.f_test "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.f_test"), [`t_test`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoissonresults.t_test#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.t_test "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") #### Notes The matrix `r_matrix` is assumed to be non-singular. More precisely, r\_matrix (pX pX.T) r\_matrix.T is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full.
programming_docs
statsmodels statsmodels.sandbox.regression.gmm.GMMResults.summary statsmodels.sandbox.regression.gmm.GMMResults.summary ===================================================== `GMMResults.summary(yname=None, xname=None, title=None, alpha=0.05)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#GMMResults.summary) Summarize the Regression Results | Parameters: | * **yname** (*string**,* *optional*) – Default is `y` * **xname** (*list of strings**,* *optional*) – Default is `var_##` for ## in p the number of regressors * **title** (*string**,* *optional*) – Title for the top table. If not None, then this replaces the default title * **alpha** (*float*) – significance level for the confidence intervals | | Returns: | **smry** – this holds the summary tables and text, which can be printed or converted to various output formats. | | Return type: | Summary instance | See also [`statsmodels.iolib.summary.Summary`](statsmodels.iolib.summary.summary#statsmodels.iolib.summary.Summary "statsmodels.iolib.summary.Summary") class to hold summary results statsmodels statsmodels.regression.mixed_linear_model.MixedLMResults.score_obsv statsmodels.regression.mixed\_linear\_model.MixedLMResults.score\_obsv ====================================================================== `MixedLMResults.score_obsv()` cached Jacobian of log-likelihood statsmodels statsmodels.regression.mixed_linear_model.MixedLMResults.tvalues statsmodels.regression.mixed\_linear\_model.MixedLMResults.tvalues ================================================================== `MixedLMResults.tvalues()` Return the t-statistic for a given parameter estimate. statsmodels statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.filter statsmodels.tsa.regime\_switching.markov\_regression.MarkovRegression.filter ============================================================================ `MarkovRegression.filter(params, transformed=True, cov_type=None, cov_kwds=None, return_raw=False, results_class=None, results_wrapper_class=None)` Apply the Hamilton filter | Parameters: | * **params** (*array\_like*) – Array of parameters at which to perform filtering. * **transformed** (*boolean**,* *optional*) – Whether or not `params` is already transformed. Default is True. * **cov\_type** (*str**,* *optional*) – See `fit` for a description of covariance matrix types for results object. * **cov\_kwds** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)") *or* *None**,* *optional*) – See `fit` for a description of required keywords for alternative covariance estimators * **return\_raw** (*boolean**,**optional*) – Whether or not to return only the raw Hamilton filter output or a full results object. Default is to return a full results object. * **results\_class** (*type**,* *optional*) – A results class to instantiate rather than `MarkovSwitchingResults`. Usually only used internally by subclasses. * **results\_wrapper\_class** (*type**,* *optional*) – A results wrapper class to instantiate rather than `MarkovSwitchingResults`. Usually only used internally by subclasses. | | Returns: | | | Return type: | MarkovSwitchingResults | statsmodels statsmodels.sandbox.regression.gmm.GMM.start_weights statsmodels.sandbox.regression.gmm.GMM.start\_weights ===================================================== `GMM.start_weights(inv=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#GMM.start_weights) statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.compare_lr_test statsmodels.sandbox.regression.gmm.IVRegressionResults.compare\_lr\_test ======================================================================== `IVRegressionResults.compare_lr_test(restricted, large_sample=False)` Likelihood ratio test to test whether restricted model is correct | Parameters: | * **restricted** (*Result instance*) – The restricted model is assumed to be nested in the current model. The result instance of the restricted model is required to have two attributes, residual sum of squares, `ssr`, residual degrees of freedom, `df_resid`. * **large\_sample** (*bool*) – Flag indicating whether to use a heteroskedasticity robust version of the LR test, which is a modified LM test. | | Returns: | * **lr\_stat** (*float*) – likelihood ratio, chisquare distributed with df\_diff degrees of freedom * **p\_value** (*float*) – p-value of the test statistic * **df\_diff** (*int*) – degrees of freedom of the restriction, i.e. difference in df between models | #### Notes The exact likelihood ratio is valid for homoskedastic data, and is defined as \[D=-2\log\left(\frac{\mathcal{L}\_{null}} {\mathcal{L}\_{alternative}}\right)\] where \(\mathcal{L}\) is the likelihood of the model. With \(D\) distributed as chisquare with df equal to difference in number of parameters or equivalently difference in residual degrees of freedom. The large sample version of the likelihood ratio is defined as \[D=n s^{\prime}S^{-1}s\] where \(s=n^{-1}\sum\_{i=1}^{n} s\_{i}\) \[s\_{i} = x\_{i,alternative} \epsilon\_{i,null}\] is the average score of the model evaluated using the residuals from null model and the regressors from the alternative model and \(S\) is the covariance of the scores, \(s\_{i}\). The covariance of the scores is estimated using the same estimator as in the alternative model. This test compares the loglikelihood of the two models. This may not be a valid test, if there is unspecified heteroscedasticity or correlation. This method will issue a warning if this is detected but still return the results without taking unspecified heteroscedasticity or correlation into account. This test compares the loglikelihood of the two models. This may not be a valid test, if there is unspecified heteroscedasticity or correlation. This method will issue a warning if this is detected but still return the results without taking unspecified heteroscedasticity or correlation into account. is the average score of the model evaluated using the residuals from null model and the regressors from the alternative model and \(S\) is the covariance of the scores, \(s\_{i}\). The covariance of the scores is estimated using the same estimator as in the alternative model. TODO: put into separate function, needs tests statsmodels statsmodels.miscmodels.tmodel.TLinearModel.predict statsmodels.miscmodels.tmodel.TLinearModel.predict ================================================== `TLinearModel.predict(params, exog=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/miscmodels/tmodel.html#TLinearModel.predict) After a model has been fit predict returns the fitted values. This is a placeholder intended to be overwritten by individual models. statsmodels statsmodels.genmod.cov_struct.Nested statsmodels.genmod.cov\_struct.Nested ===================================== `class statsmodels.genmod.cov_struct.Nested(cov_nearest_method='clipped')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/cov_struct.html#Nested) A nested working dependence structure. A working dependence structure that captures a nested hierarchy of groups, each level of which contributes to the random error term of the model. When using this working covariance structure, `dep_data` of the GEE instance should contain a n\_obs x k matrix of 0/1 indicators, corresponding to the k subgroups nested under the top-level `groups` of the GEE instance. These subgroups should be nested from left to right, so that two observations with the same value for column j of `dep_data` should also have the same value for all columns j’ < j (this only applies to observations in the same top-level cluster given by the `groups` argument to GEE). #### Examples Suppose our data are student test scores, and the students are in classrooms, nested in schools, nested in school districts. The school district is the highest level of grouping, so the school district id would be provided to GEE as `groups`, and the school and classroom id’s would be provided to the Nested class as the `dep_data` argument, e.g. 0 0 # School 0, classroom 0, student 0 0 0 # School 0, classroom 0, student 1 0 1 # School 0, classroom 1, student 0 0 1 # School 0, classroom 1, student 1 1 0 # School 1, classroom 0, student 0 1 0 # School 1, classroom 0, student 1 1 1 # School 1, classroom 1, student 0 1 1 # School 1, classroom 1, student 1 Labels lower in the hierarchy are recycled, so that student 0 in classroom 0 is different fro student 0 in classroom 1, etc. #### Notes The calculations for this dependence structure involve all pairs of observations within a group (that is, within the top level `group` structure passed to GEE). Large group sizes will result in slow iterations. The variance components are estimated using least squares regression of the products r\*r’, for standardized residuals r and r’ in the same group, on a vector of indicators defining which variance components are shared by r and r’. #### Methods | | | | --- | --- | | [`covariance_matrix`](statsmodels.genmod.cov_struct.nested.covariance_matrix#statsmodels.genmod.cov_struct.Nested.covariance_matrix "statsmodels.genmod.cov_struct.Nested.covariance_matrix")(expval, index) | Returns the working covariance or correlation matrix for a given cluster of data. | | [`covariance_matrix_solve`](statsmodels.genmod.cov_struct.nested.covariance_matrix_solve#statsmodels.genmod.cov_struct.Nested.covariance_matrix_solve "statsmodels.genmod.cov_struct.Nested.covariance_matrix_solve")(expval, index, …) | Solves matrix equations of the form `covmat * soln = rhs` and returns the values of `soln`, where `covmat` is the covariance matrix represented by this class. | | [`initialize`](statsmodels.genmod.cov_struct.nested.initialize#statsmodels.genmod.cov_struct.Nested.initialize "statsmodels.genmod.cov_struct.Nested.initialize")(model) | Called on the first call to update | | [`summary`](statsmodels.genmod.cov_struct.nested.summary#statsmodels.genmod.cov_struct.Nested.summary "statsmodels.genmod.cov_struct.Nested.summary")() | Returns a summary string describing the state of the dependence structure. | | [`update`](statsmodels.genmod.cov_struct.nested.update#statsmodels.genmod.cov_struct.Nested.update "statsmodels.genmod.cov_struct.Nested.update")(params) | Updates the association parameter values based on the current regression coefficients. | statsmodels statsmodels.sandbox.regression.gmm.GMMResults.calc_cov_params statsmodels.sandbox.regression.gmm.GMMResults.calc\_cov\_params =============================================================== `GMMResults.calc_cov_params(moms, gradmoms, weights=None, use_weights=False, has_optimal_weights=True, weights_method='cov', wargs=())` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#GMMResults.calc_cov_params) calculate covariance of parameter estimates not all options tried out yet If weights matrix is given, then the formula use to calculate cov\_params depends on whether has\_optimal\_weights is true. If no weights are given, then the weight matrix is calculated with the given method, and has\_optimal\_weights is assumed to be true. (API Note: The latter assumption could be changed if we allow for has\_optimal\_weights=None.) statsmodels statsmodels.tsa.statespace.mlemodel.MLEModel.filter statsmodels.tsa.statespace.mlemodel.MLEModel.filter =================================================== `MLEModel.filter(params, transformed=True, complex_step=False, cov_type=None, cov_kwds=None, return_ssm=False, results_class=None, results_wrapper_class=None, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEModel.filter) Kalman filtering | Parameters: | * **params** (*array\_like*) – Array of parameters at which to evaluate the loglikelihood function. * **transformed** (*boolean**,* *optional*) – Whether or not `params` is already transformed. Default is True. * **return\_ssm** (*boolean**,**optional*) – Whether or not to return only the state space output or a full results object. Default is to return a full results object. * **cov\_type** (*str**,* *optional*) – See `MLEResults.fit` for a description of covariance matrix types for results object. * **cov\_kwds** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)") *or* *None**,* *optional*) – See `MLEResults.get_robustcov_results` for a description required keywords for alternative covariance estimators * **\*\*kwargs** – Additional keyword arguments to pass to the Kalman filter. See `KalmanFilter.filter` for more details. | statsmodels statsmodels.discrete.discrete_model.CountModel.loglike statsmodels.discrete.discrete\_model.CountModel.loglike ======================================================= `CountModel.loglike(params)` Log-likelihood of model. statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.untransform_params statsmodels.tsa.statespace.dynamic\_factor.DynamicFactor.untransform\_params ============================================================================ `DynamicFactor.untransform_params(constrained)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/dynamic_factor.html#DynamicFactor.untransform_params) Transform constrained parameters used in likelihood evaluation to unconstrained parameters used by the optimizer. | Parameters: | **constrained** (*array\_like*) – Array of constrained parameters used in likelihood evalution, to be transformed. | | Returns: | **unconstrained** – Array of unconstrained parameters used by the optimizer. | | Return type: | array\_like | statsmodels statsmodels.miscmodels.count.PoissonOffsetGMLE.score_obs statsmodels.miscmodels.count.PoissonOffsetGMLE.score\_obs ========================================================= `PoissonOffsetGMLE.score_obs(params, **kwds)` Jacobian/Gradient of log-likelihood evaluated at params for each observation. statsmodels statsmodels.genmod.families.family.NegativeBinomial.deviance statsmodels.genmod.families.family.NegativeBinomial.deviance ============================================================ `NegativeBinomial.deviance(endog, mu, var_weights=1.0, freq_weights=1.0, scale=1.0)` The deviance function evaluated at (endog, mu, var\_weights, freq\_weights, scale) for the distribution. Deviance is usually defined as twice the loglikelihood ratio. | Parameters: | * **endog** (*array-like*) – The endogenous response variable * **mu** (*array-like*) – The inverse of the link function at the linear predicted values. * **var\_weights** (*array-like*) – 1d array of variance (analytic) weights. The default is 1. * **freq\_weights** (*array-like*) – 1d array of frequency weights. The default is 1. * **scale** (*float**,* *optional*) – An optional scale argument. The default is 1. | | Returns: | **Deviance** – The value of deviance function defined below. | | Return type: | array | #### Notes Deviance is defined \[D = 2\sum\_i (freq\\_weights\_i \* var\\_weights \* (llf(endog\_i, endog\_i) - llf(endog\_i, \mu\_i)))\] where y is the endogenous variable. The deviance functions are analytically defined for each family. Internally, we calculate deviance as: \[D = \sum\_i freq\\_weights\_i \* var\\_weights \* resid\\_dev\_i / scale\] statsmodels statsmodels.tsa.arima_process.lpol_sdiff statsmodels.tsa.arima\_process.lpol\_sdiff ========================================== `statsmodels.tsa.arima_process.lpol_sdiff(s)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_process.html#lpol_sdiff) return coefficients for seasonal difference (1-L^s) just a trivial convenience function | Parameters: | **s** (*int*) – number of periods in season | | Returns: | **sdiff** | | Return type: | list, length s+1 | statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.info_criteria statsmodels.tsa.statespace.dynamic\_factor.DynamicFactorResults.info\_criteria ============================================================================== `DynamicFactorResults.info_criteria(criteria, method='standard')` Information criteria | Parameters: | * **criteria** (*{'aic'**,* *'bic'**,* *'hqic'}*) – The information criteria to compute. * **method** (*{'standard'**,* *'lutkepohl'}*) – The method for information criteria computation. Default is ‘standard’ method; ‘lutkepohl’ computes the information criteria as in Lütkepohl (2007). See Notes for formulas. | #### Notes The `‘standard’` formulas are: \[\begin{split}AIC & = -2 \log L(Y\_n | \hat \psi) + 2 k \\ BIC & = -2 \log L(Y\_n | \hat \psi) + k \log n \\ HQIC & = -2 \log L(Y\_n | \hat \psi) + 2 k \log \log n \\\end{split}\] where \(\hat \psi\) are the maximum likelihood estimates of the parameters, \(n\) is the number of observations, and `k` is the number of estimated parameters. Note that the `‘standard’` formulas are returned from the `aic`, `bic`, and `hqic` results attributes. The `‘lutkepohl’` formuals are (Lütkepohl, 2010): \[\begin{split}AIC\_L & = \log | Q | + \frac{2 k}{n} \\ BIC\_L & = \log | Q | + \frac{k \log n}{n} \\ HQIC\_L & = \log | Q | + \frac{2 k \log \log n}{n} \\\end{split}\] where \(Q\) is the state covariance matrix. Note that the Lütkepohl definitions do not apply to all state space models, and should be used with care outside of SARIMAX and VARMAX models. #### References | | | | --- | --- | | [\*] | Lütkepohl, Helmut. 2007. *New Introduction to Multiple Time* *Series Analysis.* Berlin: Springer. | statsmodels statsmodels.duration.hazard_regression.PHReg.hessian statsmodels.duration.hazard\_regression.PHReg.hessian ===================================================== `PHReg.hessian(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/duration/hazard_regression.html#PHReg.hessian) Returns the Hessian matrix of the log partial likelihood function evaluated at `params`. statsmodels statsmodels.genmod.bayes_mixed_glm.BinomialBayesMixedGLM.vb_elbo_base statsmodels.genmod.bayes\_mixed\_glm.BinomialBayesMixedGLM.vb\_elbo\_base ========================================================================= `BinomialBayesMixedGLM.vb_elbo_base(h, tm, fep_mean, vcp_mean, vc_mean, fep_sd, vcp_sd, vc_sd)` Returns the evidence lower bound (ELBO) for the model. This function calculates the family-specific ELBO function based on information provided from a subclass. | Parameters: | **h** (*function mapping 1d vector to 1d vector*) – The contribution of the model to the ELBO function can be expressed as y\_i\*lp\_i + Eh\_i(z), where y\_i and lp\_i are the response and linear predictor for observation i, and z is a standard normal rangom variable. This formulation can be achieved for any GLM with a canonical link function. | statsmodels statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression.initialize statsmodels.tsa.regime\_switching.markov\_autoregression.MarkovAutoregression.initialize ======================================================================================== `MarkovAutoregression.initialize()` Initialize (possibly re-initialize) a Model instance. For instance, the design matrix of a linear model may change and some things must be recomputed. statsmodels statsmodels.discrete.discrete_model.ProbitResults.initialize statsmodels.discrete.discrete\_model.ProbitResults.initialize ============================================================= `ProbitResults.initialize(model, params, **kwd)` statsmodels statsmodels.multivariate.factor.Factor.score statsmodels.multivariate.factor.Factor.score ============================================ `Factor.score(par)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/multivariate/factor.html#Factor.score) Evaluate the score function (first derivative of loglike). | Parameters: | **par** (*ndarray* *or* *tuple of 2 ndarray's*) – The model parameters, either a packed representation of the model parameters or a 2-tuple containing a `k_endog x n_factor` matrix of factor loadings and a `k_endog` vector of uniquenesses. | | Returns: | **score** | | Return type: | ndarray |
programming_docs
statsmodels statsmodels.genmod.generalized_estimating_equations.GEE.mean_deriv statsmodels.genmod.generalized\_estimating\_equations.GEE.mean\_deriv ===================================================================== `GEE.mean_deriv(exog, lin_pred)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_estimating_equations.html#GEE.mean_deriv) Derivative of the expected endog with respect to the parameters. | Parameters: | * **exog** (*array-like*) – The exogeneous data at which the derivative is computed. * **lin\_pred** (*array-like*) – The values of the linear predictor. | | Returns: | * *The value of the derivative of the expected endog with respect* * *to the parameter vector.* | #### Notes If there is an offset or exposure, it should be added to `lin_pred` prior to calling this function. statsmodels statsmodels.tsa.varma_process.VarmaPoly.getisstationary statsmodels.tsa.varma\_process.VarmaPoly.getisstationary ======================================================== `VarmaPoly.getisstationary(a=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/varma_process.html#VarmaPoly.getisstationary) check whether the auto-regressive lag-polynomial is stationary | Returns: | * **isstationary** (*boolean*) * *\*attaches\** * **areigenvalues** (*complex array*) – eigenvalues sorted by absolute value | #### References formula taken from NAG manual statsmodels statsmodels.regression.mixed_linear_model.MixedLM.get_scale statsmodels.regression.mixed\_linear\_model.MixedLM.get\_scale ============================================================== `MixedLM.get_scale(fe_params, cov_re, vcomp)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/mixed_linear_model.html#MixedLM.get_scale) Returns the estimated error variance based on given estimates of the slopes and random effects covariance matrix. | Parameters: | * **fe\_params** (*array-like*) – The regression slope estimates * **cov\_re** (*2d array-like*) – Estimate of the random effects covariance matrix * **vcomp** (*array-like*) – Estimate of the variance components | | Returns: | **scale** – The estimated error variance. | | Return type: | float | statsmodels statsmodels.stats.multitest.NullDistribution.pdf statsmodels.stats.multitest.NullDistribution.pdf ================================================ `NullDistribution.pdf(zscores)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/multitest.html#NullDistribution.pdf) Evaluates the fitted emirical null Z-score density. | Parameters: | **zscores** (*scalar* *or* *array-like*) – The point or points at which the density is to be evaluated. | | Returns: | * *The empirical null Z-score density evaluated at the given* * *points.* | statsmodels statsmodels.sandbox.regression.gmm.GMMResults statsmodels.sandbox.regression.gmm.GMMResults ============================================= `class statsmodels.sandbox.regression.gmm.GMMResults(*args, **kwds)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#GMMResults) just a storage class right now #### Methods | | | | --- | --- | | [`bse`](statsmodels.sandbox.regression.gmm.gmmresults.bse#statsmodels.sandbox.regression.gmm.GMMResults.bse "statsmodels.sandbox.regression.gmm.GMMResults.bse")() | | | [`calc_cov_params`](statsmodels.sandbox.regression.gmm.gmmresults.calc_cov_params#statsmodels.sandbox.regression.gmm.GMMResults.calc_cov_params "statsmodels.sandbox.regression.gmm.GMMResults.calc_cov_params")(moms, gradmoms[, weights, …]) | calculate covariance of parameter estimates | | [`compare_j`](statsmodels.sandbox.regression.gmm.gmmresults.compare_j#statsmodels.sandbox.regression.gmm.GMMResults.compare_j "statsmodels.sandbox.regression.gmm.GMMResults.compare_j")(other) | overidentification test for comparing two nested gmm estimates | | [`conf_int`](statsmodels.sandbox.regression.gmm.gmmresults.conf_int#statsmodels.sandbox.regression.gmm.GMMResults.conf_int "statsmodels.sandbox.regression.gmm.GMMResults.conf_int")([alpha, cols, method]) | Returns the confidence interval of the fitted parameters. | | [`cov_params`](statsmodels.sandbox.regression.gmm.gmmresults.cov_params#statsmodels.sandbox.regression.gmm.GMMResults.cov_params "statsmodels.sandbox.regression.gmm.GMMResults.cov_params")([r\_matrix, column, scale, cov\_p, …]) | Returns the variance/covariance matrix. | | [`f_test`](statsmodels.sandbox.regression.gmm.gmmresults.f_test#statsmodels.sandbox.regression.gmm.GMMResults.f_test "statsmodels.sandbox.regression.gmm.GMMResults.f_test")(r\_matrix[, cov\_p, scale, invcov]) | Compute the F-test for a joint linear hypothesis. | | [`get_bse`](statsmodels.sandbox.regression.gmm.gmmresults.get_bse#statsmodels.sandbox.regression.gmm.GMMResults.get_bse "statsmodels.sandbox.regression.gmm.GMMResults.get_bse")(\*\*kwds) | standard error of the parameter estimates with options | | [`initialize`](statsmodels.sandbox.regression.gmm.gmmresults.initialize#statsmodels.sandbox.regression.gmm.GMMResults.initialize "statsmodels.sandbox.regression.gmm.GMMResults.initialize")(model, params, \*\*kwd) | | | [`jtest`](statsmodels.sandbox.regression.gmm.gmmresults.jtest#statsmodels.sandbox.regression.gmm.GMMResults.jtest "statsmodels.sandbox.regression.gmm.GMMResults.jtest")() | overidentification test | | [`jval`](statsmodels.sandbox.regression.gmm.gmmresults.jval#statsmodels.sandbox.regression.gmm.GMMResults.jval "statsmodels.sandbox.regression.gmm.GMMResults.jval")() | | | [`llf`](statsmodels.sandbox.regression.gmm.gmmresults.llf#statsmodels.sandbox.regression.gmm.GMMResults.llf "statsmodels.sandbox.regression.gmm.GMMResults.llf")() | | | [`load`](statsmodels.sandbox.regression.gmm.gmmresults.load#statsmodels.sandbox.regression.gmm.GMMResults.load "statsmodels.sandbox.regression.gmm.GMMResults.load")(fname) | load a pickle, (class method) | | [`normalized_cov_params`](statsmodels.sandbox.regression.gmm.gmmresults.normalized_cov_params#statsmodels.sandbox.regression.gmm.GMMResults.normalized_cov_params "statsmodels.sandbox.regression.gmm.GMMResults.normalized_cov_params")() | | | [`predict`](statsmodels.sandbox.regression.gmm.gmmresults.predict#statsmodels.sandbox.regression.gmm.GMMResults.predict "statsmodels.sandbox.regression.gmm.GMMResults.predict")([exog, transform]) | Call self.model.predict with self.params as the first argument. | | [`pvalues`](statsmodels.sandbox.regression.gmm.gmmresults.pvalues#statsmodels.sandbox.regression.gmm.GMMResults.pvalues "statsmodels.sandbox.regression.gmm.GMMResults.pvalues")() | | | [`q`](statsmodels.sandbox.regression.gmm.gmmresults.q#statsmodels.sandbox.regression.gmm.GMMResults.q "statsmodels.sandbox.regression.gmm.GMMResults.q")() | | | [`remove_data`](statsmodels.sandbox.regression.gmm.gmmresults.remove_data#statsmodels.sandbox.regression.gmm.GMMResults.remove_data "statsmodels.sandbox.regression.gmm.GMMResults.remove_data")() | remove data arrays, all nobs arrays from result and model | | [`save`](statsmodels.sandbox.regression.gmm.gmmresults.save#statsmodels.sandbox.regression.gmm.GMMResults.save "statsmodels.sandbox.regression.gmm.GMMResults.save")(fname[, remove\_data]) | save a pickle of this instance | | [`summary`](statsmodels.sandbox.regression.gmm.gmmresults.summary#statsmodels.sandbox.regression.gmm.GMMResults.summary "statsmodels.sandbox.regression.gmm.GMMResults.summary")([yname, xname, title, alpha]) | Summarize the Regression Results | | [`t_test`](statsmodels.sandbox.regression.gmm.gmmresults.t_test#statsmodels.sandbox.regression.gmm.GMMResults.t_test "statsmodels.sandbox.regression.gmm.GMMResults.t_test")(r\_matrix[, cov\_p, scale, use\_t]) | Compute a t-test for a each linear hypothesis of the form Rb = q | | [`t_test_pairwise`](statsmodels.sandbox.regression.gmm.gmmresults.t_test_pairwise#statsmodels.sandbox.regression.gmm.GMMResults.t_test_pairwise "statsmodels.sandbox.regression.gmm.GMMResults.t_test_pairwise")(term\_name[, method, alpha, …]) | perform pairwise t\_test with multiple testing corrected p-values | | [`tvalues`](statsmodels.sandbox.regression.gmm.gmmresults.tvalues#statsmodels.sandbox.regression.gmm.GMMResults.tvalues "statsmodels.sandbox.regression.gmm.GMMResults.tvalues")() | Return the t-statistic for a given parameter estimate. | | [`wald_test`](statsmodels.sandbox.regression.gmm.gmmresults.wald_test#statsmodels.sandbox.regression.gmm.GMMResults.wald_test "statsmodels.sandbox.regression.gmm.GMMResults.wald_test")(r\_matrix[, cov\_p, scale, invcov, …]) | Compute a Wald-test for a joint linear hypothesis. | | [`wald_test_terms`](statsmodels.sandbox.regression.gmm.gmmresults.wald_test_terms#statsmodels.sandbox.regression.gmm.GMMResults.wald_test_terms "statsmodels.sandbox.regression.gmm.GMMResults.wald_test_terms")([skip\_single, …]) | Compute a sequence of Wald tests for terms over multiple columns | #### Attributes | | | | --- | --- | | `bse_` | standard error of the parameter estimates | | `use_t` | | statsmodels statsmodels.regression.linear_model.OLS statsmodels.regression.linear\_model.OLS ======================================== `class statsmodels.regression.linear_model.OLS(endog, exog=None, missing='none', hasconst=None, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#OLS) A simple ordinary least squares model. | Parameters: | * **endog** (*array-like*) – 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 `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. | `weights` *scalar* – Has an attribute weights = array(1.0) due to inheritance from WLS. See also [`GLS`](statsmodels.regression.linear_model.gls#statsmodels.regression.linear_model.GLS "statsmodels.regression.linear_model.GLS") #### Examples ``` >>> import numpy as np >>> >>> import statsmodels.api as sm >>> >>> Y = [1,3,4,5,2,3,4] >>> X = range(1,8) >>> X = sm.add_constant(X) >>> >>> model = sm.OLS(Y,X) >>> results = model.fit() >>> results.params array([ 2.14285714, 0.25 ]) >>> results.tvalues array([ 1.87867287, 0.98019606]) >>> print(results.t_test([1, 0])) <T test: effect=array([ 2.14285714]), sd=array([[ 1.14062282]]), t=array([[ 1.87867287]]), p=array([[ 0.05953974]]), df_denom=5> >>> print(results.f_test(np.identity(2))) <F test: F=array([[ 19.46078431]]), p=[[ 0.00437251]], df_denom=5, df_num=2> ``` #### Notes No constant is added by the model unless you are using formulas. #### Methods | | | | --- | --- | | [`fit`](statsmodels.regression.linear_model.ols.fit#statsmodels.regression.linear_model.OLS.fit "statsmodels.regression.linear_model.OLS.fit")([method, cov\_type, cov\_kwds, use\_t]) | Full fit of the model. | | [`fit_regularized`](statsmodels.regression.linear_model.ols.fit_regularized#statsmodels.regression.linear_model.OLS.fit_regularized "statsmodels.regression.linear_model.OLS.fit_regularized")([method, alpha, L1\_wt, …]) | Return a regularized fit to a linear regression model. | | [`from_formula`](statsmodels.regression.linear_model.ols.from_formula#statsmodels.regression.linear_model.OLS.from_formula "statsmodels.regression.linear_model.OLS.from_formula")(formula, data[, subset, drop\_cols]) | Create a Model from a formula and dataframe. | | [`get_distribution`](statsmodels.regression.linear_model.ols.get_distribution#statsmodels.regression.linear_model.OLS.get_distribution "statsmodels.regression.linear_model.OLS.get_distribution")(params, scale[, exog, …]) | Returns a random number generator for the predictive distribution. | | [`hessian`](statsmodels.regression.linear_model.ols.hessian#statsmodels.regression.linear_model.OLS.hessian "statsmodels.regression.linear_model.OLS.hessian")(params[, scale]) | Evaluate the Hessian function at a given point. | | [`hessian_factor`](statsmodels.regression.linear_model.ols.hessian_factor#statsmodels.regression.linear_model.OLS.hessian_factor "statsmodels.regression.linear_model.OLS.hessian_factor")(params[, scale, observed]) | Weights for calculating Hessian | | [`information`](statsmodels.regression.linear_model.ols.information#statsmodels.regression.linear_model.OLS.information "statsmodels.regression.linear_model.OLS.information")(params) | Fisher information matrix of model | | [`initialize`](statsmodels.regression.linear_model.ols.initialize#statsmodels.regression.linear_model.OLS.initialize "statsmodels.regression.linear_model.OLS.initialize")() | Initialize (possibly re-initialize) a Model instance. | | [`loglike`](statsmodels.regression.linear_model.ols.loglike#statsmodels.regression.linear_model.OLS.loglike "statsmodels.regression.linear_model.OLS.loglike")(params[, scale]) | The likelihood function for the OLS model. | | [`predict`](statsmodels.regression.linear_model.ols.predict#statsmodels.regression.linear_model.OLS.predict "statsmodels.regression.linear_model.OLS.predict")(params[, exog]) | Return linear predicted values from a design matrix. | | [`score`](statsmodels.regression.linear_model.ols.score#statsmodels.regression.linear_model.OLS.score "statsmodels.regression.linear_model.OLS.score")(params[, scale]) | Evaluate the score function at a given point. | | [`whiten`](statsmodels.regression.linear_model.ols.whiten#statsmodels.regression.linear_model.OLS.whiten "statsmodels.regression.linear_model.OLS.whiten")(Y) | OLS model whitener does nothing: returns Y. | #### Attributes | | | | --- | --- | | `df_model` | The model degree of freedom, defined as the rank of the regressor matrix minus 1 if a constant is included. | | `df_resid` | The residual degree of freedom, defined as the number of observations minus the rank of the regressor matrix. | | `endog_names` | Names of endogenous variables | | `exog_names` | Names of exogenous variables | statsmodels statsmodels.regression.linear_model.OLSResults.summary2 statsmodels.regression.linear\_model.OLSResults.summary2 ======================================================== `OLSResults.summary2(yname=None, xname=None, title=None, alpha=0.05, float_format='%.4f')` Experimental summary function to summarize the regression results | Parameters: | * **xname** (*List of strings of length equal to the number of parameters*) – Names of the independent variables (optional) * **yname** (*string*) – Name of the dependent variable (optional) * **title** (*string**,* *optional*) – Title for the top table. If not None, then this replaces the default title * **alpha** (*float*) – significance level for the confidence intervals * **float\_format** (*string*) – print format for floats in parameters summary | | Returns: | **smry** – this holds the summary tables and text, which can be printed or converted to various output formats. | | Return type: | Summary instance | See also [`statsmodels.iolib.summary.Summary`](statsmodels.iolib.summary.summary#statsmodels.iolib.summary.Summary "statsmodels.iolib.summary.Summary") class to hold summary results statsmodels statsmodels.discrete.discrete_model.MNLogit.score_obs statsmodels.discrete.discrete\_model.MNLogit.score\_obs ======================================================= `MNLogit.score_obs(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#MNLogit.score_obs) Jacobian matrix for multinomial logit model log-likelihood | Parameters: | **params** (*array*) – The parameters of the multinomial logit model. | | Returns: | **jac** – The derivative of the loglikelihood for each observation evaluated at `params` . | | Return type: | array-like | #### Notes \[\frac{\partial\ln L\_{i}}{\partial\beta\_{j}}=\left(d\_{ij}-\frac{\exp\left(\beta\_{j}^{\prime}x\_{i}\right)}{\sum\_{k=0}^{J}\exp\left(\beta\_{k}^{\prime}x\_{i}\right)}\right)x\_{i}\] for \(j=1,...,J\), for observations \(i=1,...,n\) In the multinomial model the score vector is K x (J-1) but is returned as a flattened array. The Jacobian has the observations in rows and the flatteded array of derivatives in columns. statsmodels statsmodels.robust.robust_linear_model.RLM.loglike statsmodels.robust.robust\_linear\_model.RLM.loglike ==================================================== `RLM.loglike(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/robust_linear_model.html#RLM.loglike) Log-likelihood of model. statsmodels statsmodels.tsa.arima_model.ARIMAResults.load statsmodels.tsa.arima\_model.ARIMAResults.load ============================================== `classmethod ARIMAResults.load(fname)` load a pickle, (class method) | Parameters: | **fname** (*string* *or* *filehandle*) – fname can be a string to a file path or filename, or a filehandle. | | Returns: | | | Return type: | unpickled instance | statsmodels statsmodels.stats.contingency_tables.SquareTable.test_nominal_association statsmodels.stats.contingency\_tables.SquareTable.test\_nominal\_association ============================================================================ `SquareTable.test_nominal_association()` Assess independence for nominal factors. Assessment of independence between rows and columns using chi^2 testing. The rows and columns are treated as nominal (unordered) categorical variables. | Returns: | * *A bunch containing the following attributes* * **statistic** (*float*) – The chi^2 test statistic. * **df** (*integer*) – The degrees of freedom of the reference distribution * **pvalue** (*float*) – The p-value for the test. | statsmodels statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression.predict statsmodels.tsa.regime\_switching.markov\_autoregression.MarkovAutoregression.predict ===================================================================================== `MarkovAutoregression.predict(params, start=None, end=None, probabilities=None, conditional=False)` In-sample prediction and out-of-sample forecasting | Parameters: | * **params** (*array*) – Parameters at which to form predictions * **start** (*int**,* *str**, or* *datetime**,* *optional*) – Zero-indexed observation number at which to start forecasting, i.e., the first forecast is start. Can also be a date string to parse or a datetime type. Default is the the zeroth observation. * **end** (*int**,* *str**, or* *datetime**,* *optional*) – Zero-indexed observation number at which to end forecasting, i.e., the last forecast is end. Can also be a date string to parse or a datetime type. However, if the dates index does not have a fixed frequency, end must be an integer index if you want out of sample prediction. Default is the last observation in the sample. * **probabilities** (*string* *or* *array\_like**,* *optional*) – Specifies the weighting probabilities used in constructing the prediction as a weighted average. If a string, can be ‘predicted’, ‘filtered’, or ‘smoothed’. Otherwise can be an array of probabilities to use. Default is smoothed. * **conditional** (*boolean* *or* *int**,* *optional*) – Whether or not to return predictions conditional on current or past regimes. If False, returns a single vector of weighted predictions. If True or 1, returns predictions conditional on the current regime. For larger integers, returns predictions conditional on the current regime and some number of past regimes. | | Returns: | **predict** – Array of out of in-sample predictions and / or out-of-sample forecasts. | | Return type: | array |
programming_docs
statsmodels statsmodels.regression.recursive_ls.RecursiveLS.observed_information_matrix statsmodels.regression.recursive\_ls.RecursiveLS.observed\_information\_matrix ============================================================================== `RecursiveLS.observed_information_matrix(params, transformed=True, approx_complex_step=None, approx_centered=False, **kwargs)` Observed information matrix | Parameters: | * **params** (*array\_like**,* *optional*) – Array of parameters at which to evaluate the loglikelihood function. * **\*\*kwargs** – Additional keyword arguments to pass to the Kalman filter. See `KalmanFilter.filter` for more details. | #### Notes This method is from Harvey (1989), which shows that the information matrix only depends on terms from the gradient. This implementation is partially analytic and partially numeric approximation, therefore, because it uses the analytic formula for the information matrix, with numerically computed elements of the gradient. #### References Harvey, Andrew C. 1990. Forecasting, Structural Time Series Models and the Kalman Filter. Cambridge University Press. statsmodels statsmodels.discrete.discrete_model.MultinomialModel.from_formula statsmodels.discrete.discrete\_model.MultinomialModel.from\_formula =================================================================== `classmethod MultinomialModel.from_formula(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** (*extra arguments*) – These are passed to the model * **kwargs** (*extra keyword arguments*) – These are passed to the model with one exception. The `eval_env` keyword is passed to patsy. It can be either a [`patsy.EvalEnvironment`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.EvalEnvironment "(in patsy v0.5.0+dev)") 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** | | Return type: | 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 statsmodels.miscmodels.count.PoissonOffsetGMLE.fit statsmodels.miscmodels.count.PoissonOffsetGMLE.fit ================================================== `PoissonOffsetGMLE.fit(start_params=None, method='nm', maxiter=500, full_output=1, disp=1, callback=None, retall=0, **kwargs)` Fit the model using maximum likelihood. The rest of the docstring is from statsmodels.LikelihoodModel.fit statsmodels statsmodels.discrete.discrete_model.LogitResults.llnull statsmodels.discrete.discrete\_model.LogitResults.llnull ======================================================== `LogitResults.llnull()` statsmodels statsmodels.regression.recursive_ls.RecursiveLS.fit statsmodels.regression.recursive\_ls.RecursiveLS.fit ==================================================== `RecursiveLS.fit()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/recursive_ls.html#RecursiveLS.fit) Fits the model by application of the Kalman filter | Returns: | | | Return type: | [RecursiveLSResults](statsmodels.regression.recursive_ls.recursivelsresults#statsmodels.regression.recursive_ls.RecursiveLSResults "statsmodels.regression.recursive_ls.RecursiveLSResults") | statsmodels statsmodels.sandbox.regression.gmm.IVGMMResults.pvalues statsmodels.sandbox.regression.gmm.IVGMMResults.pvalues ======================================================= `IVGMMResults.pvalues()` statsmodels statsmodels.stats.outliers_influence.OLSInfluence.dfbetas statsmodels.stats.outliers\_influence.OLSInfluence.dfbetas ========================================================== `OLSInfluence.dfbetas()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/outliers_influence.html#OLSInfluence.dfbetas) (cached attribute) dfbetas uses results from leave-one-observation-out loop statsmodels statsmodels.regression.quantile_regression.QuantRegResults.rsquared_adj statsmodels.regression.quantile\_regression.QuantRegResults.rsquared\_adj ========================================================================= `QuantRegResults.rsquared_adj()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/quantile_regression.html#QuantRegResults.rsquared_adj) statsmodels statsmodels.tsa.statespace.kalman_smoother.SmootherResults.predict statsmodels.tsa.statespace.kalman\_smoother.SmootherResults.predict =================================================================== `SmootherResults.predict(start=None, end=None, dynamic=None, **kwargs)` In-sample and out-of-sample prediction for state space models generally | Parameters: | * **start** (*int**,* *optional*) – Zero-indexed observation number at which to start forecasting, i.e., the first forecast will be at start. * **end** (*int**,* *optional*) – Zero-indexed observation number at which to end forecasting, i.e., the last forecast will be at end. * **dynamic** (*int**,* *optional*) – Offset relative to `start` at which to begin dynamic prediction. Prior to this observation, true endogenous values will be used for prediction; starting with this observation and continuing through the end of prediction, forecasted endogenous values will be used instead. * **\*\*kwargs** – If the prediction range is outside of the sample range, any of the state space representation matrices that are time-varying must have updated values provided for the out-of-sample range. For example, of `obs_intercept` is a time-varying component and the prediction range extends 10 periods beyond the end of the sample, a (`k_endog` x 10) matrix must be provided with the new intercept values. | | Returns: | **results** – A PredictionResults object. | | Return type: | [kalman\_filter.PredictionResults](statsmodels.tsa.statespace.kalman_filter.predictionresults#statsmodels.tsa.statespace.kalman_filter.PredictionResults "statsmodels.tsa.statespace.kalman_filter.PredictionResults") | #### Notes All prediction is performed by applying the deterministic part of the measurement equation using the predicted state variables. Out-of-sample prediction first applies the Kalman filter to missing data for the number of periods desired to obtain the predicted states. statsmodels statsmodels.genmod.bayes_mixed_glm.PoissonBayesMixedGLM.fit_vb statsmodels.genmod.bayes\_mixed\_glm.PoissonBayesMixedGLM.fit\_vb ================================================================= `PoissonBayesMixedGLM.fit_vb(mean=None, sd=None, fit_method='BFGS', minim_opts=None, verbose=False)` Fit a model using the variational Bayes mean field approximation. | Parameters: | * **mean** (*array-like*) – Starting value for VB mean vector * **sd** (*array-like*) – Starting value for VB standard deviation vector * **fit\_method** (*string*) – Algorithm for scipy.minimize * **minim\_opts** (*dict-like*) – Options passed to scipy.minimize * **verbose** (*bool*) – If True, print the gradient norm to the screen each time it is calculated. | #### Notes The goal is to find a factored Gaussian approximation q1\*q2\*… to the posterior distribution, approximately minimizing the KL divergence from the factored approximation to the actual posterior. The KL divergence, or ELBO function has the form E\* log p(y, fe, vcp, vc) - E\* log q where E\* is expectation with respect to the product of qj. #### References Blei, Kucukelbir, McAuliffe (2017). Variational Inference: A review for Statisticians <https://arxiv.org/pdf/1601.00670.pdf> statsmodels statsmodels.regression.recursive_ls.RecursiveLS.opg_information_matrix statsmodels.regression.recursive\_ls.RecursiveLS.opg\_information\_matrix ========================================================================= `RecursiveLS.opg_information_matrix(params, transformed=True, approx_complex_step=None, **kwargs)` Outer product of gradients information matrix | Parameters: | * **params** (*array\_like**,* *optional*) – Array of parameters at which to evaluate the loglikelihood function. * **\*\*kwargs** – Additional arguments to the `loglikeobs` method. | #### References Berndt, Ernst R., Bronwyn Hall, Robert Hall, and Jerry Hausman. 1974. Estimation and Inference in Nonlinear Structural Models. NBER Chapters. National Bureau of Economic Research, Inc. statsmodels statsmodels.robust.scale.mad statsmodels.robust.scale.mad ============================ `statsmodels.robust.scale.mad(a, c=0.6744897501960817, axis=0, center=<function median>)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/scale.html#mad) The Median Absolute Deviation along given axis of an array | Parameters: | * **a** (*array-like*) – Input array. * **c** (*float**,* *optional*) – The normalization constant. Defined as scipy.stats.norm.ppf(3/4.), which is approximately .6745. * **axis** (*int**,* *optional*) – The defaul is 0. Can also be None. * **center** (*callable* *or* *float*) – If a callable is provided, such as the default `np.median` then it is expected to be called center(a). The axis argument will be applied via np.apply\_over\_axes. Otherwise, provide a float. | | Returns: | **mad** – `mad` = median(abs(`a` - center))/`c` | | Return type: | float | statsmodels statsmodels.sandbox.distributions.extras.SkewNorm_gen.interval statsmodels.sandbox.distributions.extras.SkewNorm\_gen.interval =============================================================== `SkewNorm_gen.interval(alpha, *args, **kwds)` Confidence interval with equal areas around the median. | Parameters: | * **alpha** (*array\_like of float*) – Probability that an rv will be drawn from the returned range. Each value should be in the range [0, 1]. * **arg2****,** **..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information). * **loc** (*array\_like**,* *optional*) – location parameter, Default is 0. * **scale** (*array\_like**,* *optional*) – scale parameter, Default is 1. | | Returns: | **a, b** – end-points of range that contain `100 * alpha %` of the rv’s possible values. | | Return type: | ndarray of float | statsmodels statsmodels.regression.recursive_ls.RecursiveLS.initialize_statespace statsmodels.regression.recursive\_ls.RecursiveLS.initialize\_statespace ======================================================================= `RecursiveLS.initialize_statespace(**kwargs)` Initialize the state space representation | Parameters: | **\*\*kwargs** – Additional keyword arguments to pass to the state space class constructor. | statsmodels statsmodels.tsa.statespace.sarimax.SARIMAX.observed_information_matrix statsmodels.tsa.statespace.sarimax.SARIMAX.observed\_information\_matrix ======================================================================== `SARIMAX.observed_information_matrix(params, transformed=True, approx_complex_step=None, approx_centered=False, **kwargs)` Observed information matrix | Parameters: | * **params** (*array\_like**,* *optional*) – Array of parameters at which to evaluate the loglikelihood function. * **\*\*kwargs** – Additional keyword arguments to pass to the Kalman filter. See `KalmanFilter.filter` for more details. | #### Notes This method is from Harvey (1989), which shows that the information matrix only depends on terms from the gradient. This implementation is partially analytic and partially numeric approximation, therefore, because it uses the analytic formula for the information matrix, with numerically computed elements of the gradient. #### References Harvey, Andrew C. 1990. Forecasting, Structural Time Series Models and the Kalman Filter. Cambridge University Press. statsmodels statsmodels.tsa.arima_process.ArmaProcess.invertroots statsmodels.tsa.arima\_process.ArmaProcess.invertroots ====================================================== `ArmaProcess.invertroots(retnew=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_process.html#ArmaProcess.invertroots) Make MA polynomial invertible by inverting roots inside unit circle | Parameters: | **retnew** (*boolean*) – If False (default), then return the lag-polynomial as array. If True, then return a new instance with invertible MA-polynomial | | Returns: | * **manew** (*array*) – new invertible MA lag-polynomial, returned if retnew is false. * **wasinvertible** (*boolean*) – True if the MA lag-polynomial was already invertible, returned if retnew is false. * **armaprocess** (*new instance of class*) – If retnew is true, then return a new instance with invertible MA-polynomial | statsmodels statsmodels.miscmodels.count.PoissonGMLE.loglike statsmodels.miscmodels.count.PoissonGMLE.loglike ================================================ `PoissonGMLE.loglike(params)` Log-likelihood of model. statsmodels statsmodels.tsa.arima_model.ARIMAResults.resid statsmodels.tsa.arima\_model.ARIMAResults.resid =============================================== `ARIMAResults.resid()` statsmodels statsmodels.regression.recursive_ls.RecursiveLS.impulse_responses statsmodels.regression.recursive\_ls.RecursiveLS.impulse\_responses =================================================================== `RecursiveLS.impulse_responses(params, steps=1, impulse=0, orthogonalized=False, cumulative=False, **kwargs)` Impulse response function | Parameters: | * **params** (*array\_like*) – Array of model parameters. * **steps** (*int**,* *optional*) – The number of steps for which impulse responses are calculated. Default is 1. Note that the initial impulse is not counted as a step, so if `steps=1`, the output will have 2 entries. * **impulse** (*int* *or* *array\_like*) – If an integer, the state innovation to pulse; must be between 0 and `k_posdef-1`. Alternatively, a custom impulse vector may be provided; must be shaped `k_posdef x 1`. * **orthogonalized** (*boolean**,* *optional*) – Whether or not to perform impulse using orthogonalized innovations. Note that this will also affect custum `impulse` vectors. Default is False. * **cumulative** (*boolean**,* *optional*) – Whether or not to return cumulative impulse responses. Default is False. * **\*\*kwargs** – If the model is time-varying and `steps` is greater than the number of observations, any of the state space representation matrices that are time-varying must have updated values provided for the out-of-sample steps. For example, if `design` is a time-varying component, `nobs` is 10, and `steps` is 15, a (`k_endog` x `k_states` x 5) matrix must be provided with the new design matrix values. | | Returns: | **impulse\_responses** – Responses for each endogenous variable due to the impulse given by the `impulse` argument. A (steps + 1 x k\_endog) array. | | Return type: | array | #### Notes Intercepts in the measurement and state equation are ignored when calculating impulse responses. statsmodels statsmodels.miscmodels.count.PoissonGMLE.reduceparams statsmodels.miscmodels.count.PoissonGMLE.reduceparams ===================================================== `PoissonGMLE.reduceparams(params)` statsmodels statsmodels.robust.norms.AndrewWave.psi_deriv statsmodels.robust.norms.AndrewWave.psi\_deriv ============================================== `AndrewWave.psi_deriv(z)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/norms.html#AndrewWave.psi_deriv) The derivative of Andrew’s wave psi function #### Notes Used to estimate the robust covariance matrix. statsmodels statsmodels.tsa.ar_model.ARResults.bic statsmodels.tsa.ar\_model.ARResults.bic ======================================= `ARResults.bic()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/ar_model.html#ARResults.bic) statsmodels statsmodels.tsa.statespace.varmax.VARMAXResults.resid statsmodels.tsa.statespace.varmax.VARMAXResults.resid ===================================================== `VARMAXResults.resid()` (array) The model residuals. An (nobs x k\_endog) array. statsmodels statsmodels.tsa.statespace.mlemodel.MLEModel.fit statsmodels.tsa.statespace.mlemodel.MLEModel.fit ================================================ `MLEModel.fit(start_params=None, transformed=True, cov_type='opg', cov_kwds=None, method='lbfgs', maxiter=50, full_output=1, disp=5, callback=None, return_params=False, optim_score=None, optim_complex_step=None, optim_hessian=None, flags=None, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEModel.fit) Fits the model by maximum likelihood via Kalman filter. | Parameters: | * **start\_params** (*array\_like**,* *optional*) – Initial guess of the solution for the loglikelihood maximization. If None, the default is given by Model.start\_params. * **transformed** (*boolean**,* *optional*) – Whether or not `start_params` is already transformed. Default is True. * **cov\_type** (*str**,* *optional*) – The `cov_type` keyword governs the method for calculating the covariance matrix of parameter estimates. Can be one of: + ’opg’ for the outer product of gradient estimator + ’oim’ for the observed information matrix estimator, calculated using the method of Harvey (1989) + ’approx’ for the observed information matrix estimator, calculated using a numerical approximation of the Hessian matrix. + ’robust’ for an approximate (quasi-maximum likelihood) covariance matrix that may be valid even in the presense of some misspecifications. Intermediate calculations use the ‘oim’ method. + ’robust\_approx’ is the same as ‘robust’ except that the intermediate calculations use the ‘approx’ method. + ’none’ for no covariance matrix calculation. * **cov\_kwds** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)") *or* *None**,* *optional*) – A dictionary of arguments affecting covariance matrix computation. **opg, oim, approx, robust, robust\_approx** + ’approx\_complex\_step’ : boolean, optional - If True, numerical approximations are computed using complex-step methods. If False, numerical approximations are computed using finite difference methods. Default is True. + ’approx\_centered’ : boolean, optional - If True, numerical approximations computed using finite difference methods use a centered approximation. Default is False. * **method** (*str**,* *optional*) – The `method` determines which solver from `scipy.optimize` is used, and it can be chosen from among the following strings: + ’newton’ for Newton-Raphson, ‘nm’ for Nelder-Mead + ’bfgs’ for Broyden-Fletcher-Goldfarb-Shanno (BFGS) + ’lbfgs’ for limited-memory BFGS with optional box constraints + ’powell’ for modified Powell’s method + ’cg’ for conjugate gradient + ’ncg’ for Newton-conjugate gradient + ’basinhopping’ for global basin-hopping solverThe explicit arguments in `fit` are passed to the solver, with the exception of the basin-hopping solver. Each solver has several optional arguments that are not the same across solvers. See the notes section below (or scipy.optimize) for the available arguments and for the list of explicit arguments that the basin-hopping solver supports. * **maxiter** (*int**,* *optional*) – The maximum number of iterations to perform. * **full\_output** (*boolean**,* *optional*) – Set to True to have all available output in the Results object’s mle\_retvals attribute. The output is dependent on the solver. See LikelihoodModelResults notes section for more information. * **disp** (*boolean**,* *optional*) – Set to True to print convergence messages. * **callback** (*callable callback**(**xk**)**,* *optional*) – Called after each iteration, as callback(xk), where xk is the current parameter vector. * **return\_params** (*boolean**,* *optional*) – Whether or not to return only the array of maximizing parameters. Default is False. * **optim\_score** (*{'harvey'**,* *'approx'}* *or* *None**,* *optional*) – The method by which the score vector is calculated. ‘harvey’ uses the method from Harvey (1989), ‘approx’ uses either finite difference or complex step differentiation depending upon the value of `optim_complex_step`, and None uses the built-in gradient approximation of the optimizer. Default is None. This keyword is only relevant if the optimization method uses the score. * **optim\_complex\_step** (*bool**,* *optional*) – Whether or not to use complex step differentiation when approximating the score; if False, finite difference approximation is used. Default is True. This keyword is only relevant if `optim_score` is set to ‘harvey’ or ‘approx’. * **optim\_hessian** (*{'opg'**,**'oim'**,**'approx'}**,* *optional*) – The method by which the Hessian is numerically approximated. ‘opg’ uses outer product of gradients, ‘oim’ uses the information matrix formula from Harvey (1989), and ‘approx’ uses numerical approximation. This keyword is only relevant if the optimization method uses the Hessian matrix. * **\*\*kwargs** – Additional keyword arguments to pass to the optimizer. | | Returns: | | | Return type: | [MLEResults](statsmodels.tsa.statespace.mlemodel.mleresults#statsmodels.tsa.statespace.mlemodel.MLEResults "statsmodels.tsa.statespace.mlemodel.MLEResults") | See also [`statsmodels.base.model.LikelihoodModel.fit`](http://www.statsmodels.org/stable/dev/generated/statsmodels.base.model.LikelihoodModel.fit.html#statsmodels.base.model.LikelihoodModel.fit "statsmodels.base.model.LikelihoodModel.fit"), [`MLEResults`](statsmodels.tsa.statespace.mlemodel.mleresults#statsmodels.tsa.statespace.mlemodel.MLEResults "statsmodels.tsa.statespace.mlemodel.MLEResults")
programming_docs
statsmodels statsmodels.discrete.discrete_model.CountModel.fit statsmodels.discrete.discrete\_model.CountModel.fit =================================================== `CountModel.fit(start_params=None, method='newton', maxiter=35, full_output=1, disp=1, callback=None, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#CountModel.fit) Fit the model using maximum likelihood. The rest of the docstring is from statsmodels.base.model.LikelihoodModel.fit Fit method for likelihood based models | Parameters: | * **start\_params** (*array-like**,* *optional*) – Initial guess of the solution for the loglikelihood maximization. The default is an array of zeros. * **method** (*str**,* *optional*) – The `method` determines which solver from `scipy.optimize` is used, and it can be chosen from among the following strings: + ’newton’ for Newton-Raphson, ‘nm’ for Nelder-Mead + ’bfgs’ for Broyden-Fletcher-Goldfarb-Shanno (BFGS) + ’lbfgs’ for limited-memory BFGS with optional box constraints + ’powell’ for modified Powell’s method + ’cg’ for conjugate gradient + ’ncg’ for Newton-conjugate gradient + ’basinhopping’ for global basin-hopping solver + ’minimize’ for generic wrapper of scipy minimize (BFGS by default)The explicit arguments in `fit` are passed to the solver, with the exception of the basin-hopping solver. Each solver has several optional arguments that are not the same across solvers. See the notes section below (or scipy.optimize) for the available arguments and for the list of explicit arguments that the basin-hopping solver supports. * **maxiter** (*int**,* *optional*) – The maximum number of iterations to perform. * **full\_output** (*bool**,* *optional*) – Set to True to have all available output in the Results object’s mle\_retvals attribute. The output is dependent on the solver. See LikelihoodModelResults notes section for more information. * **disp** (*bool**,* *optional*) – Set to True to print convergence messages. * **fargs** (*tuple**,* *optional*) – Extra arguments passed to the likelihood function, i.e., loglike(x,\*args) * **callback** (*callable callback**(**xk**)**,* *optional*) – Called after each iteration, as callback(xk), where xk is the current parameter vector. * **retall** (*bool**,* *optional*) – Set to True to return list of solutions at each iteration. Available in Results object’s mle\_retvals attribute. * **skip\_hessian** (*bool**,* *optional*) – If False (default), then the negative inverse hessian is calculated after the optimization. If True, then the hessian will not be calculated. However, it will be available in methods that use the hessian in the optimization (currently only with `“newton”`). * **kwargs** (*keywords*) – All kwargs are passed to the chosen solver with one exception. The following keyword controls what happens after the fit: ``` warn_convergence : bool, optional If True, checks the model for the converged flag. If the converged flag is False, a ConvergenceWarning is issued. ``` | #### Notes The ‘basinhopping’ solver ignores `maxiter`, `retall`, `full_output` explicit arguments. Optional arguments for solvers (see returned Results.mle\_settings): ``` 'newton' tol : float Relative error in params acceptable for convergence. 'nm' -- Nelder Mead xtol : float Relative error in params acceptable for convergence ftol : float Relative error in loglike(params) acceptable for convergence maxfun : int Maximum number of function evaluations to make. 'bfgs' gtol : float Stop when norm of gradient is less than gtol. norm : float Order of norm (np.Inf is max, -np.Inf is min) epsilon If fprime is approximated, use this value for the step size. Only relevant if LikelihoodModel.score is None. 'lbfgs' m : int This many terms are used for the Hessian approximation. factr : float A stop condition that is a variant of relative error. pgtol : float A stop condition that uses the projected gradient. epsilon If fprime is approximated, use this value for the step size. Only relevant if LikelihoodModel.score is None. maxfun : int Maximum number of function evaluations to make. bounds : sequence (min, max) pairs for each element in x, defining the bounds on that parameter. Use None for one of min or max when there is no bound in that direction. 'cg' gtol : float Stop when norm of gradient is less than gtol. norm : float Order of norm (np.Inf is max, -np.Inf is min) epsilon : float If fprime is approximated, use this value for the step size. Can be scalar or vector. Only relevant if Likelihoodmodel.score is None. 'ncg' fhess_p : callable f'(x,*args) Function which computes the Hessian of f times an arbitrary vector, p. Should only be supplied if LikelihoodModel.hessian is None. avextol : float Stop when the average relative error in the minimizer falls below this amount. epsilon : float or ndarray If fhess is approximated, use this value for the step size. Only relevant if Likelihoodmodel.hessian is None. 'powell' xtol : float Line-search error tolerance ftol : float Relative error in loglike(params) for acceptable for convergence. maxfun : int Maximum number of function evaluations to make. start_direc : ndarray Initial direction set. 'basinhopping' niter : integer The number of basin hopping iterations. niter_success : integer Stop the run if the global minimum candidate remains the same for this number of iterations. T : float The "temperature" parameter for the accept or reject criterion. Higher "temperatures" mean that larger jumps in function value will be accepted. For best results `T` should be comparable to the separation (in function value) between local minima. stepsize : float Initial step size for use in the random displacement. interval : integer The interval for how often to update the `stepsize`. minimizer : dict Extra keyword arguments to be passed to the minimizer `scipy.optimize.minimize()`, for example 'method' - the minimization method (e.g. 'L-BFGS-B'), or 'tol' - the tolerance for termination. Other arguments are mapped from explicit argument of `fit`: - `args` <- `fargs` - `jac` <- `score` - `hess` <- `hess` 'minimize' min_method : str, optional Name of minimization method to use. Any method specific arguments can be passed directly. For a list of methods and their arguments, see documentation of `scipy.optimize.minimize`. If no method is specified, then BFGS is used. ``` statsmodels statsmodels.tsa.arima_model.ARMAResults.predict statsmodels.tsa.arima\_model.ARMAResults.predict ================================================ `ARMAResults.predict(start=None, end=None, exog=None, dynamic=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_model.html#ARMAResults.predict) ARMA model in-sample and out-of-sample prediction | Parameters: | * **start** (*int**,* *str**, or* *datetime*) – Zero-indexed observation number at which to start forecasting, ie., the first forecast is start. Can also be a date string to parse or a datetime type. * **end** (*int**,* *str**, or* *datetime*) – Zero-indexed observation number at which to end forecasting, ie., the first forecast is start. Can also be a date string to parse or a datetime type. However, if the dates index does not have a fixed frequency, end must be an integer index if you want out of sample prediction. * **exog** (*array-like**,* *optional*) – If the model is an ARMAX and out-of-sample forecasting is requested, exog must be given. Note that you’ll need to pass `k_ar` additional lags for any exogenous variables. E.g., if you fit an ARMAX(2, q) model and want to predict 5 steps, you need 7 observations to do this. * **dynamic** (*bool**,* *optional*) – The `dynamic` keyword affects in-sample prediction. If dynamic is False, then the in-sample lagged values are used for prediction. If `dynamic` is True, then in-sample forecasts are used in place of lagged dependent variables. The first forecasted value is `start`. | | Returns: | **predict** – The predicted values. | | Return type: | array | #### Notes It is recommended to use dates with the time-series models, as the below will probably make clear. However, if ARIMA is used without dates and/or `start` and `end` are given as indices, then these indices are in terms of the *original*, undifferenced series. Ie., given some undifferenced observations: ``` 1970Q1, 1 1970Q2, 1.5 1970Q3, 1.25 1970Q4, 2.25 1971Q1, 1.2 1971Q2, 4.1 ``` 1970Q1 is observation 0 in the original series. However, if we fit an ARIMA(p,1,q) model then we lose this first observation through differencing. Therefore, the first observation we can forecast (if using exact MLE) is index 1. In the differenced series this is index 0, but we refer to it as 1 from the original series. statsmodels statsmodels.tools.eval_measures.meanabs statsmodels.tools.eval\_measures.meanabs ======================================== `statsmodels.tools.eval_measures.meanabs(x1, x2, axis=0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tools/eval_measures.html#meanabs) mean absolute error | Parameters: | * **x2** (*x1**,*) – The performance measure depends on the difference between these two arrays. * **axis** (*int*) – axis along which the summary statistic is calculated | | Returns: | **meanabs** – mean absolute difference along given axis. | | Return type: | ndarray or float | #### Notes If `x1` and `x2` have different shapes, then they need to broadcast. This uses `numpy.asanyarray` to convert the input. Whether this is the desired result or not depends on the array subclass. statsmodels statsmodels.tsa.statespace.varmax.VARMAX.initialize_known statsmodels.tsa.statespace.varmax.VARMAX.initialize\_known ========================================================== `VARMAX.initialize_known(initial_state, initial_state_cov)` statsmodels statsmodels.tsa.tsatools.lagmat2ds statsmodels.tsa.tsatools.lagmat2ds ================================== `statsmodels.tsa.tsatools.lagmat2ds(x, maxlag0, maxlagex=None, dropex=0, trim='forward', use_pandas=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/tsatools.html#lagmat2ds) Generate lagmatrix for 2d array, columns arranged by variables | Parameters: | * **x** (*array\_like**,* *2d*) – 2d data, observation in rows and variables in columns * **maxlag0** (*int*) – for first variable all lags from zero to maxlag are included * **maxlagex** (*None* *or* *int*) – max lag for all other variables all lags from zero to maxlag are included * **dropex** (*int* *(**default is 0**)*) – exclude first dropex lags from other variables for all variables, except the first, lags from dropex to maxlagex are included * **trim** (*string*) – + ‘forward’ : trim invalid observations in front + ’backward’ : trim invalid initial observations + ’both’ : trim invalid observations on both sides + ’none’ : no trimming of observations * **use\_pandas** (*bool**,* *optional*) – If true, returns a DataFrame when the input is a pandas Series or DataFrame. If false, return numpy ndarrays. | | Returns: | **lagmat** – array with lagged observations, columns ordered by variable | | Return type: | 2d array | #### Notes Inefficient implementation for unequal lags, implemented for convenience statsmodels statsmodels.sandbox.regression.gmm.GMM.gradient_momcond statsmodels.sandbox.regression.gmm.GMM.gradient\_momcond ======================================================== `GMM.gradient_momcond(params, epsilon=0.0001, centered=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#GMM.gradient_momcond) gradient of moment conditions | Parameters: | * **params** (*ndarray*) – parameter at which the moment conditions are evaluated * **epsilon** (*float*) – stepsize for finite difference calculation * **centered** (*bool*) – This refers to the finite difference calculation. If `centered` is true, then the centered finite difference calculation is used. Otherwise the one-sided forward differences are used. * **TODO** (*looks like not used yet*) – missing argument `weights` | statsmodels statsmodels.tsa.statespace.structural.UnobservedComponentsResults.test_normality statsmodels.tsa.statespace.structural.UnobservedComponentsResults.test\_normality ================================================================================= `UnobservedComponentsResults.test_normality(method)` Test for normality of standardized residuals. Null hypothesis is normality. | Parameters: | **method** (*string {'jarquebera'}* *or* *None*) – The statistical test for normality. Must be ‘jarquebera’ for Jarque-Bera normality test. If None, an attempt is made to select an appropriate test. | #### Notes If the first `d` loglikelihood values were burned (i.e. in the specified model, `loglikelihood_burn=d`), then this test is calculated ignoring the first `d` residuals. In the case of missing data, the maintained hypothesis is that the data are missing completely at random. This test is then run on the standardized residuals excluding those corresponding to missing observations. See also [`statsmodels.stats.stattools.jarque_bera`](statsmodels.stats.stattools.jarque_bera#statsmodels.stats.stattools.jarque_bera "statsmodels.stats.stattools.jarque_bera") statsmodels statsmodels.regression.linear_model.GLSAR.from_formula statsmodels.regression.linear\_model.GLSAR.from\_formula ======================================================== `classmethod GLSAR.from_formula(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** (*extra arguments*) – These are passed to the model * **kwargs** (*extra keyword arguments*) – These are passed to the model with one exception. The `eval_env` keyword is passed to patsy. It can be either a [`patsy.EvalEnvironment`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.EvalEnvironment "(in patsy v0.5.0+dev)") 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** | | Return type: | 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 statsmodels.discrete.discrete_model.MultinomialResults.wald_test_terms statsmodels.discrete.discrete\_model.MultinomialResults.wald\_test\_terms ========================================================================= `MultinomialResults.wald_test_terms(skip_single=False, extra_constraints=None, combine_terms=None)` Compute a sequence of Wald tests for terms over multiple columns This computes joined Wald tests for the hypothesis that all coefficients corresponding to a `term` are zero. `Terms` are defined by the underlying formula or by string matching. | Parameters: | * **skip\_single** (*boolean*) – If true, then terms that consist only of a single column and, therefore, refers only to a single parameter is skipped. If false, then all terms are included. * **extra\_constraints** (*ndarray*) – not tested yet * **combine\_terms** (*None* *or* *list of strings*) – Each string in this list is matched to the name of the terms or the name of the exogenous variables. All columns whose name includes that string are combined in one joint test. | | Returns: | **test\_result** – The result instance contains `table` which is a pandas DataFrame with the test results: test statistic, degrees of freedom and pvalues. | | Return type: | result instance | #### Examples ``` >>> res_ols = ols("np.log(Days+1) ~ C(Duration, Sum)*C(Weight, Sum)", data).fit() >>> res_ols.wald_test_terms() <class 'statsmodels.stats.contrast.WaldTestResults'> F P>F df constraint df denom Intercept 279.754525 2.37985521351e-22 1 51 C(Duration, Sum) 5.367071 0.0245738436636 1 51 C(Weight, Sum) 12.432445 3.99943118767e-05 2 51 C(Duration, Sum):C(Weight, Sum) 0.176002 0.83912310946 2 51 ``` ``` >>> res_poi = Poisson.from_formula("Days ~ C(Weight) * C(Duration)", data).fit(cov_type='HC0') >>> wt = res_poi.wald_test_terms(skip_single=False, combine_terms=['Duration', 'Weight']) >>> print(wt) chi2 P>chi2 df constraint Intercept 15.695625 7.43960374424e-05 1 C(Weight) 16.132616 0.000313940174705 2 C(Duration) 1.009147 0.315107378931 1 C(Weight):C(Duration) 0.216694 0.897315972824 2 Duration 11.187849 0.010752286833 3 Weight 30.263368 4.32586407145e-06 4 ``` statsmodels statsmodels.stats.contingency_tables.Table2x2.standardized_resids statsmodels.stats.contingency\_tables.Table2x2.standardized\_resids =================================================================== `Table2x2.standardized_resids()` statsmodels statsmodels.tsa.interp.denton.dentonm statsmodels.tsa.interp.denton.dentonm ===================================== `statsmodels.tsa.interp.denton.dentonm(indicator, benchmark, freq='aq', **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/interp/denton.html#dentonm) Modified Denton’s method to convert low-frequency to high-frequency data. Uses proportionate first-differences as the penalty function. See notes. | Parameters: | * **indicator** – A low-frequency indicator series. It is assumed that there are no pre-sample indicators. Ie., the first indicators line up with the first benchmark. * **benchmark** (*array-like*) – The higher frequency benchmark. A 1d or 2d data series in columns. If 2d, then M series are assumed. * **freq** (*str {"aq"**,**"qm"**,* *"other"}*) – “aq” - Benchmarking an annual series to quarterly. “mq” - Benchmarking a quarterly series to monthly. “other” - Custom stride. A kwarg, k, must be supplied. * **kwargs** – `k : int` The number of high-frequency observations that sum to make an aggregate low-frequency observation. `k` is used with `freq` == “other”. | | Returns: | **benchmarked series** | | Return type: | array | #### Examples ``` >>> indicator = [50,100,150,100] * 5 >>> benchmark = [500,400,300,400,500] >>> benchmarked = dentonm(indicator, benchmark, freq="aq") ``` #### Notes Denton’s method minimizes the distance given by the penalty function, in a least squares sense, between the unknown benchmarked series and the indicator series subject to the condition that the sum of the benchmarked series is equal to the benchmark. The modification allows that the first value not be pre-determined as is the case with Denton’s original method. If the there is no benchmark provided for the last few indicator observations, then extrapolation is performed using the last benchmark-indicator ratio of the previous period. Minimizes sum((X[t]/I[t] - X[t-1]/I[t-1])\*\*2) s.t. sum(X) = A, for each period. Where X is the benchmarked series, I is the indicator, and A is the benchmark. #### References Bloem, A.M, Dippelsman, R.J. and Maehle, N.O. 2001 Quarterly National Accounts Manual–Concepts, Data Sources, and Compilation. IMF. <http://www.imf.org/external/pubs/ft/qna/2000/Textbook/index.htm> Cholette, P. 1988. “Benchmarking systems of socio-economic time series.” Statistics Canada, Time Series Research and Analysis Division, Working Paper No TSRA-88-017E. Denton, F.T. 1971. “Adjustment of monthly or quarterly series to annual totals: an approach based on quadratic minimization.” Journal of the American Statistical Association. 99-102.
programming_docs
statsmodels statsmodels.sandbox.tsa.fftarma.ArmaFft.spd statsmodels.sandbox.tsa.fftarma.ArmaFft.spd =========================================== `ArmaFft.spd(npos)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/tsa/fftarma.html#ArmaFft.spd) raw spectral density, returns Fourier transform n is number of points in positive spectrum, the actual number of points is twice as large. different from other spd methods with fft statsmodels statsmodels.tsa.holtwinters.Holt.information statsmodels.tsa.holtwinters.Holt.information ============================================ `Holt.information(params)` Fisher information matrix of model Returns -Hessian of loglike evaluated at params. statsmodels statsmodels.tsa.statespace.mlemodel.MLEModel.set_conserve_memory statsmodels.tsa.statespace.mlemodel.MLEModel.set\_conserve\_memory ================================================================== `MLEModel.set_conserve_memory(conserve_memory=None, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEModel.set_conserve_memory) Set the memory conservation method By default, the Kalman filter computes a number of intermediate matrices at each iteration. The memory conservation options control which of those matrices are stored. | Parameters: | * **conserve\_memory** (*integer**,* *optional*) – Bitmask value to set the memory conservation method to. See notes for details. * **\*\*kwargs** – Keyword arguments may be used to influence the memory conservation method by setting individual boolean flags. | #### Notes This method is rarely used. See the corresponding function in the `KalmanFilter` class for details. statsmodels statsmodels.discrete.discrete_model.BinaryResults.summary statsmodels.discrete.discrete\_model.BinaryResults.summary ========================================================== `BinaryResults.summary(yname=None, xname=None, title=None, alpha=0.05, yname_list=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#BinaryResults.summary) Summarize the Regression Results | Parameters: | * **yname** (*string**,* *optional*) – Default is `y` * **xname** (*list of strings**,* *optional*) – Default is `var_##` for ## in p the number of regressors * **title** (*string**,* *optional*) – Title for the top table. If not None, then this replaces the default title * **alpha** (*float*) – significance level for the confidence intervals | | Returns: | **smry** – this holds the summary tables and text, which can be printed or converted to various output formats. | | Return type: | Summary instance | See also [`statsmodels.iolib.summary.Summary`](statsmodels.iolib.summary.summary#statsmodels.iolib.summary.Summary "statsmodels.iolib.summary.Summary") class to hold summary results statsmodels statsmodels.duration.hazard_regression.PHRegResults.pvalues statsmodels.duration.hazard\_regression.PHRegResults.pvalues ============================================================ `PHRegResults.pvalues()` statsmodels statsmodels.tsa.kalmanf.kalmanfilter.KalmanFilter.loglike statsmodels.tsa.kalmanf.kalmanfilter.KalmanFilter.loglike ========================================================= `classmethod KalmanFilter.loglike(params, arma_model, set_sigma2=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/kalmanf/kalmanfilter.html#KalmanFilter.loglike) The loglikelihood for an ARMA model using the Kalman Filter recursions. | Parameters: | * **params** (*array*) – The coefficients of the ARMA model, assumed to be in the order of trend variables and `k` exogenous coefficients, the `p` AR coefficients, then the `q` MA coefficients. * **arma\_model** (`statsmodels.tsa.arima.ARMA` instance) – A reference to the ARMA model instance. * **set\_sigma2** (*bool**,* *optional*) – True if arma\_model.sigma2 should be set. Note that sigma2 will be computed in any case, but it will be discarded if set\_sigma2 is False. | #### Notes This works for both real valued and complex valued parameters. The complex values being used to compute the numerical derivative. If available will use a Cython version of the Kalman Filter. statsmodels statsmodels.discrete.count_model.ZeroInflatedPoissonResults.save statsmodels.discrete.count\_model.ZeroInflatedPoissonResults.save ================================================================= `ZeroInflatedPoissonResults.save(fname, remove_data=False)` save a pickle of this instance | Parameters: | * **fname** (*string* *or* *filehandle*) – fname can be a string to a file path or filename, or a filehandle. * **remove\_data** (*bool*) – If False (default), then the instance is pickled without changes. If True, then all arrays with length nobs are set to None before pickling. See the remove\_data method. In some cases not all arrays will be set to None. | #### Notes If remove\_data is true and the model result does not implement a remove\_data method then this will raise an exception. statsmodels statsmodels.sandbox.distributions.transformed.Transf_gen.expect statsmodels.sandbox.distributions.transformed.Transf\_gen.expect ================================================================ `Transf_gen.expect(func=None, args=(), loc=0, scale=1, lb=None, ub=None, conditional=False, **kwds)` Calculate expected value of a function with respect to the distribution. The expected value of a function `f(x)` with respect to a distribution `dist` is defined as: ``` ubound E[x] = Integral(f(x) * dist.pdf(x)) lbound ``` | Parameters: | * **func** (*callable**,* *optional*) – Function for which integral is calculated. Takes only one argument. The default is the identity mapping f(x) = x. * **args** (*tuple**,* *optional*) – Shape parameters of the distribution. * **loc** (*float**,* *optional*) – Location parameter (default=0). * **scale** (*float**,* *optional*) – Scale parameter (default=1). * **ub** (*lb**,*) – Lower and upper bound for integration. Default is set to the support of the distribution. * **conditional** (*bool**,* *optional*) – If True, the integral is corrected by the conditional probability of the integration interval. The return value is the expectation of the function, conditional on being in the given interval. Default is False. * **keyword arguments are passed to the integration routine.** (*Additional*) – | | Returns: | **expect** – The calculated expected value. | | Return type: | float | #### Notes The integration behavior of this function is inherited from `integrate.quad`. statsmodels statsmodels.stats.mediation.Mediation.fit statsmodels.stats.mediation.Mediation.fit ========================================= `Mediation.fit(method='parametric', n_rep=1000)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/mediation.html#Mediation.fit) Fit a regression model to assess mediation. | Parameters: | * **method** (*string*) – Either ‘parametric’ or ‘bootstrap’. * **n\_rep** (*integer*) – The number of simulation replications. * **a MediationResults object.** (*Returns*) – | statsmodels statsmodels.tsa.vector_ar.vecm.VECMResults.test_whiteness statsmodels.tsa.vector\_ar.vecm.VECMResults.test\_whiteness =========================================================== `VECMResults.test_whiteness(nlags=10, signif=0.05, adjusted=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/vecm.html#VECMResults.test_whiteness) Test the whiteness of the residuals using the Portmanteau test. This test is described in [[1]](#id2), chapter 8.4.1. | Parameters: | * **nlags** (*int > 0*) – * **signif** (float, 0 < `signif` < 1) – * **adjusted** (*bool**,* *default False*) – | | Returns: | **result** | | Return type: | [`statsmodels.tsa.vector_ar.hypothesis_test_results.WhitenessTestResults`](statsmodels.tsa.vector_ar.hypothesis_test_results.whitenesstestresults#statsmodels.tsa.vector_ar.hypothesis_test_results.WhitenessTestResults "statsmodels.tsa.vector_ar.hypothesis_test_results.WhitenessTestResults") | #### References | | | | --- | --- | | [[1]](#id1) | Lütkepohl, H. 2005. *New Introduction to Multiple Time Series Analysis*. Springer. | statsmodels statsmodels.tsa.statespace.sarimax.SARIMAX.impulse_responses statsmodels.tsa.statespace.sarimax.SARIMAX.impulse\_responses ============================================================= `SARIMAX.impulse_responses(params, steps=1, impulse=0, orthogonalized=False, cumulative=False, **kwargs)` Impulse response function | Parameters: | * **params** (*array\_like*) – Array of model parameters. * **steps** (*int**,* *optional*) – The number of steps for which impulse responses are calculated. Default is 1. Note that the initial impulse is not counted as a step, so if `steps=1`, the output will have 2 entries. * **impulse** (*int* *or* *array\_like*) – If an integer, the state innovation to pulse; must be between 0 and `k_posdef-1`. Alternatively, a custom impulse vector may be provided; must be shaped `k_posdef x 1`. * **orthogonalized** (*boolean**,* *optional*) – Whether or not to perform impulse using orthogonalized innovations. Note that this will also affect custum `impulse` vectors. Default is False. * **cumulative** (*boolean**,* *optional*) – Whether or not to return cumulative impulse responses. Default is False. * **\*\*kwargs** – If the model is time-varying and `steps` is greater than the number of observations, any of the state space representation matrices that are time-varying must have updated values provided for the out-of-sample steps. For example, if `design` is a time-varying component, `nobs` is 10, and `steps` is 15, a (`k_endog` x `k_states` x 5) matrix must be provided with the new design matrix values. | | Returns: | **impulse\_responses** – Responses for each endogenous variable due to the impulse given by the `impulse` argument. A (steps + 1 x k\_endog) array. | | Return type: | array | #### Notes Intercepts in the measurement and state equation are ignored when calculating impulse responses. statsmodels statsmodels.tsa.vector_ar.var_model.VARResults.stderr_endog_lagged statsmodels.tsa.vector\_ar.var\_model.VARResults.stderr\_endog\_lagged ====================================================================== `VARResults.stderr_endog_lagged()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/var_model.html#VARResults.stderr_endog_lagged) statsmodels statsmodels.duration.hazard_regression.PHReg.baseline_cumulative_hazard_function statsmodels.duration.hazard\_regression.PHReg.baseline\_cumulative\_hazard\_function ==================================================================================== `PHReg.baseline_cumulative_hazard_function(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/duration/hazard_regression.html#PHReg.baseline_cumulative_hazard_function) Returns a function that calculates the baseline cumulative hazard function for each stratum. | Parameters: | **params** (*ndarray*) – The model parameters. | | Returns: | * *A dict mapping stratum names to the estimated baseline* * *cumulative hazard function.* | statsmodels statsmodels.tsa.vector_ar.vecm.VECM.hessian statsmodels.tsa.vector\_ar.vecm.VECM.hessian ============================================ `VECM.hessian(params)` The Hessian matrix of the model statsmodels statsmodels.genmod.families.family.Family statsmodels.genmod.families.family.Family ========================================= `class statsmodels.genmod.families.family.Family(link, variance)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/family.html#Family) The parent class for one-parameter exponential families. | Parameters: | * **link** (*a link function instance*) – Link is the linear transformation function. See the individual families for available links. * **variance** (*a variance function*) – Measures the variance as a function of the mean probabilities. See the individual families for the default variance function. | See also [Link Functions](../glm#links) #### Methods | | | | --- | --- | | [`deviance`](statsmodels.genmod.families.family.family.deviance#statsmodels.genmod.families.family.Family.deviance "statsmodels.genmod.families.family.Family.deviance")(endog, mu[, var\_weights, …]) | The deviance function evaluated at (endog, mu, var\_weights, freq\_weights, scale) for the distribution. | | [`fitted`](statsmodels.genmod.families.family.family.fitted#statsmodels.genmod.families.family.Family.fitted "statsmodels.genmod.families.family.Family.fitted")(lin\_pred) | Fitted values based on linear predictors lin\_pred. | | [`loglike`](statsmodels.genmod.families.family.family.loglike#statsmodels.genmod.families.family.Family.loglike "statsmodels.genmod.families.family.Family.loglike")(endog, mu[, var\_weights, …]) | The log-likelihood function in terms of the fitted mean response. | | [`loglike_obs`](statsmodels.genmod.families.family.family.loglike_obs#statsmodels.genmod.families.family.Family.loglike_obs "statsmodels.genmod.families.family.Family.loglike_obs")(endog, mu[, var\_weights, scale]) | The log-likelihood function for each observation in terms of the fitted mean response for the distribution. | | [`predict`](statsmodels.genmod.families.family.family.predict#statsmodels.genmod.families.family.Family.predict "statsmodels.genmod.families.family.Family.predict")(mu) | Linear predictors based on given mu values. | | [`resid_anscombe`](statsmodels.genmod.families.family.family.resid_anscombe#statsmodels.genmod.families.family.Family.resid_anscombe "statsmodels.genmod.families.family.Family.resid_anscombe")(endog, mu[, var\_weights, scale]) | The Anscombe residuals | | [`resid_dev`](statsmodels.genmod.families.family.family.resid_dev#statsmodels.genmod.families.family.Family.resid_dev "statsmodels.genmod.families.family.Family.resid_dev")(endog, mu[, var\_weights, scale]) | The deviance residuals | | [`starting_mu`](statsmodels.genmod.families.family.family.starting_mu#statsmodels.genmod.families.family.Family.starting_mu "statsmodels.genmod.families.family.Family.starting_mu")(y) | Starting value for mu in the IRLS algorithm. | | [`weights`](statsmodels.genmod.families.family.family.weights#statsmodels.genmod.families.family.Family.weights "statsmodels.genmod.families.family.Family.weights")(mu) | Weights for IRLS steps | statsmodels statsmodels.discrete.discrete_model.BinaryModel.cov_params_func_l1 statsmodels.discrete.discrete\_model.BinaryModel.cov\_params\_func\_l1 ====================================================================== `BinaryModel.cov_params_func_l1(likelihood_model, xopt, retvals)` Computes cov\_params on a reduced parameter space corresponding to the nonzero parameters resulting from the l1 regularized fit. Returns a full cov\_params matrix, with entries corresponding to zero’d values set to np.nan. statsmodels statsmodels.imputation.mice.MICEData.impute statsmodels.imputation.mice.MICEData.impute =========================================== `MICEData.impute(vname)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/imputation/mice.html#MICEData.impute) statsmodels statsmodels.tsa.statespace.structural.UnobservedComponentsResults.get_prediction statsmodels.tsa.statespace.structural.UnobservedComponentsResults.get\_prediction ================================================================================= `UnobservedComponentsResults.get_prediction(start=None, end=None, dynamic=False, index=None, exog=None, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/structural.html#UnobservedComponentsResults.get_prediction) In-sample prediction and out-of-sample forecasting | Parameters: | * **start** (*int**,* *str**, or* *datetime**,* *optional*) – Zero-indexed observation number at which to start forecasting, ie., the first forecast is start. Can also be a date string to parse or a datetime type. Default is the the zeroth observation. * **end** (*int**,* *str**, or* *datetime**,* *optional*) – Zero-indexed observation number at which to end forecasting, ie., the first forecast is start. Can also be a date string to parse or a datetime type. However, if the dates index does not have a fixed frequency, end must be an integer index if you want out of sample prediction. Default is the last observation in the sample. * **exog** (*array\_like**,* *optional*) – If the model includes exogenous regressors, you must provide exactly enough out-of-sample values for the exogenous variables if end is beyond the last observation in the sample. * **dynamic** (*boolean**,* *int**,* *str**, or* *datetime**,* *optional*) – Integer offset relative to `start` at which to begin dynamic prediction. Can also be an absolute date string to parse or a datetime type (these are not interpreted as offsets). Prior to this observation, true endogenous values will be used for prediction; starting with this observation and continuing through the end of prediction, forecasted endogenous values will be used instead. * **full\_results** (*boolean**,* *optional*) – If True, returns a FilterResults instance; if False returns a tuple with forecasts, the forecast errors, and the forecast error covariance matrices. Default is False. * **\*\*kwargs** – Additional arguments may required for forecasting beyond the end of the sample. See `FilterResults.predict` for more details. | | Returns: | **forecast** – Array of out of sample forecasts. | | Return type: | array | statsmodels statsmodels.stats.contingency_tables.Table2x2.log_riskratio statsmodels.stats.contingency\_tables.Table2x2.log\_riskratio ============================================================= `Table2x2.log_riskratio()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table2x2.log_riskratio) statsmodels statsmodels.tools.eval_measures.aic statsmodels.tools.eval\_measures.aic ==================================== `statsmodels.tools.eval_measures.aic(llf, nobs, df_modelwc)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tools/eval_measures.html#aic) Akaike information criterion | Parameters: | * **llf** (*float*) – value of the loglikelihood * **nobs** (*int*) – number of observations * **df\_modelwc** (*int*) – number of parameters including constant | | Returns: | **aic** – information criterion | | Return type: | float | #### References <http://en.wikipedia.org/wiki/Akaike_information_criterion> statsmodels statsmodels.stats.weightstats.DescrStatsW.tconfint_mean statsmodels.stats.weightstats.DescrStatsW.tconfint\_mean ======================================================== `DescrStatsW.tconfint_mean(alpha=0.05, alternative='two-sided')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/weightstats.html#DescrStatsW.tconfint_mean) two-sided confidence interval for weighted mean of data If the data is 2d, then these are separate confidence intervals for each column. | Parameters: | * **alpha** (*float*) – significance level for the confidence interval, coverage is `1-alpha` * **alternative** (*string*) – This specifies the alternative hypothesis for the test that corresponds to the confidence interval. The alternative hypothesis, H1, has to be one of the following ’two-sided’: H1: mean not equal to value (default) ‘larger’ : H1: mean larger than value ‘smaller’ : H1: mean smaller than value | | Returns: | **lower, upper** – lower and upper bound of confidence interval | | Return type: | floats or ndarrays | #### Notes In a previous version, statsmodels 0.4, alpha was the confidence level, e.g. 0.95 statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.condition_number statsmodels.sandbox.regression.gmm.IVRegressionResults.condition\_number ======================================================================== `IVRegressionResults.condition_number()` Return condition number of exogenous matrix. Calculated as ratio of largest to smallest eigenvalue.
programming_docs
statsmodels statsmodels.discrete.discrete_model.Poisson.initialize statsmodels.discrete.discrete\_model.Poisson.initialize ======================================================= `Poisson.initialize()` Initialize is called by statsmodels.model.LikelihoodModel.\_\_init\_\_ and should contain any preprocessing that needs to be done for a model. statsmodels statsmodels.sandbox.distributions.extras.ACSkewT_gen.pdf statsmodels.sandbox.distributions.extras.ACSkewT\_gen.pdf ========================================================= `ACSkewT_gen.pdf(x, *args, **kwds)` Probability density function at x of the given RV. | Parameters: | * **x** (*array\_like*) – quantiles * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **pdf** – Probability density function evaluated at x | | Return type: | ndarray | statsmodels statsmodels.genmod.families.family.Gaussian.fitted statsmodels.genmod.families.family.Gaussian.fitted ================================================== `Gaussian.fitted(lin_pred)` Fitted values based on linear predictors lin\_pred. | Parameters: | **lin\_pred** (*array*) – Values of the linear predictor of the model. \(X \cdot \beta\) in a classical linear model. | | Returns: | **mu** – The mean response variables given by the inverse of the link function. | | Return type: | array | statsmodels statsmodels.miscmodels.count.PoissonOffsetGMLE.initialize statsmodels.miscmodels.count.PoissonOffsetGMLE.initialize ========================================================= `PoissonOffsetGMLE.initialize()` Initialize (possibly re-initialize) a Model instance. For instance, the design matrix of a linear model may change and some things must be recomputed. statsmodels statsmodels.discrete.discrete_model.NegativeBinomialResults.bic statsmodels.discrete.discrete\_model.NegativeBinomialResults.bic ================================================================ `NegativeBinomialResults.bic()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#NegativeBinomialResults.bic) statsmodels statsmodels.tsa.statespace.kalman_filter.KalmanFilter.bind statsmodels.tsa.statespace.kalman\_filter.KalmanFilter.bind =========================================================== `KalmanFilter.bind(endog)` Bind data to the statespace representation | Parameters: | **endog** (*array*) – Endogenous data to bind to the model. Must be column-ordered ndarray with shape (`k_endog`, `nobs`) or row-ordered ndarray with shape (`nobs`, `k_endog`). | #### Notes The strict requirements arise because the underlying statespace and Kalman filtering classes require Fortran-ordered arrays in the wide format (shaped (`k_endog`, `nobs`)), and this structure is setup to prevent copying arrays in memory. By default, numpy arrays are row (C)-ordered and most time series are represented in the long format (with time on the 0-th axis). In this case, no copying or re-ordering needs to be performed, instead the array can simply be transposed to get it in the right order and shape. Although this class (Representation) has stringent `bind` requirements, it is assumed that it will rarely be used directly. statsmodels statsmodels.sandbox.regression.gmm.IVGMMResults.q statsmodels.sandbox.regression.gmm.IVGMMResults.q ================================================= `IVGMMResults.q()` statsmodels statsmodels.robust.robust_linear_model.RLMResults.summary2 statsmodels.robust.robust\_linear\_model.RLMResults.summary2 ============================================================ `RLMResults.summary2(xname=None, yname=None, title=None, alpha=0.05, float_format='%.4f')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/robust_linear_model.html#RLMResults.summary2) Experimental summary function for regression results | Parameters: | * **xname** (*List of strings of length equal to the number of parameters*) – Names of the independent variables (optional) * **yname** (*string*) – Name of the dependent variable (optional) * **title** (*string**,* *optional*) – Title for the top table. If not None, then this replaces the default title * **alpha** (*float*) – significance level for the confidence intervals * **float\_format** (*string*) – print format for floats in parameters summary | | Returns: | **smry** – this holds the summary tables and text, which can be printed or converted to various output formats. | | Return type: | Summary instance | See also [`statsmodels.iolib.summary.Summary`](statsmodels.iolib.summary.summary#statsmodels.iolib.summary.Summary "statsmodels.iolib.summary.Summary") class to hold summary results statsmodels statsmodels.iolib.table.SimpleTable.index statsmodels.iolib.table.SimpleTable.index ========================================= `SimpleTable.index(value[, start[, stop]]) → integer -- return first index of value.` Raises ValueError if the value is not present. statsmodels statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.hessian statsmodels.tsa.regime\_switching.markov\_regression.MarkovRegression.hessian ============================================================================= `MarkovRegression.hessian(params, transformed=True)` Hessian matrix of the likelihood function, evaluated at the given parameters | Parameters: | * **params** (*array\_like*) – Array of parameters at which to evaluate the Hessian function. * **transformed** (*boolean**,* *optional*) – Whether or not `params` is already transformed. Default is True. | statsmodels statsmodels.robust.norms.HuberT.psi statsmodels.robust.norms.HuberT.psi =================================== `HuberT.psi(z)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/norms.html#HuberT.psi) The psi function for Huber’s t estimator The analytic derivative of rho | Parameters: | **z** (*array-like*) – 1d array | | Returns: | **psi** – psi(z) = z for |z| <= tpsi(z) = sign(z)\*t for |z| > t | | Return type: | array | statsmodels statsmodels.regression.linear_model.RegressionResults.fvalue statsmodels.regression.linear\_model.RegressionResults.fvalue ============================================================= `RegressionResults.fvalue()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#RegressionResults.fvalue) statsmodels statsmodels.tools.eval_measures.mse statsmodels.tools.eval\_measures.mse ==================================== `statsmodels.tools.eval_measures.mse(x1, x2, axis=0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tools/eval_measures.html#mse) mean squared error | Parameters: | * **x2** (*x1**,*) – The performance measure depends on the difference between these two arrays. * **axis** (*int*) – axis along which the summary statistic is calculated | | Returns: | **mse** – mean squared error along given axis. | | Return type: | ndarray or float | #### Notes If `x1` and `x2` have different shapes, then they need to broadcast. This uses `numpy.asanyarray` to convert the input. Whether this is the desired result or not depends on the array subclass, for example numpy matrices will silently produce an incorrect result. statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.compare_f_test statsmodels.sandbox.regression.gmm.IVRegressionResults.compare\_f\_test ======================================================================= `IVRegressionResults.compare_f_test(restricted)` use F test to test whether restricted model is correct | Parameters: | **restricted** (*Result instance*) – The restricted model is assumed to be nested in the current model. The result instance of the restricted model is required to have two attributes, residual sum of squares, `ssr`, residual degrees of freedom, `df_resid`. | | Returns: | * **f\_value** (*float*) – test statistic, F distributed * **p\_value** (*float*) – p-value of the test statistic * **df\_diff** (*int*) – degrees of freedom of the restriction, i.e. difference in df between models | #### Notes See mailing list discussion October 17, This test compares the residual sum of squares of the two models. This is not a valid test, if there is unspecified heteroscedasticity or correlation. This method will issue a warning if this is detected but still return the results under the assumption of homoscedasticity and no autocorrelation (sphericity). statsmodels statsmodels.sandbox.distributions.transformed.ExpTransf_gen.fit_loc_scale statsmodels.sandbox.distributions.transformed.ExpTransf\_gen.fit\_loc\_scale ============================================================================ `ExpTransf_gen.fit_loc_scale(data, *args)` Estimate loc and scale parameters from data using 1st and 2nd moments. | Parameters: | * **data** (*array\_like*) – Data to fit. * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information). | | Returns: | * **Lhat** (*float*) – Estimated location parameter for the data. * **Shat** (*float*) – Estimated scale parameter for the data. | statsmodels statsmodels.tools.numdiff.approx_fprime_cs statsmodels.tools.numdiff.approx\_fprime\_cs ============================================ `statsmodels.tools.numdiff.approx_fprime_cs(x, f, epsilon=None, args=(), kwargs={})` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tools/numdiff.html#approx_fprime_cs) Calculate gradient or Jacobian with complex step derivative approximation | Parameters: | * **x** (*array*) – parameters at which the derivative is evaluated * **f** (*function*) – `f(*((x,)+args), **kwargs)` returning either one value or 1d array * **epsilon** (*float**,* *optional*) – Stepsize, if None, optimal stepsize is used. Optimal step-size is EPS\*x. See note. * **args** (*tuple*) – Tuple of additional arguments for function `f`. * **kwargs** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")) – Dictionary of additional keyword arguments for function `f`. | | Returns: | **partials** – array of partial derivatives, Gradient or Jacobian | | Return type: | ndarray | #### Notes The complex-step derivative has truncation error O(epsilon\*\*2), so truncation error can be eliminated by choosing epsilon to be very small. The complex-step derivative avoids the problem of round-off error with small epsilon because there is no subtraction. statsmodels statsmodels.tsa.statespace.kalman_smoother.SmootherResults.update_smoother statsmodels.tsa.statespace.kalman\_smoother.SmootherResults.update\_smoother ============================================================================ `SmootherResults.update_smoother(smoother)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/kalman_smoother.html#SmootherResults.update_smoother) Update the smoother results | Parameters: | **smoother** ([KalmanSmoother](statsmodels.tsa.statespace.kalman_smoother.kalmansmoother#statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother "statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother")) – The model object from which to take the updated values. | #### Notes This method is rarely required except for internal usage. statsmodels statsmodels.genmod.generalized_estimating_equations.GEEResults.summary statsmodels.genmod.generalized\_estimating\_equations.GEEResults.summary ======================================================================== `GEEResults.summary(yname=None, xname=None, title=None, alpha=0.05)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_estimating_equations.html#GEEResults.summary) Summarize the GEE regression results | Parameters: | * **yname** (*string**,* *optional*) – Default is `y` * **xname** (*list of strings**,* *optional*) – Default is `var_##` for ## in p the number of regressors * **title** (*string**,* *optional*) – Title for the top table. If not None, then this replaces the default title * **alpha** (*float*) – significance level for the confidence intervals * **cov\_type** (*string*) – The covariance type used to compute the standard errors; one of ‘robust’ (the usual robust sandwich-type covariance estimate), ‘naive’ (ignores dependence), and ‘bias reduced’ (the Mancl/DeRouen estimate). | | Returns: | **smry** – this holds the summary tables and text, which can be printed or converted to various output formats. | | Return type: | Summary instance | See also [`statsmodels.iolib.summary.Summary`](statsmodels.iolib.summary.summary#statsmodels.iolib.summary.Summary "statsmodels.iolib.summary.Summary") class to hold summary results statsmodels statsmodels.stats.sandwich_covariance.cov_white_simple statsmodels.stats.sandwich\_covariance.cov\_white\_simple ========================================================= `statsmodels.stats.sandwich_covariance.cov_white_simple(results, use_correction=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/sandwich_covariance.html#cov_white_simple) heteroscedasticity robust covariance matrix (White) | Parameters: | **results** (*result instance*) – result of a regression, uses results.model.exog and results.resid TODO: this should use wexog instead | | Returns: | **cov** – heteroscedasticity robust covariance matrix for parameter estimates | | Return type: | ndarray, (k\_vars, k\_vars) | #### Notes This produces the same result as cov\_hc0, and does not include any small sample correction. verified (against LinearRegressionResults and Peterson) See also [`cov_hc1`](statsmodels.stats.sandwich_covariance.cov_hc1#statsmodels.stats.sandwich_covariance.cov_hc1 "statsmodels.stats.sandwich_covariance.cov_hc1"), [`cov_hc2`](statsmodels.stats.sandwich_covariance.cov_hc2#statsmodels.stats.sandwich_covariance.cov_hc2 "statsmodels.stats.sandwich_covariance.cov_hc2"), [`cov_hc3`](statsmodels.stats.sandwich_covariance.cov_hc3#statsmodels.stats.sandwich_covariance.cov_hc3 "statsmodels.stats.sandwich_covariance.cov_hc3") statsmodels statsmodels.sandbox.regression.gmm.GMM.set_param_names statsmodels.sandbox.regression.gmm.GMM.set\_param\_names ======================================================== `GMM.set_param_names(param_names, k_params=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#GMM.set_param_names) set the parameter names in the model | Parameters: | * **param\_names** (*list of strings*) – param\_names should have the same length as the number of params * **k\_params** (*None* *or* *int*) – If k\_params is None, then the k\_params attribute is used, unless it is None. If k\_params is not None, then it will also set the k\_params attribute. | statsmodels statsmodels.regression.recursive_ls.RecursiveLS.hessian statsmodels.regression.recursive\_ls.RecursiveLS.hessian ======================================================== `RecursiveLS.hessian(params, *args, **kwargs)` Hessian matrix of the likelihood function, evaluated at the given parameters | Parameters: | * **params** (*array\_like*) – Array of parameters at which to evaluate the hessian. * **args** – Additional positional arguments to the `loglike` method. * **kwargs** – Additional keyword arguments to the `loglike` method. | | Returns: | **hessian** – Hessian matrix evaluated at `params` | | Return type: | array | #### Notes This is a numerical approximation. Both \*args and \*\*kwargs are necessary because the optimizer from `fit` must call this function and only supports passing arguments via \*args (for example `scipy.optimize.fmin_l_bfgs`). statsmodels statsmodels.genmod.families.family.Binomial.initialize statsmodels.genmod.families.family.Binomial.initialize ====================================================== `Binomial.initialize(endog, freq_weights)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/family.html#Binomial.initialize) Initialize the response variable. | Parameters: | * **endog** (*array*) – Endogenous response variable * **freq\_weights** (*array*) – 1d array of frequency weights | | Returns: | * If `endog` is binary, returns `endog` * If `endog` is a 2d array, then the input is assumed to be in the format * *(successes, failures) and* * *successes/(success + failures) is returned. And n is set to* * *successes + failures.* | statsmodels statsmodels.nonparametric.kernel_regression.KernelCensoredReg.sig_test statsmodels.nonparametric.kernel\_regression.KernelCensoredReg.sig\_test ======================================================================== `KernelCensoredReg.sig_test(var_pos, nboot=50, nested_res=25, pivot=False)` Significance test for the variables in the regression. | Parameters: | **var\_pos** (*sequence*) – The position of the variable in exog to be tested. | | Returns: | **sig** –The level of significance:* `*` : at 90% confidence level * `**` : at 95% confidence level * `***` : at 99\* confidence level * ”Not Significant” : if not significant | | Return type: | str | statsmodels statsmodels.stats.gof.gof_binning_discrete statsmodels.stats.gof.gof\_binning\_discrete ============================================ `statsmodels.stats.gof.gof_binning_discrete(rvs, distfn, arg, nsupp=20)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/gof.html#gof_binning_discrete) get bins for chisquare type gof tests for a discrete distribution | Parameters: | * **rvs** (*array*) – sample data * **distname** (*string*) – name of distribution function * **arg** (*sequence*) – parameters of distribution * **nsupp** (*integer*) – number of bins. The algorithm tries to find bins with equal weights. depending on the distribution, the actual number of bins can be smaller. | | Returns: | * **freq** (*array*) – empirical frequencies for sample; not normalized, adds up to sample size * **expfreq** (*array*) – theoretical frequencies according to distribution * **histsupp** (*array*) – bin boundaries for histogram, (added 1e-8 for numerical robustness) | #### Notes The results can be used for a chisquare test ``` (chis,pval) = stats.chisquare(freq, expfreq) ``` originally written for scipy.stats test suite, still needs to be checked for standalone usage, insufficient input checking may not run yet (after copy/paste) refactor: maybe a class, check returns, or separate binning from test results todo : optimal number of bins ? (check easyfit), recommendation in literature at least 5 expected observations in each bin statsmodels statsmodels.iolib.foreign.StataReader.file_format statsmodels.iolib.foreign.StataReader.file\_format ================================================== `StataReader.file_format()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/iolib/foreign.html#StataReader.file_format) Returns the file format. | Returns: | **out** | | Return type: | int | #### Notes Format 113: Stata 8/9 Format 114: Stata 10/11 Format 115: Stata 12 statsmodels statsmodels.genmod.families.family.Tweedie.weights statsmodels.genmod.families.family.Tweedie.weights ================================================== `Tweedie.weights(mu)` Weights for IRLS steps | Parameters: | **mu** (*array-like*) – The transformed mean response variable in the exponential family | | Returns: | **w** – The weights for the IRLS steps | | Return type: | array | #### Notes \[w = 1 / (g'(\mu)^2 \* Var(\mu))\] statsmodels statsmodels.iolib.table.SimpleTable statsmodels.iolib.table.SimpleTable =================================== `class statsmodels.iolib.table.SimpleTable(data, headers=None, stubs=None, title='', datatypes=None, csv_fmt=None, txt_fmt=None, ltx_fmt=None, html_fmt=None, celltype=None, rowtype=None, **fmt_dict)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/iolib/table.html#SimpleTable) Produce a simple ASCII, CSV, HTML, or LaTeX table from a *rectangular* (2d!) array of data, not necessarily numerical. Directly supports at most one header row, which should be the length of data[0]. Directly supports at most one stubs column, which must be the length of data. (But see `insert_stubs` method.) See globals `default_txt_fmt`, `default_csv_fmt`, `default_html_fmt`, and `default_latex_fmt` for formatting options. Sample uses: ``` mydata = [[11,12],[21,22]] # data MUST be 2-dimensional myheaders = [ "Column 1", "Column 2" ] mystubs = [ "Row 1", "Row 2" ] tbl = text.SimpleTable(mydata, myheaders, mystubs, title="Title") print( tbl ) print( tbl.as_html() ) # set column specific data formatting tbl = text.SimpleTable(mydata, myheaders, mystubs, data_fmts=["%3.2f","%d"]) print( tbl.as_csv() ) with open('c:/temp/temp.tex','w') as fh: fh.write( tbl.as_latex_tabular() ) ``` #### Methods | | | | --- | --- | | [`append`](statsmodels.iolib.table.simpletable.append#statsmodels.iolib.table.SimpleTable.append "statsmodels.iolib.table.SimpleTable.append")(object) | | | [`as_csv`](statsmodels.iolib.table.simpletable.as_csv#statsmodels.iolib.table.SimpleTable.as_csv "statsmodels.iolib.table.SimpleTable.as_csv")(\*\*fmt\_dict) | Return string, the table in CSV format. | | [`as_html`](statsmodels.iolib.table.simpletable.as_html#statsmodels.iolib.table.SimpleTable.as_html "statsmodels.iolib.table.SimpleTable.as_html")(\*\*fmt\_dict) | Return string. | | [`as_latex_tabular`](statsmodels.iolib.table.simpletable.as_latex_tabular#statsmodels.iolib.table.SimpleTable.as_latex_tabular "statsmodels.iolib.table.SimpleTable.as_latex_tabular")([center]) | Return string, the table as a LaTeX tabular environment. | | [`as_text`](statsmodels.iolib.table.simpletable.as_text#statsmodels.iolib.table.SimpleTable.as_text "statsmodels.iolib.table.SimpleTable.as_text")(\*\*fmt\_dict) | Return string, the table as text. | | [`clear`](statsmodels.iolib.table.simpletable.clear#statsmodels.iolib.table.SimpleTable.clear "statsmodels.iolib.table.SimpleTable.clear")() | | | [`copy`](statsmodels.iolib.table.simpletable.copy#statsmodels.iolib.table.SimpleTable.copy "statsmodels.iolib.table.SimpleTable.copy")() | | | [`count`](statsmodels.iolib.table.simpletable.count#statsmodels.iolib.table.SimpleTable.count "statsmodels.iolib.table.SimpleTable.count")(value) | | | [`extend`](statsmodels.iolib.table.simpletable.extend#statsmodels.iolib.table.SimpleTable.extend "statsmodels.iolib.table.SimpleTable.extend")(iterable) | | | [`extend_right`](statsmodels.iolib.table.simpletable.extend_right#statsmodels.iolib.table.SimpleTable.extend_right "statsmodels.iolib.table.SimpleTable.extend_right")(table) | Return None. | | [`get_colwidths`](statsmodels.iolib.table.simpletable.get_colwidths#statsmodels.iolib.table.SimpleTable.get_colwidths "statsmodels.iolib.table.SimpleTable.get_colwidths")(output\_format, \*\*fmt\_dict) | Return list, the widths of each column. | | [`index`](statsmodels.iolib.table.simpletable.index#statsmodels.iolib.table.SimpleTable.index "statsmodels.iolib.table.SimpleTable.index")(value, [start, [stop]]) | Raises ValueError if the value is not present. | | [`insert`](statsmodels.iolib.table.simpletable.insert#statsmodels.iolib.table.SimpleTable.insert "statsmodels.iolib.table.SimpleTable.insert")(idx, row[, datatype]) | Return None. | | [`insert_header_row`](statsmodels.iolib.table.simpletable.insert_header_row#statsmodels.iolib.table.SimpleTable.insert_header_row "statsmodels.iolib.table.SimpleTable.insert_header_row")(rownum, headers[, dec\_below]) | Return None. | | [`insert_stubs`](statsmodels.iolib.table.simpletable.insert_stubs#statsmodels.iolib.table.SimpleTable.insert_stubs "statsmodels.iolib.table.SimpleTable.insert_stubs")(loc, stubs) | Return None. | | [`label_cells`](statsmodels.iolib.table.simpletable.label_cells#statsmodels.iolib.table.SimpleTable.label_cells "statsmodels.iolib.table.SimpleTable.label_cells")(func) | Return None. | | [`pad`](statsmodels.iolib.table.simpletable.pad#statsmodels.iolib.table.SimpleTable.pad "statsmodels.iolib.table.SimpleTable.pad")(s, width, align) | DEPRECATED: just use the pad function | | [`pop`](statsmodels.iolib.table.simpletable.pop#statsmodels.iolib.table.SimpleTable.pop "statsmodels.iolib.table.SimpleTable.pop")([index]) | Raises IndexError if list is empty or index is out of range. | | [`remove`](statsmodels.iolib.table.simpletable.remove#statsmodels.iolib.table.SimpleTable.remove "statsmodels.iolib.table.SimpleTable.remove")(value) | Raises ValueError if the value is not present. | | [`reverse`](statsmodels.iolib.table.simpletable.reverse#statsmodels.iolib.table.SimpleTable.reverse "statsmodels.iolib.table.SimpleTable.reverse") | L.reverse() – reverse *IN PLACE* | | [`sort`](statsmodels.iolib.table.simpletable.sort#statsmodels.iolib.table.SimpleTable.sort "statsmodels.iolib.table.SimpleTable.sort")([key, reverse]) | | #### Attributes | | | | --- | --- | | `data` | |
programming_docs
statsmodels statsmodels.tsa.ar_model.ARResults.tvalues statsmodels.tsa.ar\_model.ARResults.tvalues =========================================== `ARResults.tvalues()` Return the t-statistic for a given parameter estimate. statsmodels statsmodels.iolib.table.SimpleTable.label_cells statsmodels.iolib.table.SimpleTable.label\_cells ================================================ `SimpleTable.label_cells(func)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/iolib/table.html#SimpleTable.label_cells) Return None. Labels cells based on `func`. If `func(cell) is None` then its datatype is not changed; otherwise it is set to `func(cell)`. statsmodels statsmodels.stats.gof.chisquare_effectsize statsmodels.stats.gof.chisquare\_effectsize =========================================== `statsmodels.stats.gof.chisquare_effectsize(probs0, probs1, correction=None, cohen=True, axis=0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/gof.html#chisquare_effectsize) effect size for a chisquare goodness-of-fit test | Parameters: | * **probs0** (*array\_like*) – probabilities or cell frequencies under the Null hypothesis * **probs1** (*array\_like*) – probabilities or cell frequencies under the Alternative hypothesis probs0 and probs1 need to have the same length in the `axis` dimension. and broadcast in the other dimensions Both probs0 and probs1 are normalized to add to one (in the `axis` dimension). * **correction** (*None* *or* *tuple*) – If None, then the effect size is the chisquare statistic divide by the number of observations. If the correction is a tuple (nobs, df), then the effectsize is corrected to have less bias and a smaller variance. However, the correction can make the effectsize negative. In that case, the effectsize is set to zero. Pederson and Johnson (1990) as referenced in McLaren et all. (1994) * **cohen** (*bool*) – If True, then the square root is returned as in the definition of the effect size by Cohen (1977), If False, then the original effect size is returned. * **axis** (*int*) – If the probability arrays broadcast to more than 1 dimension, then this is the axis over which the sums are taken. | | Returns: | **effectsize** – effect size of chisquare test | | Return type: | float | statsmodels statsmodels.genmod.generalized_linear_model.GLM.score_obs statsmodels.genmod.generalized\_linear\_model.GLM.score\_obs ============================================================ `GLM.score_obs(params, scale=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_linear_model.html#GLM.score_obs) score first derivative of the loglikelihood for each observation. | Parameters: | * **params** (*ndarray*) – parameter at which score is evaluated * **scale** (*None* *or* *float*) – If scale is None, then the default scale will be calculated. Default scale is defined by `self.scaletype` and set in fit. If scale is not None, then it is used as a fixed scale. | | Returns: | **score\_obs** – The first derivative of the loglikelihood function evaluated at params for each observation. | | Return type: | ndarray, 2d | statsmodels statsmodels.genmod.families.links.Log.inverse_deriv statsmodels.genmod.families.links.Log.inverse\_deriv ==================================================== `Log.inverse_deriv(z)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/links.html#Log.inverse_deriv) Derivative of the inverse of the log transform link function | Parameters: | **z** (*array*) – The inverse of the link function at `p` | | Returns: | **g^(-1)’(z)** – The value of the derivative of the inverse of the log function, the exponential function | | Return type: | array | statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.zvalues statsmodels.tsa.statespace.dynamic\_factor.DynamicFactorResults.zvalues ======================================================================= `DynamicFactorResults.zvalues()` (array) The z-statistics for the coefficients. statsmodels statsmodels.stats.power.tt_solve_power statsmodels.stats.power.tt\_solve\_power ======================================== `statsmodels.stats.power.tt_solve_power = <bound method TTestPower.solve_power of <statsmodels.stats.power.TTestPower object>>` solve for any one parameter of the power of a one sample t-test for the one sample t-test the keywords are: effect\_size, nobs, alpha, power Exactly one needs to be `None`, all others need numeric values. This test can also be used for a paired t-test, where effect size is defined in terms of the mean difference, and nobs is the number of pairs. | Parameters: | * **effect\_size** (*float*) – standardized effect size, mean divided by the standard deviation. effect size has to be positive. * **nobs** (*int* *or* *float*) – sample size, number of observations. * **alpha** (*float in interval* *(**0**,**1**)*) – significance level, e.g. 0.05, is the probability of a type I error, that is wrong rejections if the Null Hypothesis is true. * **power** (*float in interval* *(**0**,**1**)*) – power of the test, e.g. 0.8, is one minus the probability of a type II error. Power is the probability that the test correctly rejects the Null Hypothesis if the Alternative Hypothesis is true. * **alternative** (*string**,* *'two-sided'* *(**default**) or* *'one-sided'*) – extra argument to choose whether the power is calculated for a two-sided (default) or one sided test. ‘one-sided’ assumes we are in the relevant tail. | | Returns: | * **value** (*float*) – The value of the parameter that was set to None in the call. The value solves the power equation given the remaining parameters. * *\*attaches\** * **cache\_fit\_res** (*list*) – Cache of the result of the root finding procedure for the latest call to `solve_power`, mainly for debugging purposes. The first element is the success indicator, one if successful. The remaining elements contain the return information of the up to three solvers that have been tried. | #### Notes The function uses scipy.optimize for finding the value that satisfies the power equation. It first uses `brentq` with a prior search for bounds. If this fails to find a root, `fsolve` is used. If `fsolve` also fails, then, for `alpha`, `power` and `effect_size`, `brentq` with fixed bounds is used. However, there can still be cases where this fails. statsmodels statsmodels.tsa.statespace.varmax.VARMAXResults.llf statsmodels.tsa.statespace.varmax.VARMAXResults.llf =================================================== `VARMAXResults.llf()` (float) The value of the log-likelihood function evaluated at `params`. statsmodels statsmodels.discrete.discrete_model.NegativeBinomialResults.bse statsmodels.discrete.discrete\_model.NegativeBinomialResults.bse ================================================================ `NegativeBinomialResults.bse()` statsmodels statsmodels.regression.quantile_regression.QuantRegResults.wresid statsmodels.regression.quantile\_regression.QuantRegResults.wresid ================================================================== `QuantRegResults.wresid()` statsmodels statsmodels.discrete.discrete_model.GeneralizedPoissonResults statsmodels.discrete.discrete\_model.GeneralizedPoissonResults ============================================================== `class statsmodels.discrete.discrete_model.GeneralizedPoissonResults(model, mlefit, cov_type='nonrobust', cov_kwds=None, use_t=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#GeneralizedPoissonResults) A results class for Generalized Poisson | Parameters: | * **model** (*A DiscreteModel instance*) – * **params** (*array-like*) – The parameters of a fitted model. * **hessian** (*array-like*) – The hessian of the fitted model. * **scale** (*float*) – A scale parameter for the covariance matrix. | | Returns: | * *\*Attributes\** * **aic** (*float*) – Akaike information criterion. `-2*(llf - p)` where `p` is the number of regressors including the intercept. * **bic** (*float*) – Bayesian information criterion. `-2*llf + ln(nobs)*p` where `p` is the number of regressors including the intercept. * **bse** (*array*) – The standard errors of the coefficients. * **df\_resid** (*float*) – See model definition. * **df\_model** (*float*) – See model definition. * **fitted\_values** (*array*) – Linear predictor XB. * **llf** (*float*) – Value of the loglikelihood * **llnull** (*float*) – Value of the constant-only loglikelihood * **llr** (*float*) – Likelihood ratio chi-squared statistic; `-2*(llnull - llf)` * **llr\_pvalue** (*float*) – The chi-squared probability of getting a log-likelihood ratio statistic greater than llr. llr has a chi-squared distribution with degrees of freedom `df_model`. * **prsquared** (*float*) – McFadden’s pseudo-R-squared. `1 - (llf / llnull)` | #### Methods | | | | --- | --- | | [`aic`](statsmodels.discrete.discrete_model.generalizedpoissonresults.aic#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.aic "statsmodels.discrete.discrete_model.GeneralizedPoissonResults.aic")() | | | [`bic`](statsmodels.discrete.discrete_model.generalizedpoissonresults.bic#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.bic "statsmodels.discrete.discrete_model.GeneralizedPoissonResults.bic")() | | | [`bse`](statsmodels.discrete.discrete_model.generalizedpoissonresults.bse#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.bse "statsmodels.discrete.discrete_model.GeneralizedPoissonResults.bse")() | | | [`conf_int`](statsmodels.discrete.discrete_model.generalizedpoissonresults.conf_int#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.conf_int "statsmodels.discrete.discrete_model.GeneralizedPoissonResults.conf_int")([alpha, cols, method]) | Returns the confidence interval of the fitted parameters. | | [`cov_params`](statsmodels.discrete.discrete_model.generalizedpoissonresults.cov_params#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.cov_params "statsmodels.discrete.discrete_model.GeneralizedPoissonResults.cov_params")([r\_matrix, column, scale, cov\_p, …]) | Returns the variance/covariance matrix. | | [`f_test`](statsmodels.discrete.discrete_model.generalizedpoissonresults.f_test#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.f_test "statsmodels.discrete.discrete_model.GeneralizedPoissonResults.f_test")(r\_matrix[, cov\_p, scale, invcov]) | Compute the F-test for a joint linear hypothesis. | | [`fittedvalues`](statsmodels.discrete.discrete_model.generalizedpoissonresults.fittedvalues#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.fittedvalues "statsmodels.discrete.discrete_model.GeneralizedPoissonResults.fittedvalues")() | | | [`get_margeff`](statsmodels.discrete.discrete_model.generalizedpoissonresults.get_margeff#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.get_margeff "statsmodels.discrete.discrete_model.GeneralizedPoissonResults.get_margeff")([at, method, atexog, dummy, count]) | Get marginal effects of the fitted model. | | [`initialize`](statsmodels.discrete.discrete_model.generalizedpoissonresults.initialize#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.initialize "statsmodels.discrete.discrete_model.GeneralizedPoissonResults.initialize")(model, params, \*\*kwd) | | | [`llf`](statsmodels.discrete.discrete_model.generalizedpoissonresults.llf#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.llf "statsmodels.discrete.discrete_model.GeneralizedPoissonResults.llf")() | | | [`llnull`](statsmodels.discrete.discrete_model.generalizedpoissonresults.llnull#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.llnull "statsmodels.discrete.discrete_model.GeneralizedPoissonResults.llnull")() | | | [`llr`](statsmodels.discrete.discrete_model.generalizedpoissonresults.llr#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.llr "statsmodels.discrete.discrete_model.GeneralizedPoissonResults.llr")() | | | [`llr_pvalue`](statsmodels.discrete.discrete_model.generalizedpoissonresults.llr_pvalue#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.llr_pvalue "statsmodels.discrete.discrete_model.GeneralizedPoissonResults.llr_pvalue")() | | | [`lnalpha`](statsmodels.discrete.discrete_model.generalizedpoissonresults.lnalpha#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.lnalpha "statsmodels.discrete.discrete_model.GeneralizedPoissonResults.lnalpha")() | | | [`lnalpha_std_err`](statsmodels.discrete.discrete_model.generalizedpoissonresults.lnalpha_std_err#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.lnalpha_std_err "statsmodels.discrete.discrete_model.GeneralizedPoissonResults.lnalpha_std_err")() | | | [`load`](statsmodels.discrete.discrete_model.generalizedpoissonresults.load#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.load "statsmodels.discrete.discrete_model.GeneralizedPoissonResults.load")(fname) | load a pickle, (class method) | | [`normalized_cov_params`](statsmodels.discrete.discrete_model.generalizedpoissonresults.normalized_cov_params#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.normalized_cov_params "statsmodels.discrete.discrete_model.GeneralizedPoissonResults.normalized_cov_params")() | | | [`predict`](statsmodels.discrete.discrete_model.generalizedpoissonresults.predict#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.predict "statsmodels.discrete.discrete_model.GeneralizedPoissonResults.predict")([exog, transform]) | Call self.model.predict with self.params as the first argument. | | [`prsquared`](statsmodels.discrete.discrete_model.generalizedpoissonresults.prsquared#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.prsquared "statsmodels.discrete.discrete_model.GeneralizedPoissonResults.prsquared")() | | | [`pvalues`](statsmodels.discrete.discrete_model.generalizedpoissonresults.pvalues#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.pvalues "statsmodels.discrete.discrete_model.GeneralizedPoissonResults.pvalues")() | | | [`remove_data`](statsmodels.discrete.discrete_model.generalizedpoissonresults.remove_data#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.remove_data "statsmodels.discrete.discrete_model.GeneralizedPoissonResults.remove_data")() | remove data arrays, all nobs arrays from result and model | | [`resid`](statsmodels.discrete.discrete_model.generalizedpoissonresults.resid#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.resid "statsmodels.discrete.discrete_model.GeneralizedPoissonResults.resid")() | Residuals | | [`save`](statsmodels.discrete.discrete_model.generalizedpoissonresults.save#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.save "statsmodels.discrete.discrete_model.GeneralizedPoissonResults.save")(fname[, remove\_data]) | save a pickle of this instance | | [`set_null_options`](statsmodels.discrete.discrete_model.generalizedpoissonresults.set_null_options#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.set_null_options "statsmodels.discrete.discrete_model.GeneralizedPoissonResults.set_null_options")([llnull, attach\_results]) | set fit options for Null (constant-only) model | | [`summary`](statsmodels.discrete.discrete_model.generalizedpoissonresults.summary#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.summary "statsmodels.discrete.discrete_model.GeneralizedPoissonResults.summary")([yname, xname, title, alpha, yname\_list]) | Summarize the Regression Results | | [`summary2`](statsmodels.discrete.discrete_model.generalizedpoissonresults.summary2#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.summary2 "statsmodels.discrete.discrete_model.GeneralizedPoissonResults.summary2")([yname, xname, title, alpha, …]) | Experimental function to summarize regression results | | [`t_test`](statsmodels.discrete.discrete_model.generalizedpoissonresults.t_test#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.t_test "statsmodels.discrete.discrete_model.GeneralizedPoissonResults.t_test")(r\_matrix[, cov\_p, scale, use\_t]) | Compute a t-test for a each linear hypothesis of the form Rb = q | | [`t_test_pairwise`](statsmodels.discrete.discrete_model.generalizedpoissonresults.t_test_pairwise#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.t_test_pairwise "statsmodels.discrete.discrete_model.GeneralizedPoissonResults.t_test_pairwise")(term\_name[, method, alpha, …]) | perform pairwise t\_test with multiple testing corrected p-values | | [`tvalues`](statsmodels.discrete.discrete_model.generalizedpoissonresults.tvalues#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.tvalues "statsmodels.discrete.discrete_model.GeneralizedPoissonResults.tvalues")() | Return the t-statistic for a given parameter estimate. | | [`wald_test`](statsmodels.discrete.discrete_model.generalizedpoissonresults.wald_test#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.wald_test "statsmodels.discrete.discrete_model.GeneralizedPoissonResults.wald_test")(r\_matrix[, cov\_p, scale, invcov, …]) | Compute a Wald-test for a joint linear hypothesis. | | [`wald_test_terms`](statsmodels.discrete.discrete_model.generalizedpoissonresults.wald_test_terms#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.wald_test_terms "statsmodels.discrete.discrete_model.GeneralizedPoissonResults.wald_test_terms")([skip\_single, …]) | Compute a sequence of Wald tests for terms over multiple columns | #### Attributes | | | | --- | --- | | `use_t` | | statsmodels statsmodels.sandbox.distributions.extras.ACSkewT_gen.var statsmodels.sandbox.distributions.extras.ACSkewT\_gen.var ========================================================= `ACSkewT_gen.var(*args, **kwds)` Variance of the distribution. | Parameters: | * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **var** – the variance of the distribution | | Return type: | float | statsmodels statsmodels.sandbox.tsa.fftarma.ArmaFft.generate_sample statsmodels.sandbox.tsa.fftarma.ArmaFft.generate\_sample ======================================================== `ArmaFft.generate_sample(nsample=100, scale=1.0, distrvs=None, axis=0, burnin=0)` Simulate an ARMA | Parameters: | * **nsample** (*int* *or* *tuple of ints*) – If nsample is an integer, then this creates a 1d timeseries of length size. If nsample is a tuple, creates a len(nsample) dimensional time series where time is indexed along the input variable `axis`. All series are unless `distrvs` generates dependent data. * **scale** (*float*) – standard deviation of noise * **distrvs** (*function**,* *random number generator*) – function that generates the random numbers, and takes sample size as argument default: np.random.randn TODO: change to size argument * **burnin** (*integer* *(**default: 0**)*) – to reduce the effect of initial conditions, burnin observations at the beginning of the sample are dropped * **axis** (*int*) – See nsample. | | Returns: | **rvs** – random sample(s) of arma process | | Return type: | ndarray | #### Notes Should work for n-dimensional with time series along axis, but not tested yet. Processes are sampled independently. statsmodels statsmodels.duration.survfunc.SurvfuncRight.quantile_ci statsmodels.duration.survfunc.SurvfuncRight.quantile\_ci ======================================================== `SurvfuncRight.quantile_ci(p, alpha=0.05, method='cloglog')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/duration/survfunc.html#SurvfuncRight.quantile_ci) Returns a confidence interval for a survival quantile. | Parameters: | * **p** (*float*) – The probability point for which a confidence interval is determined. * **alpha** (*float*) – The confidence interval has nominal coverage probability 1 - `alpha`. * **method** (*string*) – Function to use for g-transformation, must be … | | Returns: | * **lb** (*float*) – The lower confidence limit. * **ub** (*float*) – The upper confidence limit. | #### Notes The confidence interval is obtained by inverting Z-tests. The limits of the confidence interval will always be observed event times. #### References The method is based on the approach used in SAS, documented here: <http://support.sas.com/documentation/cdl/en/statug/68162/HTML/default/viewer.htm#statug_lifetest_details03.htm>
programming_docs
statsmodels statsmodels.discrete.discrete_model.MultinomialResults.llnull statsmodels.discrete.discrete\_model.MultinomialResults.llnull ============================================================== `MultinomialResults.llnull()` statsmodels statsmodels.discrete.discrete_model.BinaryModel statsmodels.discrete.discrete\_model.BinaryModel ================================================ `class statsmodels.discrete.discrete_model.BinaryModel(endog, exog, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#BinaryModel) #### Methods | | | | --- | --- | | [`cdf`](statsmodels.discrete.discrete_model.binarymodel.cdf#statsmodels.discrete.discrete_model.BinaryModel.cdf "statsmodels.discrete.discrete_model.BinaryModel.cdf")(X) | The cumulative distribution function of the model. | | [`cov_params_func_l1`](statsmodels.discrete.discrete_model.binarymodel.cov_params_func_l1#statsmodels.discrete.discrete_model.BinaryModel.cov_params_func_l1 "statsmodels.discrete.discrete_model.BinaryModel.cov_params_func_l1")(likelihood\_model, xopt, …) | Computes cov\_params on a reduced parameter space corresponding to the nonzero parameters resulting from the l1 regularized fit. | | [`fit`](statsmodels.discrete.discrete_model.binarymodel.fit#statsmodels.discrete.discrete_model.BinaryModel.fit "statsmodels.discrete.discrete_model.BinaryModel.fit")([start\_params, method, maxiter, …]) | Fit the model using maximum likelihood. | | [`fit_regularized`](statsmodels.discrete.discrete_model.binarymodel.fit_regularized#statsmodels.discrete.discrete_model.BinaryModel.fit_regularized "statsmodels.discrete.discrete_model.BinaryModel.fit_regularized")([start\_params, method, …]) | Fit the model using a regularized maximum likelihood. | | [`from_formula`](statsmodels.discrete.discrete_model.binarymodel.from_formula#statsmodels.discrete.discrete_model.BinaryModel.from_formula "statsmodels.discrete.discrete_model.BinaryModel.from_formula")(formula, data[, subset, drop\_cols]) | Create a Model from a formula and dataframe. | | [`hessian`](statsmodels.discrete.discrete_model.binarymodel.hessian#statsmodels.discrete.discrete_model.BinaryModel.hessian "statsmodels.discrete.discrete_model.BinaryModel.hessian")(params) | The Hessian matrix of the model | | [`information`](statsmodels.discrete.discrete_model.binarymodel.information#statsmodels.discrete.discrete_model.BinaryModel.information "statsmodels.discrete.discrete_model.BinaryModel.information")(params) | Fisher information matrix of model | | [`initialize`](statsmodels.discrete.discrete_model.binarymodel.initialize#statsmodels.discrete.discrete_model.BinaryModel.initialize "statsmodels.discrete.discrete_model.BinaryModel.initialize")() | Initialize is called by statsmodels.model.LikelihoodModel.\_\_init\_\_ and should contain any preprocessing that needs to be done for a model. | | [`loglike`](statsmodels.discrete.discrete_model.binarymodel.loglike#statsmodels.discrete.discrete_model.BinaryModel.loglike "statsmodels.discrete.discrete_model.BinaryModel.loglike")(params) | Log-likelihood of model. | | [`pdf`](statsmodels.discrete.discrete_model.binarymodel.pdf#statsmodels.discrete.discrete_model.BinaryModel.pdf "statsmodels.discrete.discrete_model.BinaryModel.pdf")(X) | The probability density (mass) function of the model. | | [`predict`](statsmodels.discrete.discrete_model.binarymodel.predict#statsmodels.discrete.discrete_model.BinaryModel.predict "statsmodels.discrete.discrete_model.BinaryModel.predict")(params[, exog, linear]) | Predict response variable of a model given exogenous variables. | | [`score`](statsmodels.discrete.discrete_model.binarymodel.score#statsmodels.discrete.discrete_model.BinaryModel.score "statsmodels.discrete.discrete_model.BinaryModel.score")(params) | Score vector of model. | #### Attributes | | | | --- | --- | | `endog_names` | Names of endogenous variables | | `exog_names` | Names of exogenous variables | statsmodels statsmodels.sandbox.distributions.transformed.ExpTransf_gen.median statsmodels.sandbox.distributions.transformed.ExpTransf\_gen.median =================================================================== `ExpTransf_gen.median(*args, **kwds)` Median of the distribution. | Parameters: | * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – Location parameter, Default is 0. * **scale** (*array\_like**,* *optional*) – Scale parameter, Default is 1. | | Returns: | **median** – The median of the distribution. | | Return type: | float | See also `stats.distributions.rv_discrete.ppf` Inverse of the CDF statsmodels statsmodels.genmod.generalized_estimating_equations.GEEMargins.summary_frame statsmodels.genmod.generalized\_estimating\_equations.GEEMargins.summary\_frame =============================================================================== `GEEMargins.summary_frame(alpha=0.05)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_estimating_equations.html#GEEMargins.summary_frame) Returns a DataFrame summarizing the marginal effects. | Parameters: | **alpha** (*float*) – Number between 0 and 1. The confidence intervals have the probability 1-alpha. | | Returns: | **frame** – A DataFrame summarizing the marginal effects. | | Return type: | DataFrames | statsmodels statsmodels.regression.recursive_ls.RecursiveLS.from_formula statsmodels.regression.recursive\_ls.RecursiveLS.from\_formula ============================================================== `classmethod RecursiveLS.from_formula(formula, data, subset=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/recursive_ls.html#RecursiveLS.from_formula) Not implemented for state space models statsmodels statsmodels.sandbox.distributions.transformed.Transf_gen.logcdf statsmodels.sandbox.distributions.transformed.Transf\_gen.logcdf ================================================================ `Transf_gen.logcdf(x, *args, **kwds)` Log of the cumulative distribution function at x of the given RV. | Parameters: | * **x** (*array\_like*) – quantiles * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **logcdf** – Log of the cumulative distribution function evaluated at x | | Return type: | array\_like | statsmodels statsmodels.tsa.holtwinters.Holt.predict statsmodels.tsa.holtwinters.Holt.predict ======================================== `Holt.predict(params, start=None, end=None)` Returns in-sample and out-of-sample prediction. | Parameters: | * **params** (*array*) – The fitted model parameters. * **start** (*int**,* *str**, or* *datetime*) – Zero-indexed observation number at which to start forecasting, ie., the first forecast is start. Can also be a date string to parse or a datetime type. * **end** (*int**,* *str**, or* *datetime*) – Zero-indexed observation number at which to end forecasting, ie., the first forecast is start. Can also be a date string to parse or a datetime type. | | Returns: | **predicted values** | | Return type: | array | statsmodels statsmodels.tsa.vector_ar.var_model.VARResults.mean statsmodels.tsa.vector\_ar.var\_model.VARResults.mean ===================================================== `VARResults.mean()` Long run intercept of stable VAR process Warning: trend and exog except for intercept are ignored for this. This might change in future versions. Lütkepohl eq. 2.1.23 \[\mu = (I - A\_1 - \dots - A\_p)^{-1} \alpha\] where alpha is the intercept (parameter of the constant) statsmodels statsmodels.regression.quantile_regression.QuantReg.score statsmodels.regression.quantile\_regression.QuantReg.score ========================================================== `QuantReg.score(params)` Score vector of model. The gradient of logL with respect to each parameter. statsmodels statsmodels.graphics.regressionplots.plot_ccpr statsmodels.graphics.regressionplots.plot\_ccpr =============================================== `statsmodels.graphics.regressionplots.plot_ccpr(results, exog_idx, ax=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/graphics/regressionplots.html#plot_ccpr) Plot CCPR against one regressor. Generates a CCPR (component and component-plus-residual) plot. | Parameters: | * **results** (*result instance*) – A regression results instance. * **exog\_idx** (*int* *or* *string*) – Exogenous, explanatory variable. If string is given, it should be the variable name that you want to use, and you can use arbitrary translations as with a formula. * **ax** (*Matplotlib AxesSubplot instance**,* *optional*) – If given, it is used to plot in instead of a new figure being created. | | Returns: | **fig** – If `ax` is None, the created figure. Otherwise the figure to which `ax` is connected. | | Return type: | Matplotlib figure instance | See also `plot_ccpr_grid` Creates CCPR plot for multiple regressors in a plot grid. #### Notes The CCPR plot provides a way to judge the effect of one regressor on the response variable by taking into account the effects of the other independent variables. The partial residuals plot is defined as Residuals + B\_i\*X\_i versus X\_i. The component adds the B\_i\*X\_i versus X\_i to show where the fitted line would lie. Care should be taken if X\_i is highly correlated with any of the other independent variables. If this is the case, the variance evident in the plot will be an underestimate of the true variance. #### References <http://www.itl.nist.gov/div898/software/dataplot/refman1/auxillar/ccpr.htm> statsmodels statsmodels.discrete.discrete_model.BinaryResults.resid_pearson statsmodels.discrete.discrete\_model.BinaryResults.resid\_pearson ================================================================= `BinaryResults.resid_pearson()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#BinaryResults.resid_pearson) Pearson residuals #### Notes Pearson residuals are defined to be \[r\_j = \frac{(y - M\_jp\_j)}{\sqrt{M\_jp\_j(1-p\_j)}}\] where \(p\_j=cdf(X\beta)\) and \(M\_j\) is the total number of observations sharing the covariate pattern \(j\). For now \(M\_j\) is always set to 1. statsmodels statsmodels.robust.robust_linear_model.RLMResults.normalized_cov_params statsmodels.robust.robust\_linear\_model.RLMResults.normalized\_cov\_params =========================================================================== `RLMResults.normalized_cov_params()` statsmodels statsmodels.imputation.mice.MICE.fit statsmodels.imputation.mice.MICE.fit ==================================== `MICE.fit(n_burnin=10, n_imputations=10)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/imputation/mice.html#MICE.fit) Fit a model using MICE. | Parameters: | * **n\_burnin** (*int*) – The number of burn-in cycles to skip. * **n\_imputations** (*int*) – The number of data sets to impute | statsmodels statsmodels.iolib.summary2.Summary statsmodels.iolib.summary2.Summary ================================== `class statsmodels.iolib.summary2.Summary` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/iolib/summary2.html#Summary) #### Methods | | | | --- | --- | | [`add_array`](statsmodels.iolib.summary2.summary.add_array#statsmodels.iolib.summary2.Summary.add_array "statsmodels.iolib.summary2.Summary.add_array")(array[, align, float\_format]) | Add the contents of a Numpy array to summary table | | [`add_base`](statsmodels.iolib.summary2.summary.add_base#statsmodels.iolib.summary2.Summary.add_base "statsmodels.iolib.summary2.Summary.add_base")(results[, alpha, float\_format, …]) | Try to construct a basic summary instance. | | [`add_df`](statsmodels.iolib.summary2.summary.add_df#statsmodels.iolib.summary2.Summary.add_df "statsmodels.iolib.summary2.Summary.add_df")(df[, index, header, float\_format, align]) | Add the contents of a DataFrame to summary table | | [`add_dict`](statsmodels.iolib.summary2.summary.add_dict#statsmodels.iolib.summary2.Summary.add_dict "statsmodels.iolib.summary2.Summary.add_dict")(d[, ncols, align, float\_format]) | Add the contents of a Dict to summary table | | [`add_text`](statsmodels.iolib.summary2.summary.add_text#statsmodels.iolib.summary2.Summary.add_text "statsmodels.iolib.summary2.Summary.add_text")(string) | Append a note to the bottom of the summary table. | | [`add_title`](statsmodels.iolib.summary2.summary.add_title#statsmodels.iolib.summary2.Summary.add_title "statsmodels.iolib.summary2.Summary.add_title")([title, results]) | Insert a title on top of the summary table. | | [`as_html`](statsmodels.iolib.summary2.summary.as_html#statsmodels.iolib.summary2.Summary.as_html "statsmodels.iolib.summary2.Summary.as_html")() | Generate HTML Summary Table | | [`as_latex`](statsmodels.iolib.summary2.summary.as_latex#statsmodels.iolib.summary2.Summary.as_latex "statsmodels.iolib.summary2.Summary.as_latex")() | Generate LaTeX Summary Table | | [`as_text`](statsmodels.iolib.summary2.summary.as_text#statsmodels.iolib.summary2.Summary.as_text "statsmodels.iolib.summary2.Summary.as_text")() | Generate ASCII Summary Table | statsmodels statsmodels.discrete.count_model.ZeroInflatedPoisson.fit_regularized statsmodels.discrete.count\_model.ZeroInflatedPoisson.fit\_regularized ====================================================================== `ZeroInflatedPoisson.fit_regularized(start_params=None, method='l1', maxiter='defined_by_method', full_output=1, disp=1, callback=None, alpha=0, trim_mode='auto', auto_trim_tol=0.01, size_trim_tol=0.0001, qc_tol=0.03, **kwargs)` Fit the model using a regularized maximum likelihood. The regularization method AND the solver used is determined by the argument method. | Parameters: | * **start\_params** (*array-like**,* *optional*) – Initial guess of the solution for the loglikelihood maximization. The default is an array of zeros. * **method** (*'l1'* *or* *'l1\_cvxopt\_cp'*) – See notes for details. * **maxiter** (*Integer* *or* *'defined\_by\_method'*) – Maximum number of iterations to perform. If ‘defined\_by\_method’, then use method defaults (see notes). * **full\_output** (*bool*) – Set to True to have all available output in the Results object’s mle\_retvals attribute. The output is dependent on the solver. See LikelihoodModelResults notes section for more information. * **disp** (*bool*) – Set to True to print convergence messages. * **fargs** (*tuple*) – Extra arguments passed to the likelihood function, i.e., loglike(x,\*args) * **callback** (*callable callback**(**xk**)*) – Called after each iteration, as callback(xk), where xk is the current parameter vector. * **retall** (*bool*) – Set to True to return list of solutions at each iteration. Available in Results object’s mle\_retvals attribute. * **alpha** (*non-negative scalar* *or* *numpy array* *(**same size as parameters**)*) – The weight multiplying the l1 penalty term * **trim\_mode** (*'auto**,* *'size'**, or* *'off'*) – If not ‘off’, trim (set to zero) parameters that would have been zero if the solver reached the theoretical minimum. If ‘auto’, trim params using the Theory above. If ‘size’, trim params if they have very small absolute value * **size\_trim\_tol** (*float* *or* *'auto'* *(**default = 'auto'**)*) – For use when trim\_mode == ‘size’ * **auto\_trim\_tol** (*float*) – For sue when trim\_mode == ‘auto’. Use * **qc\_tol** (*float*) – Print warning and don’t allow auto trim when (ii) (above) is violated by this much. * **qc\_verbose** (*Boolean*) – If true, print out a full QC report upon failure | #### Notes Extra parameters are not penalized if alpha is given as a scalar. An example is the shape parameter in NegativeBinomial `nb1` and `nb2`. Optional arguments for the solvers (available in Results.mle\_settings): ``` 'l1' acc : float (default 1e-6) Requested accuracy as used by slsqp 'l1_cvxopt_cp' abstol : float absolute accuracy (default: 1e-7). reltol : float relative accuracy (default: 1e-6). feastol : float tolerance for feasibility conditions (default: 1e-7). refinement : int number of iterative refinement steps when solving KKT equations (default: 1). ``` Optimization methodology With \(L\) the negative log likelihood, we solve the convex but non-smooth problem \[\min\_\beta L(\beta) + \sum\_k\alpha\_k |\beta\_k|\] via the transformation to the smooth, convex, constrained problem in twice as many variables (adding the “added variables” \(u\_k\)) \[\min\_{\beta,u} L(\beta) + \sum\_k\alpha\_k u\_k,\] subject to \[-u\_k \leq \beta\_k \leq u\_k.\] With \(\partial\_k L\) the derivative of \(L\) in the \(k^{th}\) parameter direction, theory dictates that, at the minimum, exactly one of two conditions holds: 1. \(|\partial\_k L| = \alpha\_k\) and \(\beta\_k \neq 0\) 2. \(|\partial\_k L| \leq \alpha\_k\) and \(\beta\_k = 0\) statsmodels statsmodels.tsa.arima_model.ARIMAResults.arroots statsmodels.tsa.arima\_model.ARIMAResults.arroots ================================================= `ARIMAResults.arroots()` statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.fittedvalues statsmodels.sandbox.regression.gmm.IVRegressionResults.fittedvalues =================================================================== `IVRegressionResults.fittedvalues()` statsmodels statsmodels.robust.norms.LeastSquares statsmodels.robust.norms.LeastSquares ===================================== `class statsmodels.robust.norms.LeastSquares` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/norms.html#LeastSquares) Least squares rho for M-estimation and its derived functions. See also [`statsmodels.robust.norms.RobustNorm`](statsmodels.robust.norms.robustnorm#statsmodels.robust.norms.RobustNorm "statsmodels.robust.norms.RobustNorm") #### Methods | | | | --- | --- | | [`psi`](statsmodels.robust.norms.leastsquares.psi#statsmodels.robust.norms.LeastSquares.psi "statsmodels.robust.norms.LeastSquares.psi")(z) | The psi function for the least squares estimator | | [`psi_deriv`](statsmodels.robust.norms.leastsquares.psi_deriv#statsmodels.robust.norms.LeastSquares.psi_deriv "statsmodels.robust.norms.LeastSquares.psi_deriv")(z) | The derivative of the least squares psi function. | | [`rho`](statsmodels.robust.norms.leastsquares.rho#statsmodels.robust.norms.LeastSquares.rho "statsmodels.robust.norms.LeastSquares.rho")(z) | The least squares estimator rho function | | [`weights`](statsmodels.robust.norms.leastsquares.weights#statsmodels.robust.norms.LeastSquares.weights "statsmodels.robust.norms.LeastSquares.weights")(z) | The least squares estimator weighting function for the IRLS algorithm. | statsmodels statsmodels.robust.norms.TrimmedMean.weights statsmodels.robust.norms.TrimmedMean.weights ============================================ `TrimmedMean.weights(z)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/norms.html#TrimmedMean.weights) Least trimmed mean weighting function for the IRLS algorithm The psi function scaled by z | Parameters: | **z** (*array-like*) – 1d array | | Returns: | **weights** – weights(z) = 1 for |z| <= cweights(z) = 0 for |z| > c | | Return type: | array | statsmodels statsmodels.regression.mixed_linear_model.MixedLM.hessian statsmodels.regression.mixed\_linear\_model.MixedLM.hessian =========================================================== `MixedLM.hessian(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/mixed_linear_model.html#MixedLM.hessian) Returns the model’s Hessian matrix. Calculates the Hessian matrix for the linear mixed effects model with respect to the parameterization in which the covariance matrix is represented directly (without square-root transformation). | Parameters: | **params** (*MixedLMParams* *or* *array-like*) – The model parameters at which the Hessian is calculated. If array-like, must contain the packed parameters in a form that is compatible with this model instance. | | Returns: | **hess** – The Hessian matrix, evaluated at `params`. | | Return type: | 2d ndarray |
programming_docs
statsmodels statsmodels.genmod.generalized_linear_model.GLMResults.llnull statsmodels.genmod.generalized\_linear\_model.GLMResults.llnull =============================================================== `GLMResults.llnull()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_linear_model.html#GLMResults.llnull) statsmodels statsmodels.graphics.functional.hdrboxplot statsmodels.graphics.functional.hdrboxplot ========================================== `statsmodels.graphics.functional.hdrboxplot(data, ncomp=2, alpha=None, threshold=0.95, bw=None, xdata=None, labels=None, ax=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/graphics/functional.html#hdrboxplot) High Density Region boxplot | Parameters: | * **data** (*sequence of ndarrays* *or* *2-D ndarray*) – The vectors of functions to create a functional boxplot from. If a sequence of 1-D arrays, these should all be the same size. The first axis is the function index, the second axis the one along which the function is defined. So `data[0, :]` is the first functional curve. * **ncomp** (*int**,* *optional*) – Number of components to use. If None, returns the as many as the smaller of the number of rows or columns in data. * **alpha** (*list of floats between 0 and 1**,* *optional*) – Extra quantile values to compute. Default is None * **threshold** (*float between 0 and 1**,* *optional*) – Percentile threshold value for outliers detection. High value means a lower sensitivity to outliers. Default is `0.95`. * **bw** (*array\_like* *or* *str**,* *optional*) – If an array, it is a fixed user-specified bandwidth. If `None`, set to `normal_reference`. If a string, should be one of: + normal\_reference: normal reference rule of thumb (default) + cv\_ml: cross validation maximum likelihood + cv\_ls: cross validation least squares * **xdata** (*ndarray**,* *optional*) – The independent variable for the data. If not given, it is assumed to be an array of integers 0..N-1 with N the length of the vectors in `data`. * **labels** (*sequence of scalar* *or* *str**,* *optional*) – The labels or identifiers of the curves in `data`. If not given, outliers are labeled in the plot with array indices. * **ax** (*Matplotlib AxesSubplot instance**,* *optional*) – If given, this subplot is used to plot in instead of a new figure being created. | | Returns: | * **fig** (*Matplotlib figure instance*) – If `ax` is None, the created figure. Otherwise the figure to which `ax` is connected. * **hdr\_res** (*HdrResults instance*) – An `HdrResults` instance with the following attributes: + ’median’, array. Median curve. + ’hdr\_50’, array. 50% quantile band. [sup, inf] curves + ’hdr\_90’, list of array. 90% quantile band. [sup, inf] curves. + ’extra\_quantiles’, list of array. Extra quantile band. [sup, inf] curves. + ’outliers’, ndarray. Outlier curves. | #### Notes The median curve is the curve with the highest probability on the reduced space of a Principal Component Analysis (PCA). Outliers are defined as curves that fall outside the band corresponding to the quantile given by `threshold`. The non-outlying region is defined as the band made up of all the non-outlying curves. Behind the scene, the dataset is represented as a matrix. Each line corresponding to a 1D curve. This matrix is then decomposed using Principal Components Analysis (PCA). This allows to represent the data using a finite number of modes, or components. This compression process allows to turn the functional representation into a scalar representation of the matrix. In other words, you can visualize each curve from its components. Each curve is thus a point in this reduced space. With 2 components, this is called a bivariate plot (2D plot). In this plot, if some points are adjacent (similar components), it means that back in the original space, the curves are similar. Then, finding the median curve means finding the higher density region (HDR) in the reduced space. Moreover, the more you get away from this HDR, the more the curve is unlikely to be similar to the other curves. Using a kernel smoothing technique, the probability density function (PDF) of the multivariate space can be recovered. From this PDF, it is possible to compute the density probability linked to the cluster of points and plot its contours. Finally, using these contours, the different quantiles can be extracted along with the median curve and the outliers. Steps to produce the HDR boxplot include: 1. Compute a multivariate kernel density estimation 2. Compute contour lines for quantiles 90%, 50% and `alpha` % 3. Plot the bivariate plot 4. Compute median curve along with quantiles and outliers curves. #### References [1] R.J. Hyndman and H.L. Shang, “Rainbow Plots, Bagplots, and Boxplots for Functional Data”, vol. 19, pp. 29-45, 2010. #### Examples Load the El Nino dataset. Consists of 60 years worth of Pacific Ocean sea surface temperature data. ``` >>> import matplotlib.pyplot as plt >>> import statsmodels.api as sm >>> data = sm.datasets.elnino.load() ``` Create a functional boxplot. We see that the years 1982-83 and 1997-98 are outliers; these are the years where El Nino (a climate pattern characterized by warming up of the sea surface and higher air pressures) occurred with unusual intensity. ``` >>> fig = plt.figure() >>> ax = fig.add_subplot(111) >>> res = sm.graphics.hdrboxplot(data.raw_data[:, 1:], ... labels=data.raw_data[:, 0].astype(int), ... ax=ax) ``` ``` >>> ax.set_xlabel("Month of the year") >>> ax.set_ylabel("Sea surface temperature (C)") >>> ax.set_xticks(np.arange(13, step=3) - 1) >>> ax.set_xticklabels(["", "Mar", "Jun", "Sep", "Dec"]) >>> ax.set_xlim([-0.2, 11.2]) ``` ``` >>> plt.show() ``` ([Source code](../plots/graphics_functional_hdrboxplot.py), [png](../plots/graphics_functional_hdrboxplot_00_00.png), [hires.png](../plots/graphics_functional_hdrboxplot_00_00.hires.png), [pdf](../plots/graphics_functional_hdrboxplot_00_00.pdf)) See also [`banddepth`](statsmodels.graphics.functional.banddepth#statsmodels.graphics.functional.banddepth "statsmodels.graphics.functional.banddepth"), [`rainbowplot`](statsmodels.graphics.functional.rainbowplot#statsmodels.graphics.functional.rainbowplot "statsmodels.graphics.functional.rainbowplot"), [`fboxplot`](statsmodels.graphics.functional.fboxplot#statsmodels.graphics.functional.fboxplot "statsmodels.graphics.functional.fboxplot") statsmodels statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.smooth statsmodels.tsa.regime\_switching.markov\_regression.MarkovRegression.smooth ============================================================================ `MarkovRegression.smooth(params, transformed=True, cov_type=None, cov_kwds=None, return_raw=False, results_class=None, results_wrapper_class=None)` Apply the Kim smoother and Hamilton filter | Parameters: | * **params** (*array\_like*) – Array of parameters at which to perform filtering. * **transformed** (*boolean**,* *optional*) – Whether or not `params` is already transformed. Default is True. * **cov\_type** (*str**,* *optional*) – See `fit` for a description of covariance matrix types for results object. * **cov\_kwds** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)") *or* *None**,* *optional*) – See `fit` for a description of required keywords for alternative covariance estimators * **return\_raw** (*boolean**,**optional*) – Whether or not to return only the raw Hamilton filter output or a full results object. Default is to return a full results object. * **results\_class** (*type**,* *optional*) – A results class to instantiate rather than `MarkovSwitchingResults`. Usually only used internally by subclasses. * **results\_wrapper\_class** (*type**,* *optional*) – A results wrapper class to instantiate rather than `MarkovSwitchingResults`. Usually only used internally by subclasses. | | Returns: | | | Return type: | MarkovSwitchingResults | statsmodels statsmodels.sandbox.distributions.transformed.ExpTransf_gen.nnlf statsmodels.sandbox.distributions.transformed.ExpTransf\_gen.nnlf ================================================================= `ExpTransf_gen.nnlf(theta, x)` Return negative loglikelihood function. #### Notes This is `-sum(log pdf(x, theta), axis=0)` where `theta` are the parameters (including loc and scale). statsmodels statsmodels.tsa.statespace.mlemodel.MLEModel.smooth statsmodels.tsa.statespace.mlemodel.MLEModel.smooth =================================================== `MLEModel.smooth(params, transformed=True, complex_step=False, cov_type=None, cov_kwds=None, return_ssm=False, results_class=None, results_wrapper_class=None, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEModel.smooth) Kalman smoothing | Parameters: | * **params** (*array\_like*) – Array of parameters at which to evaluate the loglikelihood function. * **transformed** (*boolean**,* *optional*) – Whether or not `params` is already transformed. Default is True. * **return\_ssm** (*boolean**,**optional*) – Whether or not to return only the state space output or a full results object. Default is to return a full results object. * **cov\_type** (*str**,* *optional*) – See `MLEResults.fit` for a description of covariance matrix types for results object. * **cov\_kwds** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)") *or* *None**,* *optional*) – See `MLEResults.get_robustcov_results` for a description required keywords for alternative covariance estimators * **\*\*kwargs** – Additional keyword arguments to pass to the Kalman filter. See `KalmanFilter.filter` for more details. | statsmodels statsmodels.stats.contingency_tables.Table.test_nominal_association statsmodels.stats.contingency\_tables.Table.test\_nominal\_association ====================================================================== `Table.test_nominal_association()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table.test_nominal_association) Assess independence for nominal factors. Assessment of independence between rows and columns using chi^2 testing. The rows and columns are treated as nominal (unordered) categorical variables. | Returns: | * *A bunch containing the following attributes* * **statistic** (*float*) – The chi^2 test statistic. * **df** (*integer*) – The degrees of freedom of the reference distribution * **pvalue** (*float*) – The p-value for the test. | statsmodels statsmodels.tsa.statespace.structural.UnobservedComponents.hessian statsmodels.tsa.statespace.structural.UnobservedComponents.hessian ================================================================== `UnobservedComponents.hessian(params, *args, **kwargs)` Hessian matrix of the likelihood function, evaluated at the given parameters | Parameters: | * **params** (*array\_like*) – Array of parameters at which to evaluate the hessian. * **args** – Additional positional arguments to the `loglike` method. * **kwargs** – Additional keyword arguments to the `loglike` method. | | Returns: | **hessian** – Hessian matrix evaluated at `params` | | Return type: | array | #### Notes This is a numerical approximation. Both \*args and \*\*kwargs are necessary because the optimizer from `fit` must call this function and only supports passing arguments via \*args (for example `scipy.optimize.fmin_l_bfgs`). statsmodels statsmodels.stats.outliers_influence.OLSInfluence.dffits_internal statsmodels.stats.outliers\_influence.OLSInfluence.dffits\_internal =================================================================== `OLSInfluence.dffits_internal()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/outliers_influence.html#OLSInfluence.dffits_internal) (cached attribute) dffits measure for influence of an observation based on resid\_studentized\_internal uses original results, no nobs loop statsmodels statsmodels.robust.norms.Hampel.psi statsmodels.robust.norms.Hampel.psi =================================== `Hampel.psi(z)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/norms.html#Hampel.psi) The psi function for Hampel’s estimator The analytic derivative of rho | Parameters: | **z** (*array-like*) – 1d array | | Returns: | **psi** – psi(z) = z for |z| <= apsi(z) = a\*sign(z) for a < |z| <= b psi(z) = a\*sign(z)\*(c - |z|)/(c-b) for b < |z| <= c psi(z) = 0 for |z| > c | | Return type: | array | statsmodels statsmodels.stats.weightstats.DescrStatsW.quantile statsmodels.stats.weightstats.DescrStatsW.quantile ================================================== `DescrStatsW.quantile(probs, return_pandas=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/weightstats.html#DescrStatsW.quantile) Compute quantiles for a weighted sample. | Parameters: | * **probs** (*array-like*) – A vector of probability points at which to calculate the quantiles. Each element of `probs` should fall in [0, 1]. * **return\_pandas** (*bool*) – If True, return value is a Pandas DataFrame or Series. Otherwise returns a ndarray. | | Returns: | **quantiles** – `If return_pandas = True, returns one of the following:` * data are 1d, `return_pandas` = True: a Series indexed by the probability points. * data are 2d, `return_pandas` = True: a DataFrame with the probability points as row index and the variables as column index. If `return_pandas` = False, returns an ndarray containing the same values as the Series/DataFrame. | | Return type: | Series, DataFrame, or ndarray | #### Notes To compute the quantiles, first, the weights are summed over exact ties yielding distinct data values y\_1 < y\_2 < …, and corresponding weights w\_1, w\_2, …. Let s\_j denote the sum of the first j weights, and let W denote the sum of all the weights. For a probability point p, if pW falls strictly between s\_j and s\_{j+1} then the estimated quantile is y\_{j+1}. If pW = s\_j then the estimated quantile is (y\_j + y\_{j+1})/2. If pW < p\_1 then the estimated quantile is y\_1. #### References SAS documentation for weighted quantiles: <https://support.sas.com/documentation/cdl/en/procstat/63104/HTML/default/viewer.htm#procstat_univariate_sect028.htm> statsmodels statsmodels.sandbox.tsa.fftarma.ArmaFft.invertroots statsmodels.sandbox.tsa.fftarma.ArmaFft.invertroots =================================================== `ArmaFft.invertroots(retnew=False)` Make MA polynomial invertible by inverting roots inside unit circle | Parameters: | **retnew** (*boolean*) – If False (default), then return the lag-polynomial as array. If True, then return a new instance with invertible MA-polynomial | | Returns: | * **manew** (*array*) – new invertible MA lag-polynomial, returned if retnew is false. * **wasinvertible** (*boolean*) – True if the MA lag-polynomial was already invertible, returned if retnew is false. * **armaprocess** (*new instance of class*) – If retnew is true, then return a new instance with invertible MA-polynomial | statsmodels statsmodels.sandbox.regression.gmm.IVGMM.fit statsmodels.sandbox.regression.gmm.IVGMM.fit ============================================ `IVGMM.fit(start_params=None, maxiter=10, inv_weights=None, weights_method='cov', wargs=(), has_optimal_weights=True, optim_method='bfgs', optim_args=None)` Estimate parameters using GMM and return GMMResults TODO: weight and covariance arguments still need to be made consistent with similar options in other models, see RegressionResult.get\_robustcov\_results | Parameters: | * **start\_params** (*array* *(**optional**)*) – starting value for parameters ub minimization. If None then fitstart method is called for the starting values. * **maxiter** (*int* *or* *'cue'*) – Number of iterations in iterated GMM. The onestep estimate can be obtained with maxiter=0 or 1. If maxiter is large, then the iteration will stop either at maxiter or on convergence of the parameters (TODO: no options for convergence criteria yet.) If `maxiter == ‘cue’`, the the continuously updated GMM is calculated which updates the weight matrix during the minimization of the GMM objective function. The CUE estimation uses the onestep parameters as starting values. * **inv\_weights** (*None* *or* *ndarray*) – inverse of the starting weighting matrix. If inv\_weights are not given then the method `start_weights` is used which depends on the subclass, for IV subclasses `inv_weights = z’z` where `z` are the instruments, otherwise an identity matrix is used. * **weights\_method** (*string**,* *defines method for robust*) – Options here are similar to `statsmodels.stats.robust_covariance` default is heteroscedasticity consistent, HC0 currently available methods are + `cov` : HC0, optionally with degrees of freedom correction + `hac` : + `iid` : untested, only for Z\*u case, IV cases with u as error indep of Z + `ac` : not available yet + `cluster` : not connected yet + others from robust\_covariance * **wargs`** (*tuple* *or* [dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")*,*) – required and optional arguments for weights\_method + `centered` : bool, indicates whether moments are centered for the calculation of the weights and covariance matrix, applies to all weight\_methods + `ddof` : int degrees of freedom correction, applies currently only to `cov` + `maxlag` : int number of lags to include in HAC calculation , applies only to `hac` + others not yet, e.g. groups for cluster robust * **has\_optimal\_weights** (*If true**,* *then the calculation of the covariance*) – matrix assumes that we have optimal GMM with \(W = S^{-1}\). Default is True. TODO: do we want to have a different default after `onestep`? * **optim\_method** (*string**,* *default is 'bfgs'*) – numerical optimization method. Currently not all optimizers that are available in LikelihoodModels are connected. * **optim\_args** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")) – keyword arguments for the numerical optimizer. | | Returns: | **results** – this is also attached as attribute results | | Return type: | instance of GMMResults | #### Notes Warning: One-step estimation, `maxiter` either 0 or 1, still has problems (at least compared to Stata’s gmm). By default it uses a heteroscedasticity robust covariance matrix, but uses the assumption that the weight matrix is optimal. See options for cov\_params in the results instance. The same options as for weight matrix also apply to the calculation of the estimate of the covariance matrix of the parameter estimates. statsmodels statsmodels.tsa.statespace.varmax.VARMAXResults.cov_params_opg statsmodels.tsa.statespace.varmax.VARMAXResults.cov\_params\_opg ================================================================ `VARMAXResults.cov_params_opg()` (array) The variance / covariance matrix. Computed using the outer product of gradients method. statsmodels statsmodels.miscmodels.count.PoissonZiGMLE.loglike statsmodels.miscmodels.count.PoissonZiGMLE.loglike ================================================== `PoissonZiGMLE.loglike(params)` Log-likelihood of model. statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.predict statsmodels.tsa.statespace.dynamic\_factor.DynamicFactor.predict ================================================================ `DynamicFactor.predict(params, exog=None, *args, **kwargs)` After a model has been fit predict returns the fitted values. This is a placeholder intended to be overwritten by individual models. statsmodels statsmodels.tsa.statespace.sarimax.SARIMAX.set_inversion_method statsmodels.tsa.statespace.sarimax.SARIMAX.set\_inversion\_method ================================================================= `SARIMAX.set_inversion_method(inversion_method=None, **kwargs)` Set the inversion method The Kalman filter may contain one matrix inversion: that of the forecast error covariance matrix. The inversion method controls how and if that inverse is performed. | Parameters: | * **inversion\_method** (*integer**,* *optional*) – Bitmask value to set the inversion method to. See notes for details. * **\*\*kwargs** – Keyword arguments may be used to influence the inversion method by setting individual boolean flags. See notes for details. | #### Notes This method is rarely used. See the corresponding function in the `KalmanFilter` class for details.
programming_docs
statsmodels statsmodels.regression.recursive_ls.RecursiveLS.initialize_known statsmodels.regression.recursive\_ls.RecursiveLS.initialize\_known ================================================================== `RecursiveLS.initialize_known(initial_state, initial_state_cov)` statsmodels statsmodels.sandbox.regression.gmm.NonlinearIVGMM.get_error statsmodels.sandbox.regression.gmm.NonlinearIVGMM.get\_error ============================================================ `NonlinearIVGMM.get_error(params)` statsmodels statsmodels.stats.diagnostic.recursive_olsresiduals statsmodels.stats.diagnostic.recursive\_olsresiduals ==================================================== `statsmodels.stats.diagnostic.recursive_olsresiduals(olsresults, skip=None, lamda=0.0, alpha=0.95)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/diagnostic.html#recursive_olsresiduals) calculate recursive ols with residuals and cusum test statistic | Parameters: | * **olsresults** (*instance of RegressionResults*) – uses only endog and exog * **skip** (*int* *or* *None*) – number of observations to use for initial OLS, if None then skip is set equal to the number of regressors (columns in exog) * **lamda** (*float*) – weight for Ridge correction to initial (X’X)^{-1} * **alpha** (*{0.95**,* *0.99}*) – confidence level of test, currently only two values supported, used for confidence interval in cusum graph | | Returns: | * **rresid** (*array*) – recursive ols residuals * **rparams** (*array*) – recursive ols parameter estimates * **rypred** (*array*) – recursive prediction of endogenous variable * **rresid\_standardized** (*array*) – recursive residuals standardized so that N(0,sigma2) distributed, where sigma2 is the error variance * **rresid\_scaled** (*array*) – recursive residuals normalize so that N(0,1) distributed * **rcusum** (*array*) – cumulative residuals for cusum test * **rcusumci** (*array*) – confidence interval for cusum test, currently hard coded for alpha=0.95 | #### Notes It produces same recursive residuals as other version. This version updates the inverse of the X’X matrix and does not require matrix inversion during updating. looks efficient but no timing Confidence interval in Greene and Brown, Durbin and Evans is the same as in Ploberger after a little bit of algebra. #### References jplv to check formulas, follows Harvey BigJudge 5.5.2b for formula for inverse(X’X) updating Greene section 7.5.2 Brown, R. L., J. Durbin, and J. M. Evans. “Techniques for Testing the Constancy of Regression Relationships over Time.” Journal of the Royal Statistical Society. Series B (Methodological) 37, no. 2 (1975): 149-192. statsmodels statsmodels.tsa.statespace.mlemodel.MLEResults.conf_int statsmodels.tsa.statespace.mlemodel.MLEResults.conf\_int ======================================================== `MLEResults.conf_int(alpha=0.05, cols=None, method='default')` Returns the confidence interval of the fitted parameters. | Parameters: | * **alpha** (*float**,* *optional*) – The significance level for the confidence interval. ie., The default `alpha` = .05 returns a 95% confidence interval. * **cols** (*array-like**,* *optional*) – `cols` specifies which confidence intervals to return * **method** (*string*) – Not Implemented Yet Method to estimate the confidence\_interval. “Default” : uses self.bse which is based on inverse Hessian for MLE “hjjh” : “jac” : “boot-bse” “boot\_quant” “profile” | | Returns: | **conf\_int** – Each row contains [lower, upper] limits of the confidence interval for the corresponding parameter. The first column contains all lower, the second column contains all upper limits. | | Return type: | array | #### Examples ``` >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> results.conf_int() array([[-5496529.48322745, -1467987.78596704], [ -177.02903529, 207.15277984], [ -0.1115811 , 0.03994274], [ -3.12506664, -0.91539297], [ -1.5179487 , -0.54850503], [ -0.56251721, 0.460309 ], [ 798.7875153 , 2859.51541392]]) ``` ``` >>> results.conf_int(cols=(2,3)) array([[-0.1115811 , 0.03994274], [-3.12506664, -0.91539297]]) ``` #### Notes The confidence interval is based on the standard normal distribution. Models wish to use a different distribution should overwrite this method. statsmodels statsmodels.robust.norms.AndrewWave.psi statsmodels.robust.norms.AndrewWave.psi ======================================= `AndrewWave.psi(z)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/norms.html#AndrewWave.psi) The psi function for Andrew’s wave The analytic derivative of rho | Parameters: | **z** (*array-like*) – 1d array | | Returns: | **psi** – psi(z) = sin(z/a) for |z| <= a\*pipsi(z) = 0 for |z| > a\*pi | | Return type: | array | statsmodels statsmodels.discrete.discrete_model.GeneralizedPoissonResults.t_test_pairwise statsmodels.discrete.discrete\_model.GeneralizedPoissonResults.t\_test\_pairwise ================================================================================ `GeneralizedPoissonResults.t_test_pairwise(term_name, method='hs', alpha=0.05, factor_labels=None)` perform pairwise t\_test with multiple testing corrected p-values This uses the formula design\_info encoding contrast matrix and should work for all encodings of a main effect. | Parameters: | * **result** (*result instance*) – The results of an estimated model with a categorical main effect. * **term\_name** (*str*) – name of the term for which pairwise comparisons are computed. Term names for categorical effects are created by patsy and correspond to the main part of the exog names. * **method** (*str* *or* *list of strings*) – multiple testing p-value correction, default is ‘hs’, see stats.multipletesting * **alpha** (*float*) – significance level for multiple testing reject decision. * **factor\_labels** (*None**,* *list of str*) – Labels for the factor levels used for pairwise labels. If not provided, then the labels from the formula design\_info are used. | | Returns: | **results** – The results are stored as attributes, the main attributes are the following two. Other attributes are added for debugging purposes or as background information.* result\_frame : pandas DataFrame with t\_test results and multiple testing corrected p-values. * contrasts : matrix of constraints of the null hypothesis in the t\_test. | | Return type: | instance of a simple Results class | #### Notes Status: experimental. Currently only checked for treatment coding with and without specified reference level. Currently there are no multiple testing corrected confidence intervals available. #### Examples ``` >>> res = ols("np.log(Days+1) ~ C(Weight) + C(Duration)", data).fit() >>> pw = res.t_test_pairwise("C(Weight)") >>> pw.result_frame coef std err t P>|t| Conf. Int. Low 2-1 0.632315 0.230003 2.749157 8.028083e-03 0.171563 3-1 1.302555 0.230003 5.663201 5.331513e-07 0.841803 3-2 0.670240 0.230003 2.914044 5.119126e-03 0.209488 Conf. Int. Upp. pvalue-hs reject-hs 2-1 1.093067 0.010212 True 3-1 1.763307 0.000002 True 3-2 1.130992 0.010212 True ``` statsmodels statsmodels.discrete.discrete_model.NegativeBinomialP.cdf statsmodels.discrete.discrete\_model.NegativeBinomialP.cdf ========================================================== `NegativeBinomialP.cdf(X)` The cumulative distribution function of the model. statsmodels statsmodels.discrete.discrete_model.NegativeBinomialResults.wald_test_terms statsmodels.discrete.discrete\_model.NegativeBinomialResults.wald\_test\_terms ============================================================================== `NegativeBinomialResults.wald_test_terms(skip_single=False, extra_constraints=None, combine_terms=None)` Compute a sequence of Wald tests for terms over multiple columns This computes joined Wald tests for the hypothesis that all coefficients corresponding to a `term` are zero. `Terms` are defined by the underlying formula or by string matching. | Parameters: | * **skip\_single** (*boolean*) – If true, then terms that consist only of a single column and, therefore, refers only to a single parameter is skipped. If false, then all terms are included. * **extra\_constraints** (*ndarray*) – not tested yet * **combine\_terms** (*None* *or* *list of strings*) – Each string in this list is matched to the name of the terms or the name of the exogenous variables. All columns whose name includes that string are combined in one joint test. | | Returns: | **test\_result** – The result instance contains `table` which is a pandas DataFrame with the test results: test statistic, degrees of freedom and pvalues. | | Return type: | result instance | #### Examples ``` >>> res_ols = ols("np.log(Days+1) ~ C(Duration, Sum)*C(Weight, Sum)", data).fit() >>> res_ols.wald_test_terms() <class 'statsmodels.stats.contrast.WaldTestResults'> F P>F df constraint df denom Intercept 279.754525 2.37985521351e-22 1 51 C(Duration, Sum) 5.367071 0.0245738436636 1 51 C(Weight, Sum) 12.432445 3.99943118767e-05 2 51 C(Duration, Sum):C(Weight, Sum) 0.176002 0.83912310946 2 51 ``` ``` >>> res_poi = Poisson.from_formula("Days ~ C(Weight) * C(Duration)", data).fit(cov_type='HC0') >>> wt = res_poi.wald_test_terms(skip_single=False, combine_terms=['Duration', 'Weight']) >>> print(wt) chi2 P>chi2 df constraint Intercept 15.695625 7.43960374424e-05 1 C(Weight) 16.132616 0.000313940174705 2 C(Duration) 1.009147 0.315107378931 1 C(Weight):C(Duration) 0.216694 0.897315972824 2 Duration 11.187849 0.010752286833 3 Weight 30.263368 4.32586407145e-06 4 ``` statsmodels statsmodels.tsa.statespace.sarimax.SARIMAXResults.cov_params_robust_oim statsmodels.tsa.statespace.sarimax.SARIMAXResults.cov\_params\_robust\_oim ========================================================================== `SARIMAXResults.cov_params_robust_oim()` (array) The QMLE variance / covariance matrix. Computed using the method from Harvey (1989) as the evaluated hessian. statsmodels statsmodels.tsa.statespace.mlemodel.MLEResults.cov_params_approx statsmodels.tsa.statespace.mlemodel.MLEResults.cov\_params\_approx ================================================================== `MLEResults.cov_params_approx()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEResults.cov_params_approx) (array) The variance / covariance matrix. Computed using the numerical Hessian approximated by complex step or finite differences methods. statsmodels statsmodels.tsa.statespace.structural.UnobservedComponents.initialize_stationary statsmodels.tsa.statespace.structural.UnobservedComponents.initialize\_stationary ================================================================================= `UnobservedComponents.initialize_stationary()` statsmodels statsmodels.regression.linear_model.OLSResults.initialize statsmodels.regression.linear\_model.OLSResults.initialize ========================================================== `OLSResults.initialize(model, params, **kwd)` statsmodels statsmodels.sandbox.distributions.extras.NormExpan_gen.var statsmodels.sandbox.distributions.extras.NormExpan\_gen.var =========================================================== `NormExpan_gen.var(*args, **kwds)` Variance of the distribution. | Parameters: | * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **var** – the variance of the distribution | | Return type: | float | statsmodels statsmodels.tsa.varma_process.VarmaPoly.vstackarma_minus1 statsmodels.tsa.varma\_process.VarmaPoly.vstackarma\_minus1 =========================================================== `VarmaPoly.vstackarma_minus1()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/varma_process.html#VarmaPoly.vstackarma_minus1) stack ar and lagpolynomial vertically in 2d array statsmodels statsmodels.genmod.families.links.inverse_power.inverse statsmodels.genmod.families.links.inverse\_power.inverse ======================================================== `inverse_power.inverse(z)` Inverse of the power transform link function | Parameters: | **z** (*array-like*) – Value of the transformed mean parameters at `p` | | Returns: | **`p`** – Mean parameters | | Return type: | array | #### Notes g^(-1)(z`) = `z`**(1/`power`) statsmodels statsmodels.sandbox.regression.gmm.IVGMM.fitstart statsmodels.sandbox.regression.gmm.IVGMM.fitstart ================================================= `IVGMM.fitstart()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#IVGMM.fitstart) statsmodels statsmodels.regression.linear_model.WLS.loglike statsmodels.regression.linear\_model.WLS.loglike ================================================ `WLS.loglike(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#WLS.loglike) Returns the value of the gaussian log-likelihood function at params. Given the whitened design matrix, the log-likelihood is evaluated at the parameter vector `params` for the dependent variable `Y`. | Parameters: | **params** (*array-like*) – The parameter estimates. | | Returns: | **llf** – The value of the log-likelihood function for a WLS Model. | | Return type: | float | #### Notes \[-\frac{n}{2}\log\left(Y-\hat{Y}\right)-\frac{n}{2}\left(1+\log\left(\frac{2\pi}{n}\right)\right)-\frac{1}{2}log\left(\left|W\right|\right)\] where \(W\) is a diagonal matrix statsmodels statsmodels.stats.contingency_tables.Table2x2.symmetry statsmodels.stats.contingency\_tables.Table2x2.symmetry ======================================================= `Table2x2.symmetry(method='bowker')` Test for symmetry of a joint distribution. This procedure tests the null hypothesis that the joint distribution is symmetric around the main diagonal, that is \[\] p\_{i, j} = p\_{j, i} for all i, j | Returns: | * *A bunch with attributes* * **statistic** (*float*) – chisquare test statistic * **p-value** (*float*) – p-value of the test statistic based on chisquare distribution * **df** (*int*) – degrees of freedom of the chisquare distribution | #### Notes The implementation is based on the SAS documentation. R includes it in `mcnemar.test` if the table is not 2 by 2. However a more direct generalization of the McNemar test to larger tables is provided by the homogeneity test (TableSymmetry.homogeneity). The p-value is based on the chi-square distribution which requires that the sample size is not very small to be a good approximation of the true distribution. For 2x2 contingency tables the exact distribution can be obtained with `mcnemar` See also [`mcnemar`](statsmodels.stats.contingency_tables.mcnemar#statsmodels.stats.contingency_tables.mcnemar "statsmodels.stats.contingency_tables.mcnemar"), [`homogeneity`](statsmodels.stats.contingency_tables.table2x2.homogeneity#statsmodels.stats.contingency_tables.Table2x2.homogeneity "statsmodels.stats.contingency_tables.Table2x2.homogeneity") statsmodels statsmodels.discrete.discrete_model.DiscreteResults.load statsmodels.discrete.discrete\_model.DiscreteResults.load ========================================================= `classmethod DiscreteResults.load(fname)` load a pickle, (class method) | Parameters: | **fname** (*string* *or* *filehandle*) – fname can be a string to a file path or filename, or a filehandle. | | Returns: | | | Return type: | unpickled instance | statsmodels statsmodels.discrete.discrete_model.MultinomialResults.tvalues statsmodels.discrete.discrete\_model.MultinomialResults.tvalues =============================================================== `MultinomialResults.tvalues()` Return the t-statistic for a given parameter estimate. statsmodels statsmodels.duration.hazard_regression.PHReg.from_formula statsmodels.duration.hazard\_regression.PHReg.from\_formula =========================================================== `classmethod PHReg.from_formula(formula, data, status=None, entry=None, strata=None, offset=None, subset=None, ties='breslow', missing='drop', *args, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/duration/hazard_regression.html#PHReg.from_formula) Create a proportional hazards regression 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. * **status** (*array-like*) – The censoring status values; status=1 indicates that an event occured (e.g. failure or death), status=0 indicates that the observation was right censored. If None, defaults to status=1 for all cases. * **entry** (*array-like*) – The entry times, if left truncation occurs * **strata** (*array-like*) – Stratum labels. If None, all observations are taken to be in a single stratum. * **offset** (*array-like*) – Array of offset values * **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` * **ties** (*string*) – The method used to handle tied times, must be either ‘breslow’ or ‘efron’. * **missing** (*string*) – The method used to handle missing data * **args** (*extra arguments*) – These are passed to the model * **kwargs** (*extra keyword arguments*) – These are passed to the model with one exception. The `eval_env` keyword is passed to patsy. It can be either a [`patsy.EvalEnvironment`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.EvalEnvironment "(in patsy v0.5.0+dev)") 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** | | Return type: | PHReg model instance | statsmodels statsmodels.tsa.vector_ar.irf.IRAnalysis.stderr statsmodels.tsa.vector\_ar.irf.IRAnalysis.stderr ================================================ `IRAnalysis.stderr(orth=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/irf.html#IRAnalysis.stderr) statsmodels statsmodels.regression.mixed_linear_model.MixedLMResults.bse_fe statsmodels.regression.mixed\_linear\_model.MixedLMResults.bse\_fe ================================================================== `MixedLMResults.bse_fe()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/mixed_linear_model.html#MixedLMResults.bse_fe) Returns the standard errors of the fixed effect regression coefficients. statsmodels statsmodels.sandbox.distributions.extras.SkewNorm_gen.mean statsmodels.sandbox.distributions.extras.SkewNorm\_gen.mean =========================================================== `SkewNorm_gen.mean(*args, **kwds)` Mean of the distribution. | Parameters: | * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **mean** – the mean of the distribution | | Return type: | float |
programming_docs
statsmodels statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.cdf statsmodels.discrete.count\_model.ZeroInflatedGeneralizedPoisson.cdf ==================================================================== `ZeroInflatedGeneralizedPoisson.cdf(X)` The cumulative distribution function of the model. statsmodels statsmodels.sandbox.regression.gmm.NonlinearIVGMM.score statsmodels.sandbox.regression.gmm.NonlinearIVGMM.score ======================================================= `NonlinearIVGMM.score(params, weights, **kwds)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#NonlinearIVGMM.score) statsmodels statsmodels.regression.mixed_linear_model.MixedLMResults.t_test statsmodels.regression.mixed\_linear\_model.MixedLMResults.t\_test ================================================================== `MixedLMResults.t_test(r_matrix, scale=None, use_t=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/mixed_linear_model.html#MixedLMResults.t_test) Compute a t-test for a each linear hypothesis of the form Rb = q | Parameters: | * **r\_matrix** (*array-like*) – If an array is given, a p x k 2d array or length k 1d array specifying the linear restrictions. It is assumed that the linear combination is equal to zero. * **scale** (*float**,* *optional*) – An optional `scale` to use. Default is the scale specified by the model fit. * **use\_t** (*bool**,* *optional*) – If use\_t is None, then the default of the model is used. If use\_t is True, then the p-values are based on the t distribution. If use\_t is False, then the p-values are based on the normal distribution. | | Returns: | **res** – The results for the test are attributes of this results instance. The available results have the same elements as the parameter table in `summary()`. | | Return type: | ContrastResults instance | statsmodels statsmodels.sandbox.distributions.extras.NormExpan_gen.median statsmodels.sandbox.distributions.extras.NormExpan\_gen.median ============================================================== `NormExpan_gen.median(*args, **kwds)` Median of the distribution. | Parameters: | * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – Location parameter, Default is 0. * **scale** (*array\_like**,* *optional*) – Scale parameter, Default is 1. | | Returns: | **median** – The median of the distribution. | | Return type: | float | See also `stats.distributions.rv_discrete.ppf` Inverse of the CDF statsmodels statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression.loglikeobs statsmodels.tsa.regime\_switching.markov\_autoregression.MarkovAutoregression.loglikeobs ======================================================================================== `MarkovAutoregression.loglikeobs(params, transformed=True)` Loglikelihood evaluation for each period | Parameters: | * **params** (*array\_like*) – Array of parameters at which to evaluate the loglikelihood function. * **transformed** (*boolean**,* *optional*) – Whether or not `params` is already transformed. Default is True. | statsmodels statsmodels.nonparametric.kernel_density.KDEMultivariate.loo_likelihood statsmodels.nonparametric.kernel\_density.KDEMultivariate.loo\_likelihood ========================================================================= `KDEMultivariate.loo_likelihood(bw, func=<function KDEMultivariate.<lambda>>)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/nonparametric/kernel_density.html#KDEMultivariate.loo_likelihood) Returns the leave-one-out likelihood function. The leave-one-out likelihood function for the unconditional KDE. | Parameters: | * **bw** (*array\_like*) – The value for the bandwidth parameter(s). * **func** (*callable**,* *optional*) – Function to transform the likelihood values (before summing); for the log likelihood, use `func=np.log`. Default is `f(x) = x`. | #### Notes The leave-one-out kernel estimator of \(f\_{-i}\) is: \[f\_{-i}(X\_{i})=\frac{1}{(n-1)h} \sum\_{j=1,j\neq i}K\_{h}(X\_{i},X\_{j})\] where \(K\_{h}\) represents the generalized product kernel estimator: \[K\_{h}(X\_{i},X\_{j}) = \prod\_{s=1}^{q}h\_{s}^{-1}k\left(\frac{X\_{is}-X\_{js}}{h\_{s}}\right)\] statsmodels statsmodels.iolib.table.SimpleTable.extend_right statsmodels.iolib.table.SimpleTable.extend\_right ================================================= `SimpleTable.extend_right(table)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/iolib/table.html#SimpleTable.extend_right) Return None. Extend each row of `self` with corresponding row of `table`. Does **not** import formatting from `table`. This generally makes sense only if the two tables have the same number of rows, but that is not enforced. :note: To extend append a table below, just use `extend`, which is the ordinary list method. This generally makes sense only if the two tables have the same number of columns, but that is not enforced. statsmodels statsmodels.tsa.vector_ar.var_model.VARResults.roots statsmodels.tsa.vector\_ar.var\_model.VARResults.roots ====================================================== `VARResults.roots()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/var_model.html#VARResults.roots) statsmodels statsmodels.genmod.generalized_estimating_equations.GEEResults.get_margeff statsmodels.genmod.generalized\_estimating\_equations.GEEResults.get\_margeff ============================================================================= `GEEResults.get_margeff(at='overall', method='dydx', atexog=None, dummy=False, count=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_estimating_equations.html#GEEResults.get_margeff) Get marginal effects of the fitted model. | Parameters: | * **at** (*str**,* *optional*) – Options are: + ’overall’, The average of the marginal effects at each observation. + ’mean’, The marginal effects at the mean of each regressor. + ’median’, The marginal effects at the median of each regressor. + ’zero’, The marginal effects at zero for each regressor. + ’all’, The marginal effects at each observation. If `at` is ‘all’ only margeff will be available.Note that if `exog` is specified, then marginal effects for all variables not specified by `exog` are calculated using the `at` option. * **method** (*str**,* *optional*) – Options are: + ’dydx’ - dy/dx - No transformation is made and marginal effects are returned. This is the default. + ’eyex’ - estimate elasticities of variables in `exog` – d(lny)/d(lnx) + ’dyex’ - estimate semielasticity – dy/d(lnx) + ’eydx’ - estimate semeilasticity – d(lny)/dxNote that tranformations are done after each observation is calculated. Semi-elasticities for binary variables are computed using the midpoint method. ‘dyex’ and ‘eyex’ do not make sense for discrete variables. * **atexog** (*array-like**,* *optional*) – Optionally, you can provide the exogenous variables over which to get the marginal effects. This should be a dictionary with the key as the zero-indexed column number and the value of the dictionary. Default is None for all independent variables less the constant. * **dummy** (*bool**,* *optional*) – If False, treats binary variables (if present) as continuous. This is the default. Else if True, treats binary variables as changing from 0 to 1. Note that any variable that is either 0 or 1 is treated as binary. Each binary variable is treated separately for now. * **count** (*bool**,* *optional*) – If False, treats count variables (if present) as continuous. This is the default. Else if True, the marginal effect is the change in probabilities when each observation is increased by one. | | Returns: | **effects** – the marginal effect corresponding to the input options | | Return type: | ndarray | #### Notes When using after Poisson, returns the expected number of events per period, assuming that the model is loglinear. statsmodels statsmodels.sandbox.regression.gmm.IVGMMResults.resid statsmodels.sandbox.regression.gmm.IVGMMResults.resid ===================================================== `IVGMMResults.resid()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#IVGMMResults.resid) statsmodels statsmodels.tsa.statespace.sarimax.SARIMAX.smooth statsmodels.tsa.statespace.sarimax.SARIMAX.smooth ================================================= `SARIMAX.smooth(params, transformed=True, complex_step=False, cov_type=None, cov_kwds=None, return_ssm=False, results_class=None, results_wrapper_class=None, **kwargs)` Kalman smoothing | Parameters: | * **params** (*array\_like*) – Array of parameters at which to evaluate the loglikelihood function. * **transformed** (*boolean**,* *optional*) – Whether or not `params` is already transformed. Default is True. * **return\_ssm** (*boolean**,**optional*) – Whether or not to return only the state space output or a full results object. Default is to return a full results object. * **cov\_type** (*str**,* *optional*) – See `MLEResults.fit` for a description of covariance matrix types for results object. * **cov\_kwds** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)") *or* *None**,* *optional*) – See `MLEResults.get_robustcov_results` for a description required keywords for alternative covariance estimators * **\*\*kwargs** – Additional keyword arguments to pass to the Kalman filter. See `KalmanFilter.filter` for more details. | statsmodels statsmodels.discrete.discrete_model.Probit.from_formula statsmodels.discrete.discrete\_model.Probit.from\_formula ========================================================= `classmethod Probit.from_formula(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** (*extra arguments*) – These are passed to the model * **kwargs** (*extra keyword arguments*) – These are passed to the model with one exception. The `eval_env` keyword is passed to patsy. It can be either a [`patsy.EvalEnvironment`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.EvalEnvironment "(in patsy v0.5.0+dev)") 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** | | Return type: | 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 statsmodels.stats.outliers_influence.OLSInfluence.summary_frame statsmodels.stats.outliers\_influence.OLSInfluence.summary\_frame ================================================================= `OLSInfluence.summary_frame()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/outliers_influence.html#OLSInfluence.summary_frame) Creates a DataFrame with all available influence results. | Returns: | **frame** – A DataFrame with all results. | | Return type: | DataFrame | #### Notes The resultant DataFrame contains six variables in addition to the DFBETAS. These are: * cooks\_d : Cook’s Distance defined in `Influence.cooks_distance` * standard\_resid : Standardized residuals defined in `Influence.resid_studentized_internal` * hat\_diag : The diagonal of the projection, or hat, matrix defined in `Influence.hat_matrix_diag` * dffits\_internal : DFFITS statistics using internally Studentized residuals defined in `Influence.dffits_internal` * dffits : DFFITS statistics using externally Studentized residuals defined in `Influence.dffits` * student\_resid : Externally Studentized residuals defined in `Influence.resid_studentized_external` statsmodels statsmodels.regression.mixed_linear_model.MixedLMResults.random_effects_cov statsmodels.regression.mixed\_linear\_model.MixedLMResults.random\_effects\_cov =============================================================================== `MixedLMResults.random_effects_cov()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/mixed_linear_model.html#MixedLMResults.random_effects_cov) Returns the conditional covariance matrix of the random effects for each group given the data. | Returns: | **random\_effects\_cov** – A dictionary mapping the distinct values of the `group` variable to the conditional covariance matrix of the random effects given the data. | | Return type: | [dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)") | statsmodels statsmodels.genmod.bayes_mixed_glm.PoissonBayesMixedGLM.from_formula statsmodels.genmod.bayes\_mixed\_glm.PoissonBayesMixedGLM.from\_formula ======================================================================= `classmethod PoissonBayesMixedGLM.from_formula(formula, vc_formulas, data, vcp_p=1, fe_p=2, vcp_names=None, vc_names=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/bayes_mixed_glm.html#PoissonBayesMixedGLM.from_formula) Fit a BayesMixedGLM using a formula. | Parameters: | * **formula** (*string*) – Formula for the endog and fixed effects terms (use ~ to separate dependent and independent expressions). * **vc\_formulas** (*dictionary*) – vc\_formulas[name] is a one-sided formula that creates one collection of random effects with a common variance prameter. If using a categorical expression to produce variance components, note that generally `0 + …` should be used so that an intercept is not included. * **data** (*data frame*) – The data to which the formulas are applied. * **family** (*genmod.families instance*) – A GLM family. * **vcp\_p** (*float*) – The prior standard deviation for the logarithms of the standard deviations of the random effects. * **fe\_p** (*float*) – The prior standard deviation for the fixed effects parameters. | statsmodels statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.wald_test_terms statsmodels.discrete.count\_model.ZeroInflatedGeneralizedPoissonResults.wald\_test\_terms ========================================================================================= `ZeroInflatedGeneralizedPoissonResults.wald_test_terms(skip_single=False, extra_constraints=None, combine_terms=None)` Compute a sequence of Wald tests for terms over multiple columns This computes joined Wald tests for the hypothesis that all coefficients corresponding to a `term` are zero. `Terms` are defined by the underlying formula or by string matching. | Parameters: | * **skip\_single** (*boolean*) – If true, then terms that consist only of a single column and, therefore, refers only to a single parameter is skipped. If false, then all terms are included. * **extra\_constraints** (*ndarray*) – not tested yet * **combine\_terms** (*None* *or* *list of strings*) – Each string in this list is matched to the name of the terms or the name of the exogenous variables. All columns whose name includes that string are combined in one joint test. | | Returns: | **test\_result** – The result instance contains `table` which is a pandas DataFrame with the test results: test statistic, degrees of freedom and pvalues. | | Return type: | result instance | #### Examples ``` >>> res_ols = ols("np.log(Days+1) ~ C(Duration, Sum)*C(Weight, Sum)", data).fit() >>> res_ols.wald_test_terms() <class 'statsmodels.stats.contrast.WaldTestResults'> F P>F df constraint df denom Intercept 279.754525 2.37985521351e-22 1 51 C(Duration, Sum) 5.367071 0.0245738436636 1 51 C(Weight, Sum) 12.432445 3.99943118767e-05 2 51 C(Duration, Sum):C(Weight, Sum) 0.176002 0.83912310946 2 51 ``` ``` >>> res_poi = Poisson.from_formula("Days ~ C(Weight) * C(Duration)", data).fit(cov_type='HC0') >>> wt = res_poi.wald_test_terms(skip_single=False, combine_terms=['Duration', 'Weight']) >>> print(wt) chi2 P>chi2 df constraint Intercept 15.695625 7.43960374424e-05 1 C(Weight) 16.132616 0.000313940174705 2 C(Duration) 1.009147 0.315107378931 1 C(Weight):C(Duration) 0.216694 0.897315972824 2 Duration 11.187849 0.010752286833 3 Weight 30.263368 4.32586407145e-06 4 ``` statsmodels statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.fit_regularized statsmodels.discrete.count\_model.ZeroInflatedGeneralizedPoisson.fit\_regularized ================================================================================= `ZeroInflatedGeneralizedPoisson.fit_regularized(start_params=None, method='l1', maxiter='defined_by_method', full_output=1, disp=1, callback=None, alpha=0, trim_mode='auto', auto_trim_tol=0.01, size_trim_tol=0.0001, qc_tol=0.03, **kwargs)` Fit the model using a regularized maximum likelihood. The regularization method AND the solver used is determined by the argument method. | Parameters: | * **start\_params** (*array-like**,* *optional*) – Initial guess of the solution for the loglikelihood maximization. The default is an array of zeros. * **method** (*'l1'* *or* *'l1\_cvxopt\_cp'*) – See notes for details. * **maxiter** (*Integer* *or* *'defined\_by\_method'*) – Maximum number of iterations to perform. If ‘defined\_by\_method’, then use method defaults (see notes). * **full\_output** (*bool*) – Set to True to have all available output in the Results object’s mle\_retvals attribute. The output is dependent on the solver. See LikelihoodModelResults notes section for more information. * **disp** (*bool*) – Set to True to print convergence messages. * **fargs** (*tuple*) – Extra arguments passed to the likelihood function, i.e., loglike(x,\*args) * **callback** (*callable callback**(**xk**)*) – Called after each iteration, as callback(xk), where xk is the current parameter vector. * **retall** (*bool*) – Set to True to return list of solutions at each iteration. Available in Results object’s mle\_retvals attribute. * **alpha** (*non-negative scalar* *or* *numpy array* *(**same size as parameters**)*) – The weight multiplying the l1 penalty term * **trim\_mode** (*'auto**,* *'size'**, or* *'off'*) – If not ‘off’, trim (set to zero) parameters that would have been zero if the solver reached the theoretical minimum. If ‘auto’, trim params using the Theory above. If ‘size’, trim params if they have very small absolute value * **size\_trim\_tol** (*float* *or* *'auto'* *(**default = 'auto'**)*) – For use when trim\_mode == ‘size’ * **auto\_trim\_tol** (*float*) – For sue when trim\_mode == ‘auto’. Use * **qc\_tol** (*float*) – Print warning and don’t allow auto trim when (ii) (above) is violated by this much. * **qc\_verbose** (*Boolean*) – If true, print out a full QC report upon failure | #### Notes Extra parameters are not penalized if alpha is given as a scalar. An example is the shape parameter in NegativeBinomial `nb1` and `nb2`. Optional arguments for the solvers (available in Results.mle\_settings): ``` 'l1' acc : float (default 1e-6) Requested accuracy as used by slsqp 'l1_cvxopt_cp' abstol : float absolute accuracy (default: 1e-7). reltol : float relative accuracy (default: 1e-6). feastol : float tolerance for feasibility conditions (default: 1e-7). refinement : int number of iterative refinement steps when solving KKT equations (default: 1). ``` Optimization methodology With \(L\) the negative log likelihood, we solve the convex but non-smooth problem \[\min\_\beta L(\beta) + \sum\_k\alpha\_k |\beta\_k|\] via the transformation to the smooth, convex, constrained problem in twice as many variables (adding the “added variables” \(u\_k\)) \[\min\_{\beta,u} L(\beta) + \sum\_k\alpha\_k u\_k,\] subject to \[-u\_k \leq \beta\_k \leq u\_k.\] With \(\partial\_k L\) the derivative of \(L\) in the \(k^{th}\) parameter direction, theory dictates that, at the minimum, exactly one of two conditions holds: 1. \(|\partial\_k L| = \alpha\_k\) and \(\beta\_k \neq 0\) 2. \(|\partial\_k L| \leq \alpha\_k\) and \(\beta\_k = 0\)
programming_docs
statsmodels statsmodels.regression.linear_model.OLSResults.llf statsmodels.regression.linear\_model.OLSResults.llf =================================================== `OLSResults.llf()` statsmodels statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialP.cdf statsmodels.discrete.count\_model.ZeroInflatedNegativeBinomialP.cdf =================================================================== `ZeroInflatedNegativeBinomialP.cdf(X)` The cumulative distribution function of the model. statsmodels statsmodels.regression.linear_model.RegressionResults.HC3_se statsmodels.regression.linear\_model.RegressionResults.HC3\_se ============================================================== `RegressionResults.HC3_se()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#RegressionResults.HC3_se) See statsmodels.RegressionResults statsmodels statsmodels.genmod.families.family.Family.resid_anscombe statsmodels.genmod.families.family.Family.resid\_anscombe ========================================================= `Family.resid_anscombe(endog, mu, var_weights=1.0, scale=1.0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/family.html#Family.resid_anscombe) The Anscombe residuals | Parameters: | * **endog** (*array*) – The endogenous response variable * **mu** (*array*) – The inverse of the link function at the linear predicted values. * **var\_weights** (*array-like*) – 1d array of variance (analytic) weights. The default is 1. * **scale** (*float**,* *optional*) – An optional argument to divide the residuals by sqrt(scale). The default is 1. | See also [`statsmodels.genmod.families.family.Family`](statsmodels.genmod.families.family.family#statsmodels.genmod.families.family.Family "statsmodels.genmod.families.family.Family") `resid_anscombe` for the individual families for more information #### Notes Anscombe residuals are defined by \[resid\\_anscombe\_i = \frac{A(y)-A(\mu)}{A'(\mu)\sqrt{Var[\mu]}} \* \sqrt(var\\_weights)\] where \(A'(y)=v(y)^{-\frac{1}{3}}\) and \(v(\mu)\) is the variance function \(Var[y]=\frac{\phi}{w}v(mu)\). The transformation \(A(y)\) makes the residuals more normal distributed. statsmodels statsmodels.regression.mixed_linear_model.MixedLM.initialize statsmodels.regression.mixed\_linear\_model.MixedLM.initialize ============================================================== `MixedLM.initialize()` Initialize (possibly re-initialize) a Model instance. For instance, the design matrix of a linear model may change and some things must be recomputed. statsmodels statsmodels.miscmodels.count.PoissonOffsetGMLE.score statsmodels.miscmodels.count.PoissonOffsetGMLE.score ==================================================== `PoissonOffsetGMLE.score(params)` Gradient of log-likelihood evaluated at params statsmodels statsmodels.stats.correlation_tools.corr_clipped statsmodels.stats.correlation\_tools.corr\_clipped ================================================== `statsmodels.stats.correlation_tools.corr_clipped(corr, threshold=1e-15)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/correlation_tools.html#corr_clipped) Find a near correlation matrix that is positive semi-definite This function clips the eigenvalues, replacing eigenvalues smaller than the threshold by the threshold. The new matrix is normalized, so that the diagonal elements are one. Compared to corr\_nearest, the distance between the original correlation matrix and the positive definite correlation matrix is larger, however, it is much faster since it only computes eigenvalues once. | Parameters: | * **corr** (*ndarray**,* *(**k**,* *k**)*) – initial correlation matrix * **threshold** (*float*) – clipping threshold for smallest eigenvalue, see Notes | | Returns: | **corr\_new** – corrected correlation matrix | | Return type: | ndarray, (optional) | #### Notes The smallest eigenvalue of the corrected correlation matrix is approximately equal to the `threshold`. In examples, the smallest eigenvalue can be by a factor of 10 smaller than the threshold, e.g. threshold 1e-8 can result in smallest eigenvalue in the range between 1e-9 and 1e-8. If the threshold=0, then the smallest eigenvalue of the correlation matrix might be negative, but zero within a numerical error, for example in the range of -1e-16. Assumes input correlation matrix is symmetric. The diagonal elements of returned correlation matrix is set to ones. If the correlation matrix is already positive semi-definite given the threshold, then the original correlation matrix is returned. `cov_clipped` is 40 or more times faster than `cov_nearest` in simple example, but has a slightly larger approximation error. See also [`corr_nearest`](statsmodels.stats.correlation_tools.corr_nearest#statsmodels.stats.correlation_tools.corr_nearest "statsmodels.stats.correlation_tools.corr_nearest"), [`cov_nearest`](statsmodels.stats.correlation_tools.cov_nearest#statsmodels.stats.correlation_tools.cov_nearest "statsmodels.stats.correlation_tools.cov_nearest") statsmodels statsmodels.robust.norms.RamsayE.rho statsmodels.robust.norms.RamsayE.rho ==================================== `RamsayE.rho(z)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/norms.html#RamsayE.rho) The robust criterion function for Ramsay’s Ea. | Parameters: | **z** (*array-like*) – 1d array | | Returns: | **rho** – rho(z) = a\*\*-2 \* (1 - exp(-a\*|z|)\*(1 + a\*|z|)) | | Return type: | array | statsmodels statsmodels.regression.linear_model.RegressionResults.compare_f_test statsmodels.regression.linear\_model.RegressionResults.compare\_f\_test ======================================================================= `RegressionResults.compare_f_test(restricted)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#RegressionResults.compare_f_test) use F test to test whether restricted model is correct | Parameters: | **restricted** (*Result instance*) – The restricted model is assumed to be nested in the current model. The result instance of the restricted model is required to have two attributes, residual sum of squares, `ssr`, residual degrees of freedom, `df_resid`. | | Returns: | * **f\_value** (*float*) – test statistic, F distributed * **p\_value** (*float*) – p-value of the test statistic * **df\_diff** (*int*) – degrees of freedom of the restriction, i.e. difference in df between models | #### Notes See mailing list discussion October 17, This test compares the residual sum of squares of the two models. This is not a valid test, if there is unspecified heteroscedasticity or correlation. This method will issue a warning if this is detected but still return the results under the assumption of homoscedasticity and no autocorrelation (sphericity). statsmodels statsmodels.sandbox.distributions.extras.SkewNorm_gen.moment statsmodels.sandbox.distributions.extras.SkewNorm\_gen.moment ============================================================= `SkewNorm_gen.moment(n, *args, **kwds)` n-th order non-central moment of distribution. | Parameters: | * **n** (*int**,* *n >= 1*) – Order of moment. * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information). * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.cov_HC2 statsmodels.sandbox.regression.gmm.IVRegressionResults.cov\_HC2 =============================================================== `IVRegressionResults.cov_HC2()` See statsmodels.RegressionResults statsmodels statsmodels.sandbox.stats.multicomp.TukeyHSDResults.summary statsmodels.sandbox.stats.multicomp.TukeyHSDResults.summary =========================================================== `TukeyHSDResults.summary()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/multicomp.html#TukeyHSDResults.summary) Summary table that can be printed statsmodels statsmodels.regression.linear_model.OLSResults.nobs statsmodels.regression.linear\_model.OLSResults.nobs ==================================================== `OLSResults.nobs()` statsmodels statsmodels.regression.mixed_linear_model.MixedLM.fit_regularized statsmodels.regression.mixed\_linear\_model.MixedLM.fit\_regularized ==================================================================== `MixedLM.fit_regularized(start_params=None, method='l1', alpha=0, ceps=0.0001, ptol=1e-06, maxit=200, **fit_kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/mixed_linear_model.html#MixedLM.fit_regularized) Fit a model in which the fixed effects parameters are penalized. The dependence parameters are held fixed at their estimated values in the unpenalized model. | Parameters: | * **method** (*string of Penalty object*) – Method for regularization. If a string, must be ‘l1’. * **alpha** (*array-like*) – Scalar or vector of penalty weights. If a scalar, the same weight is applied to all coefficients; if a vector, it contains a weight for each coefficient. If method is a Penalty object, the weights are scaled by alpha. For L1 regularization, the weights are used directly. * **ceps** (*positive real scalar*) – Fixed effects parameters smaller than this value in magnitude are treaded as being zero. * **ptol** (*positive real scalar*) – Convergence occurs when the sup norm difference between successive values of `fe_params` is less than `ptol`. * **maxit** (*integer*) – The maximum number of iterations. * **fit\_kwargs** (*keywords*) – Additional keyword arguments passed to fit. | | Returns: | | | Return type: | A MixedLMResults instance containing the results. | #### Notes The covariance structure is not updated as the fixed effects parameters are varied. The algorithm used here for L1 regularization is a”shooting” or cyclic coordinate descent algorithm. If method is ‘l1’, then `fe_pen` and `cov_pen` are used to obtain the covariance structure, but are ignored during the L1-penalized fitting. #### References Friedman, J. H., Hastie, T. and Tibshirani, R. Regularized Paths for Generalized Linear Models via Coordinate Descent. Journal of Statistical Software, 33(1) (2008) <http://www.jstatsoft.org/v33/i01/paper> <http://statweb.stanford.edu/~tibs/stat315a/Supplements/fuse.pdf> statsmodels statsmodels.sandbox.tsa.fftarma.ArmaFft.spdshift statsmodels.sandbox.tsa.fftarma.ArmaFft.spdshift ================================================ `ArmaFft.spdshift(n)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/tsa/fftarma.html#ArmaFft.spdshift) power spectral density using fftshift currently returns two-sided according to fft frequencies, use first half statsmodels statsmodels.genmod.families.links.probit.inverse statsmodels.genmod.families.links.probit.inverse ================================================ `probit.inverse(z)` The inverse of the CDF link | Parameters: | **z** (*array-like*) – The value of the inverse of the link function at `p` | | Returns: | **p** – Mean probabilities. The value of the inverse of CDF link of `z` | | Return type: | array | #### Notes g^(-1)(`z`) = `dbn`.cdf(`z`) statsmodels statsmodels.discrete.discrete_model.LogitResults.prsquared statsmodels.discrete.discrete\_model.LogitResults.prsquared =========================================================== `LogitResults.prsquared()` statsmodels statsmodels.discrete.discrete_model.GeneralizedPoisson.fit statsmodels.discrete.discrete\_model.GeneralizedPoisson.fit =========================================================== `GeneralizedPoisson.fit(start_params=None, method='bfgs', maxiter=35, full_output=1, disp=1, callback=None, use_transparams=False, cov_type='nonrobust', cov_kwds=None, use_t=None, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#GeneralizedPoisson.fit) Fit the model using maximum likelihood. The rest of the docstring is from statsmodels.base.model.LikelihoodModel.fit Fit method for likelihood based models | Parameters: | * **start\_params** (*array-like**,* *optional*) – Initial guess of the solution for the loglikelihood maximization. The default is an array of zeros. * **method** (*str**,* *optional*) – The `method` determines which solver from `scipy.optimize` is used, and it can be chosen from among the following strings: + ’newton’ for Newton-Raphson, ‘nm’ for Nelder-Mead + ’bfgs’ for Broyden-Fletcher-Goldfarb-Shanno (BFGS) + ’lbfgs’ for limited-memory BFGS with optional box constraints + ’powell’ for modified Powell’s method + ’cg’ for conjugate gradient + ’ncg’ for Newton-conjugate gradient + ’basinhopping’ for global basin-hopping solver + ’minimize’ for generic wrapper of scipy minimize (BFGS by default)The explicit arguments in `fit` are passed to the solver, with the exception of the basin-hopping solver. Each solver has several optional arguments that are not the same across solvers. See the notes section below (or scipy.optimize) for the available arguments and for the list of explicit arguments that the basin-hopping solver supports. * **maxiter** (*int**,* *optional*) – The maximum number of iterations to perform. * **full\_output** (*bool**,* *optional*) – Set to True to have all available output in the Results object’s mle\_retvals attribute. The output is dependent on the solver. See LikelihoodModelResults notes section for more information. * **disp** (*bool**,* *optional*) – Set to True to print convergence messages. * **fargs** (*tuple**,* *optional*) – Extra arguments passed to the likelihood function, i.e., loglike(x,\*args) * **callback** (*callable callback**(**xk**)**,* *optional*) – Called after each iteration, as callback(xk), where xk is the current parameter vector. * **retall** (*bool**,* *optional*) – Set to True to return list of solutions at each iteration. Available in Results object’s mle\_retvals attribute. * **skip\_hessian** (*bool**,* *optional*) – If False (default), then the negative inverse hessian is calculated after the optimization. If True, then the hessian will not be calculated. However, it will be available in methods that use the hessian in the optimization (currently only with `“newton”`). * **kwargs** (*keywords*) – All kwargs are passed to the chosen solver with one exception. The following keyword controls what happens after the fit: ``` warn_convergence : bool, optional If True, checks the model for the converged flag. If the converged flag is False, a ConvergenceWarning is issued. ``` | #### Notes The ‘basinhopping’ solver ignores `maxiter`, `retall`, `full_output` explicit arguments. Optional arguments for solvers (see returned Results.mle\_settings): ``` 'newton' tol : float Relative error in params acceptable for convergence. 'nm' -- Nelder Mead xtol : float Relative error in params acceptable for convergence ftol : float Relative error in loglike(params) acceptable for convergence maxfun : int Maximum number of function evaluations to make. 'bfgs' gtol : float Stop when norm of gradient is less than gtol. norm : float Order of norm (np.Inf is max, -np.Inf is min) epsilon If fprime is approximated, use this value for the step size. Only relevant if LikelihoodModel.score is None. 'lbfgs' m : int This many terms are used for the Hessian approximation. factr : float A stop condition that is a variant of relative error. pgtol : float A stop condition that uses the projected gradient. epsilon If fprime is approximated, use this value for the step size. Only relevant if LikelihoodModel.score is None. maxfun : int Maximum number of function evaluations to make. bounds : sequence (min, max) pairs for each element in x, defining the bounds on that parameter. Use None for one of min or max when there is no bound in that direction. 'cg' gtol : float Stop when norm of gradient is less than gtol. norm : float Order of norm (np.Inf is max, -np.Inf is min) epsilon : float If fprime is approximated, use this value for the step size. Can be scalar or vector. Only relevant if Likelihoodmodel.score is None. 'ncg' fhess_p : callable f'(x,*args) Function which computes the Hessian of f times an arbitrary vector, p. Should only be supplied if LikelihoodModel.hessian is None. avextol : float Stop when the average relative error in the minimizer falls below this amount. epsilon : float or ndarray If fhess is approximated, use this value for the step size. Only relevant if Likelihoodmodel.hessian is None. 'powell' xtol : float Line-search error tolerance ftol : float Relative error in loglike(params) for acceptable for convergence. maxfun : int Maximum number of function evaluations to make. start_direc : ndarray Initial direction set. 'basinhopping' niter : integer The number of basin hopping iterations. niter_success : integer Stop the run if the global minimum candidate remains the same for this number of iterations. T : float The "temperature" parameter for the accept or reject criterion. Higher "temperatures" mean that larger jumps in function value will be accepted. For best results `T` should be comparable to the separation (in function value) between local minima. stepsize : float Initial step size for use in the random displacement. interval : integer The interval for how often to update the `stepsize`. minimizer : dict Extra keyword arguments to be passed to the minimizer `scipy.optimize.minimize()`, for example 'method' - the minimization method (e.g. 'L-BFGS-B'), or 'tol' - the tolerance for termination. Other arguments are mapped from explicit argument of `fit`: - `args` <- `fargs` - `jac` <- `score` - `hess` <- `hess` 'minimize' min_method : str, optional Name of minimization method to use. Any method specific arguments can be passed directly. For a list of methods and their arguments, see documentation of `scipy.optimize.minimize`. If no method is specified, then BFGS is used. ``` | Parameters: | **use\_transparams** (*bool*) – This parameter enable internal transformation to impose non-negativity. True to enable. Default is False. use\_transparams=True imposes the no underdispersion (alpha > 0) constaint. In case use\_transparams=True and method=”newton” or “ncg” transformation is ignored. | statsmodels statsmodels.iolib.summary2.Summary.add_array statsmodels.iolib.summary2.Summary.add\_array ============================================= `Summary.add_array(array, align='r', float_format='%.4f')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/iolib/summary2.html#Summary.add_array) Add the contents of a Numpy array to summary table | Parameters: | * **array** (*numpy array* *(**2D**)*) – * **float\_format** (*string*) – Formatting to array if type is float * **align** (*string*) – Data alignment (l/c/r) | statsmodels statsmodels.tsa.vector_ar.vecm.VECMResults.pvalues_gamma statsmodels.tsa.vector\_ar.vecm.VECMResults.pvalues\_gamma ========================================================== `VECMResults.pvalues_gamma()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/vecm.html#VECMResults.pvalues_gamma)
programming_docs
statsmodels statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialResults.llnull statsmodels.discrete.count\_model.ZeroInflatedNegativeBinomialResults.llnull ============================================================================ `ZeroInflatedNegativeBinomialResults.llnull()` statsmodels statsmodels.discrete.count_model.GenericZeroInflated.score_obs statsmodels.discrete.count\_model.GenericZeroInflated.score\_obs ================================================================ `GenericZeroInflated.score_obs(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/count_model.html#GenericZeroInflated.score_obs) Generic Zero Inflated model score (gradient) vector of the log-likelihood | Parameters: | **params** (*array-like*) – The parameters of the model | | Returns: | **score** – The score vector of the model, i.e. the first derivative of the loglikelihood function, evaluated at `params` | | Return type: | ndarray, 1-D | statsmodels statsmodels.sandbox.distributions.extras.ACSkewT_gen.nnlf statsmodels.sandbox.distributions.extras.ACSkewT\_gen.nnlf ========================================================== `ACSkewT_gen.nnlf(theta, x)` Return negative loglikelihood function. #### Notes This is `-sum(log pdf(x, theta), axis=0)` where `theta` are the parameters (including loc and scale). statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.t_test statsmodels.tsa.statespace.dynamic\_factor.DynamicFactorResults.t\_test ======================================================================= `DynamicFactorResults.t_test(r_matrix, cov_p=None, scale=None, use_t=None)` Compute a t-test for a each linear hypothesis of the form Rb = q | Parameters: | * **r\_matrix** (*array-like**,* *str**,* *tuple*) – + array : If an array is given, a p x k 2d array or length k 1d array specifying the linear restrictions. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q). If q is given, can be either a scalar or a length p row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – An optional `scale` to use. Default is the scale specified by the model fit. * **use\_t** (*bool**,* *optional*) – If use\_t is None, then the default of the model is used. If use\_t is True, then the p-values are based on the t distribution. If use\_t is False, then the p-values are based on the normal distribution. | | Returns: | **res** – The results for the test are attributes of this results instance. The available results have the same elements as the parameter table in `summary()`. | | Return type: | ContrastResults instance | #### Examples ``` >>> import numpy as np >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> r = np.zeros_like(results.params) >>> r[5:] = [1,-1] >>> print(r) [ 0. 0. 0. 0. 0. 1. -1.] ``` r tests that the coefficients on the 5th and 6th independent variable are the same. ``` >>> T_test = results.t_test(r) >>> print(T_test) Test for Constraints ============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------ c0 -1829.2026 455.391 -4.017 0.003 -2859.368 -799.037 ============================================================================== >>> T_test.effect -1829.2025687192481 >>> T_test.sd 455.39079425193762 >>> T_test.tvalue -4.0167754636411717 >>> T_test.pvalue 0.0015163772380899498 ``` Alternatively, you can specify the hypothesis tests using a string ``` >>> from statsmodels.formula.api import ols >>> dta = sm.datasets.longley.load_pandas().data >>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' >>> results = ols(formula, dta).fit() >>> hypotheses = 'GNPDEFL = GNP, UNEMP = 2, YEAR/1829 = 1' >>> t_test = results.t_test(hypotheses) >>> print(t_test) Test for Constraints ============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------ c0 15.0977 84.937 0.178 0.863 -177.042 207.238 c1 -2.0202 0.488 -8.231 0.000 -3.125 -0.915 c2 1.0001 0.249 0.000 1.000 0.437 1.563 ============================================================================== ``` See also [`tvalues`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactorresults.tvalues#statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.tvalues "statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.tvalues") individual t statistics [`f_test`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactorresults.f_test#statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.f_test "statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.f_test") for F tests [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") statsmodels statsmodels.tsa.ar_model.ARResults.resid statsmodels.tsa.ar\_model.ARResults.resid ========================================= `ARResults.resid()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/ar_model.html#ARResults.resid) statsmodels statsmodels.sandbox.distributions.transformed.TransfTwo_gen.cdf statsmodels.sandbox.distributions.transformed.TransfTwo\_gen.cdf ================================================================ `TransfTwo_gen.cdf(x, *args, **kwds)` Cumulative distribution function of the given RV. | Parameters: | * **x** (*array\_like*) – quantiles * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **cdf** – Cumulative distribution function evaluated at `x` | | Return type: | ndarray | statsmodels statsmodels.genmod.families.links.inverse_squared.deriv2 statsmodels.genmod.families.links.inverse\_squared.deriv2 ========================================================= `inverse_squared.deriv2(p)` Second derivative of the power transform | Parameters: | **p** (*array-like*) – Mean parameters | | Returns: | **g’‘(p)** – Second derivative of the power transform of `p` | | Return type: | array | #### Notes g’‘(`p`) = `power` \* (`power` - 1) \* `p`**(`power` - 2) statsmodels statsmodels.tsa.statespace.mlemodel.MLEResults.impulse_responses statsmodels.tsa.statespace.mlemodel.MLEResults.impulse\_responses ================================================================= `MLEResults.impulse_responses(steps=1, impulse=0, orthogonalized=False, cumulative=False, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEResults.impulse_responses) Impulse response function | Parameters: | * **steps** (*int**,* *optional*) – The number of steps for which impulse responses are calculated. Default is 1. Note that the initial impulse is not counted as a step, so if `steps=1`, the output will have 2 entries. * **impulse** (*int* *or* *array\_like*) – If an integer, the state innovation to pulse; must be between 0 and `k_posdef-1`. Alternatively, a custom impulse vector may be provided; must be shaped `k_posdef x 1`. * **orthogonalized** (*boolean**,* *optional*) – Whether or not to perform impulse using orthogonalized innovations. Note that this will also affect custum `impulse` vectors. Default is False. * **cumulative** (*boolean**,* *optional*) – Whether or not to return cumulative impulse responses. Default is False. * **\*\*kwargs** – If the model is time-varying and `steps` is greater than the number of observations, any of the state space representation matrices that are time-varying must have updated values provided for the out-of-sample steps. For example, if `design` is a time-varying component, `nobs` is 10, and `steps` is 15, a (`k_endog` x `k_states` x 5) matrix must be provided with the new design matrix values. | | Returns: | **impulse\_responses** – Responses for each endogenous variable due to the impulse given by the `impulse` argument. A (steps + 1 x k\_endog) array. | | Return type: | array | #### Notes Intercepts in the measurement and state equation are ignored when calculating impulse responses. statsmodels statsmodels.tsa.arima_model.ARMAResults.forecast statsmodels.tsa.arima\_model.ARMAResults.forecast ================================================= `ARMAResults.forecast(steps=1, exog=None, alpha=0.05)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_model.html#ARMAResults.forecast) Out-of-sample forecasts | Parameters: | * **steps** (*int*) – The number of out of sample forecasts from the end of the sample. * **exog** (*array*) – If the model is an ARMAX, you must provide out of sample values for the exogenous variables. This should not include the constant. * **alpha** (*float*) – The confidence intervals for the forecasts are (1 - alpha) % | | Returns: | * **forecast** (*array*) – Array of out of sample forecasts * **stderr** (*array*) – Array of the standard error of the forecasts. * **conf\_int** (*array*) – 2d array of the confidence interval for the forecast | statsmodels statsmodels.sandbox.distributions.transformed.ExpTransf_gen.fit statsmodels.sandbox.distributions.transformed.ExpTransf\_gen.fit ================================================================ `ExpTransf_gen.fit(data, *args, **kwds)` Return MLEs for shape (if applicable), location, and scale parameters from data. MLE stands for Maximum Likelihood Estimate. Starting estimates for the fit are given by input arguments; for any arguments not provided with starting estimates, `self._fitstart(data)` is called to generate such. One can hold some parameters fixed to specific values by passing in keyword arguments `f0`, `f1`, …, `fn` (for shape parameters) and `floc` and `fscale` (for location and scale parameters, respectively). | Parameters: | * **data** (*array\_like*) – Data to use in calculating the MLEs. * **args** (*floats**,* *optional*) – Starting value(s) for any shape-characterizing arguments (those not provided will be determined by a call to `_fitstart(data)`). No default value. * **kwds** (*floats**,* *optional*) – Starting values for the location and scale parameters; no default. Special keyword arguments are recognized as holding certain parameters fixed: + f0…fn : hold respective shape parameters fixed. Alternatively, shape parameters to fix can be specified by name. For example, if `self.shapes == "a, b"`, `fa``and ``fix_a` are equivalent to `f0`, and `fb` and `fix_b` are equivalent to `f1`. + floc : hold location parameter fixed to specified value. + fscale : hold scale parameter fixed to specified value. + optimizer : The optimizer to use. The optimizer must take `func`, and starting position as the first two arguments, plus `args` (for extra arguments to pass to the function to be optimized) and `disp=0` to suppress output as keyword arguments. | | Returns: | **mle\_tuple** – MLEs for any shape parameters (if applicable), followed by those for location and scale. For most random variables, shape statistics will be returned, but there are exceptions (e.g. `norm`). | | Return type: | tuple of floats | #### Notes This fit is computed by maximizing a log-likelihood function, with penalty applied for samples outside of range of the distribution. The returned answer is not guaranteed to be the globally optimal MLE, it may only be locally optimal, or the optimization may fail altogether. #### Examples Generate some data to fit: draw random variates from the `beta` distribution ``` >>> from scipy.stats import beta >>> a, b = 1., 2. >>> x = beta.rvs(a, b, size=1000) ``` Now we can fit all four parameters (`a`, `b`, `loc` and `scale`): ``` >>> a1, b1, loc1, scale1 = beta.fit(x) ``` We can also use some prior knowledge about the dataset: let’s keep `loc` and `scale` fixed: ``` >>> a1, b1, loc1, scale1 = beta.fit(x, floc=0, fscale=1) >>> loc1, scale1 (0, 1) ``` We can also keep shape parameters fixed by using `f`-keywords. To keep the zero-th shape parameter `a` equal 1, use `f0=1` or, equivalently, `fa=1`: ``` >>> a1, b1, loc1, scale1 = beta.fit(x, fa=1, floc=0, fscale=1) >>> a1 1 ``` Not all distributions return estimates for the shape parameters. `norm` for example just returns estimates for location and scale: ``` >>> from scipy.stats import norm >>> x = norm.rvs(a, b, size=1000, random_state=123) >>> loc1, scale1 = norm.fit(x) >>> loc1, scale1 (0.92087172783841631, 2.0015750750324668) ``` statsmodels statsmodels.discrete.discrete_model.Probit.hessian statsmodels.discrete.discrete\_model.Probit.hessian =================================================== `Probit.hessian(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#Probit.hessian) Probit model Hessian matrix of the log-likelihood | Parameters: | **params** (*array-like*) – The parameters of the model | | Returns: | **hess** – The Hessian, second derivative of loglikelihood function, evaluated at `params` | | Return type: | ndarray, (k\_vars, k\_vars) | #### Notes \[\frac{\partial^{2}\ln L}{\partial\beta\partial\beta^{\prime}}=-\lambda\_{i}\left(\lambda\_{i}+x\_{i}^{\prime}\beta\right)x\_{i}x\_{i}^{\prime}\] where \[\lambda\_{i}=\frac{q\_{i}\phi\left(q\_{i}x\_{i}^{\prime}\beta\right)}{\Phi\left(q\_{i}x\_{i}^{\prime}\beta\right)}\] and \(q=2y-1\) statsmodels statsmodels.tsa.statespace.mlemodel.MLEModel.initialize_statespace statsmodels.tsa.statespace.mlemodel.MLEModel.initialize\_statespace =================================================================== `MLEModel.initialize_statespace(**kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEModel.initialize_statespace) Initialize the state space representation | Parameters: | **\*\*kwargs** – Additional keyword arguments to pass to the state space class constructor. | statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.plot_coefficients_of_determination statsmodels.tsa.statespace.dynamic\_factor.DynamicFactorResults.plot\_coefficients\_of\_determination ===================================================================================================== `DynamicFactorResults.plot_coefficients_of_determination(endog_labels=None, fig=None, figsize=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/dynamic_factor.html#DynamicFactorResults.plot_coefficients_of_determination) Plot the coefficients of determination | Parameters: | * **endog\_labels** (*boolean**,* *optional*) – Whether or not to label the endogenous variables along the x-axis of the plots. Default is to include labels if there are 5 or fewer endogenous variables. * **fig** (*Matplotlib Figure instance**,* *optional*) – If given, subplots are created in this figure instead of in a new figure. Note that the grid will be created in the provided figure using `fig.add_subplot()`. * **figsize** (*tuple**,* *optional*) – If a figure is created, this argument allows specifying a size. The tuple is (width, height). | #### Notes Produces a `k_factors` x 1 plot grid. The `i`th plot shows a bar plot of the coefficients of determination associated with factor `i`. The endogenous variables are arranged along the x-axis according to their position in the `endog` array. See also [`coefficients_of_determination`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactorresults.coefficients_of_determination#statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.coefficients_of_determination "statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.coefficients_of_determination") statsmodels statsmodels.regression.linear_model.OLSResults.cov_HC3 statsmodels.regression.linear\_model.OLSResults.cov\_HC3 ======================================================== `OLSResults.cov_HC3()` See statsmodels.RegressionResults statsmodels statsmodels.iolib.table.SimpleTable.as_html statsmodels.iolib.table.SimpleTable.as\_html ============================================ `SimpleTable.as_html(**fmt_dict)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/iolib/table.html#SimpleTable.as_html) Return string. This is the default formatter for HTML tables. An HTML table formatter must accept as arguments a table and a format dictionary. statsmodels statsmodels.regression.quantile_regression.QuantRegResults.eigenvals statsmodels.regression.quantile\_regression.QuantRegResults.eigenvals ===================================================================== `QuantRegResults.eigenvals()` Return eigenvalues sorted in decreasing order. statsmodels statsmodels.sandbox.regression.gmm.GMM.momcond_mean statsmodels.sandbox.regression.gmm.GMM.momcond\_mean ==================================================== `GMM.momcond_mean(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#GMM.momcond_mean) mean of moment conditions, statsmodels statsmodels.sandbox.tsa.fftarma.ArmaFft.spddirect statsmodels.sandbox.tsa.fftarma.ArmaFft.spddirect ================================================= `ArmaFft.spddirect(n)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/tsa/fftarma.html#ArmaFft.spddirect) power spectral density using padding to length n done by fft currently returns two-sided according to fft frequencies, use first half statsmodels statsmodels.discrete.discrete_model.LogitResults.get_margeff statsmodels.discrete.discrete\_model.LogitResults.get\_margeff ============================================================== `LogitResults.get_margeff(at='overall', method='dydx', atexog=None, dummy=False, count=False)` Get marginal effects of the fitted model. | Parameters: | * **at** (*str**,* *optional*) – Options are: + ’overall’, The average of the marginal effects at each observation. + ’mean’, The marginal effects at the mean of each regressor. + ’median’, The marginal effects at the median of each regressor. + ’zero’, The marginal effects at zero for each regressor. + ’all’, The marginal effects at each observation. If `at` is all only margeff will be available from the returned object.Note that if `exog` is specified, then marginal effects for all variables not specified by `exog` are calculated using the `at` option. * **method** (*str**,* *optional*) – Options are: + ’dydx’ - dy/dx - No transformation is made and marginal effects are returned. This is the default. + ’eyex’ - estimate elasticities of variables in `exog` – d(lny)/d(lnx) + ’dyex’ - estimate semielasticity – dy/d(lnx) + ’eydx’ - estimate semeilasticity – d(lny)/dxNote that tranformations are done after each observation is calculated. Semi-elasticities for binary variables are computed using the midpoint method. ‘dyex’ and ‘eyex’ do not make sense for discrete variables. * **atexog** (*array-like**,* *optional*) – Optionally, you can provide the exogenous variables over which to get the marginal effects. This should be a dictionary with the key as the zero-indexed column number and the value of the dictionary. Default is None for all independent variables less the constant. * **dummy** (*bool**,* *optional*) – If False, treats binary variables (if present) as continuous. This is the default. Else if True, treats binary variables as changing from 0 to 1. Note that any variable that is either 0 or 1 is treated as binary. Each binary variable is treated separately for now. * **count** (*bool**,* *optional*) – If False, treats count variables (if present) as continuous. This is the default. Else if True, the marginal effect is the change in probabilities when each observation is increased by one. | | Returns: | **DiscreteMargins** – Returns an object that holds the marginal effects, standard errors, confidence intervals, etc. See `statsmodels.discrete.discrete_margins.DiscreteMargins` for more information. | | Return type: | marginal effects instance | #### Notes When using after Poisson, returns the expected number of events per period, assuming that the model is loglinear.
programming_docs
statsmodels statsmodels.sandbox.distributions.extras.SkewNorm2_gen.fit statsmodels.sandbox.distributions.extras.SkewNorm2\_gen.fit =========================================================== `SkewNorm2_gen.fit(data, *args, **kwds)` Return MLEs for shape (if applicable), location, and scale parameters from data. MLE stands for Maximum Likelihood Estimate. Starting estimates for the fit are given by input arguments; for any arguments not provided with starting estimates, `self._fitstart(data)` is called to generate such. One can hold some parameters fixed to specific values by passing in keyword arguments `f0`, `f1`, …, `fn` (for shape parameters) and `floc` and `fscale` (for location and scale parameters, respectively). | Parameters: | * **data** (*array\_like*) – Data to use in calculating the MLEs. * **args** (*floats**,* *optional*) – Starting value(s) for any shape-characterizing arguments (those not provided will be determined by a call to `_fitstart(data)`). No default value. * **kwds** (*floats**,* *optional*) – Starting values for the location and scale parameters; no default. Special keyword arguments are recognized as holding certain parameters fixed: + f0…fn : hold respective shape parameters fixed. Alternatively, shape parameters to fix can be specified by name. For example, if `self.shapes == "a, b"`, `fa``and ``fix_a` are equivalent to `f0`, and `fb` and `fix_b` are equivalent to `f1`. + floc : hold location parameter fixed to specified value. + fscale : hold scale parameter fixed to specified value. + optimizer : The optimizer to use. The optimizer must take `func`, and starting position as the first two arguments, plus `args` (for extra arguments to pass to the function to be optimized) and `disp=0` to suppress output as keyword arguments. | | Returns: | **mle\_tuple** – MLEs for any shape parameters (if applicable), followed by those for location and scale. For most random variables, shape statistics will be returned, but there are exceptions (e.g. `norm`). | | Return type: | tuple of floats | #### Notes This fit is computed by maximizing a log-likelihood function, with penalty applied for samples outside of range of the distribution. The returned answer is not guaranteed to be the globally optimal MLE, it may only be locally optimal, or the optimization may fail altogether. #### Examples Generate some data to fit: draw random variates from the `beta` distribution ``` >>> from scipy.stats import beta >>> a, b = 1., 2. >>> x = beta.rvs(a, b, size=1000) ``` Now we can fit all four parameters (`a`, `b`, `loc` and `scale`): ``` >>> a1, b1, loc1, scale1 = beta.fit(x) ``` We can also use some prior knowledge about the dataset: let’s keep `loc` and `scale` fixed: ``` >>> a1, b1, loc1, scale1 = beta.fit(x, floc=0, fscale=1) >>> loc1, scale1 (0, 1) ``` We can also keep shape parameters fixed by using `f`-keywords. To keep the zero-th shape parameter `a` equal 1, use `f0=1` or, equivalently, `fa=1`: ``` >>> a1, b1, loc1, scale1 = beta.fit(x, fa=1, floc=0, fscale=1) >>> a1 1 ``` Not all distributions return estimates for the shape parameters. `norm` for example just returns estimates for location and scale: ``` >>> from scipy.stats import norm >>> x = norm.rvs(a, b, size=1000, random_state=123) >>> loc1, scale1 = norm.fit(x) >>> loc1, scale1 (0.92087172783841631, 2.0015750750324668) ``` statsmodels statsmodels.tsa.arima_model.ARIMAResults.pvalues statsmodels.tsa.arima\_model.ARIMAResults.pvalues ================================================= `ARIMAResults.pvalues()` statsmodels statsmodels.tsa.statespace.varmax.VARMAXResults.info_criteria statsmodels.tsa.statespace.varmax.VARMAXResults.info\_criteria ============================================================== `VARMAXResults.info_criteria(criteria, method='standard')` Information criteria | Parameters: | * **criteria** (*{'aic'**,* *'bic'**,* *'hqic'}*) – The information criteria to compute. * **method** (*{'standard'**,* *'lutkepohl'}*) – The method for information criteria computation. Default is ‘standard’ method; ‘lutkepohl’ computes the information criteria as in Lütkepohl (2007). See Notes for formulas. | #### Notes The `‘standard’` formulas are: \[\begin{split}AIC & = -2 \log L(Y\_n | \hat \psi) + 2 k \\ BIC & = -2 \log L(Y\_n | \hat \psi) + k \log n \\ HQIC & = -2 \log L(Y\_n | \hat \psi) + 2 k \log \log n \\\end{split}\] where \(\hat \psi\) are the maximum likelihood estimates of the parameters, \(n\) is the number of observations, and `k` is the number of estimated parameters. Note that the `‘standard’` formulas are returned from the `aic`, `bic`, and `hqic` results attributes. The `‘lutkepohl’` formuals are (Lütkepohl, 2010): \[\begin{split}AIC\_L & = \log | Q | + \frac{2 k}{n} \\ BIC\_L & = \log | Q | + \frac{k \log n}{n} \\ HQIC\_L & = \log | Q | + \frac{2 k \log \log n}{n} \\\end{split}\] where \(Q\) is the state covariance matrix. Note that the Lütkepohl definitions do not apply to all state space models, and should be used with care outside of SARIMAX and VARMAX models. #### References | | | | --- | --- | | [\*] | Lütkepohl, Helmut. 2007. *New Introduction to Multiple Time* *Series Analysis.* Berlin: Springer. | statsmodels statsmodels.sandbox.distributions.extras.NormExpan_gen.pdf statsmodels.sandbox.distributions.extras.NormExpan\_gen.pdf =========================================================== `NormExpan_gen.pdf(x, *args, **kwds)` Probability density function at x of the given RV. | Parameters: | * **x** (*array\_like*) – quantiles * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **pdf** – Probability density function evaluated at x | | Return type: | ndarray | statsmodels statsmodels.regression.mixed_linear_model.MixedLMResults.initialize statsmodels.regression.mixed\_linear\_model.MixedLMResults.initialize ===================================================================== `MixedLMResults.initialize(model, params, **kwd)` statsmodels statsmodels.robust.robust_linear_model.RLMResults.predict statsmodels.robust.robust\_linear\_model.RLMResults.predict =========================================================== `RLMResults.predict(exog=None, transform=True, *args, **kwargs)` Call self.model.predict with self.params as the first argument. | Parameters: | * **exog** (*array-like**,* *optional*) – The values for which you want to predict. see Notes below. * **transform** (*bool**,* *optional*) – If the model was fit via a formula, do you want to pass exog through the formula. Default is True. E.g., if you fit a model y ~ log(x1) + log(x2), and transform is True, then you can pass a data structure that contains x1 and x2 in their original form. Otherwise, you’d need to log the data first. * **kwargs** (*args**,*) – Some models can take additional arguments or keywords, see the predict method of the model for the details. | | Returns: | **prediction** – See self.model.predict | | Return type: | ndarray, [pandas.Series](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html#pandas.Series "(in pandas v0.22.0)") or [pandas.DataFrame](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html#pandas.DataFrame "(in pandas v0.22.0)") | #### Notes The types of exog that are supported depends on whether a formula was used in the specification of the model. If a formula was used, then exog is processed in the same way as the original data. This transformation needs to have key access to the same variable names, and can be a pandas DataFrame or a dict like object. If no formula was used, then the provided exog needs to have the same number of columns as the original exog in the model. No transformation of the data is performed except converting it to a numpy array. Row indices as in pandas data frames are supported, and added to the returned prediction. statsmodels statsmodels.sandbox.distributions.transformed.ExpTransf_gen.interval statsmodels.sandbox.distributions.transformed.ExpTransf\_gen.interval ===================================================================== `ExpTransf_gen.interval(alpha, *args, **kwds)` Confidence interval with equal areas around the median. | Parameters: | * **alpha** (*array\_like of float*) – Probability that an rv will be drawn from the returned range. Each value should be in the range [0, 1]. * **arg2****,** **..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information). * **loc** (*array\_like**,* *optional*) – location parameter, Default is 0. * **scale** (*array\_like**,* *optional*) – scale parameter, Default is 1. | | Returns: | **a, b** – end-points of range that contain `100 * alpha %` of the rv’s possible values. | | Return type: | ndarray of float | statsmodels statsmodels.stats.weightstats.CompareMeans.ztest_ind statsmodels.stats.weightstats.CompareMeans.ztest\_ind ===================================================== `CompareMeans.ztest_ind(alternative='two-sided', usevar='pooled', value=0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/weightstats.html#CompareMeans.ztest_ind) z-test for the null hypothesis of identical means | Parameters: | * **x2** (*x1**,*) – two independent samples, see notes for 2-D case * **alternative** (*string*) – The alternative hypothesis, H1, has to be one of the following ‘two-sided’: H1: difference in means not equal to value (default) ‘larger’ : H1: difference in means larger than value ‘smaller’ : H1: difference in means smaller than value * **usevar** (*string**,* *'pooled'* *or* *'unequal'*) – If `pooled`, then the standard deviation of the samples is assumed to be the same. If `unequal`, then the standard deviations of the samples may be different. * **value** (*float*) – difference between the means under the Null hypothesis. | | Returns: | * **tstat** (*float*) – test statisic * **pvalue** (*float*) – pvalue of the z-test | statsmodels statsmodels.discrete.discrete_model.Poisson.loglike statsmodels.discrete.discrete\_model.Poisson.loglike ==================================================== `Poisson.loglike(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#Poisson.loglike) Loglikelihood of Poisson model | Parameters: | **params** (*array-like*) – The parameters of the model. | | Returns: | **loglike** – The log-likelihood function of the model evaluated at `params`. See notes. | | Return type: | float | #### Notes \[\ln L=\sum\_{i=1}^{n}\left[-\lambda\_{i}+y\_{i}x\_{i}^{\prime}\beta-\ln y\_{i}!\right]\] statsmodels statsmodels.multivariate.manova.MANOVA.mv_test statsmodels.multivariate.manova.MANOVA.mv\_test =============================================== `MANOVA.mv_test(hypotheses=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/multivariate/manova.html#MANOVA.mv_test) Linear hypotheses testing | Parameters: | **hypotheses** (*A list of tuples*) – Hypothesis `L*B*M = C` to be tested where B is the parameters in regression Y = X\*B. Each element is a tuple of length 2, 3, or 4:* (name, contrast\_L) * (name, contrast\_L, transform\_M) * (name, contrast\_L, transform\_M, constant\_C) containing a string `name`, the contrast matrix L, the transform matrix M (for transforming dependent variables), and right-hand side constant matrix constant\_C, respectively. `contrast_L : 2D array or an array of strings` Left-hand side contrast matrix for hypotheses testing. If 2D array, each row is an hypotheses and each column is an independent variable. At least 1 row (1 by k\_exog, the number of independent variables) is required. If an array of strings, it will be passed to patsy.DesignInfo().linear\_constraint. `transform_M : 2D array or an array of strings or None, optional` Left hand side transform matrix. If `None` or left out, it is set to a k\_endog by k\_endog identity matrix (i.e. do not transform y matrix). If an array of strings, it will be passed to patsy.DesignInfo().linear\_constraint. `constant_C : 2D array or None, optional` Right-hand side constant matrix. if `None` or left out it is set to a matrix of zeros Must has the same number of rows as contrast\_L and the same number of columns as transform\_M If `hypotheses` is None: 1) the effect of each independent variable on the dependent variables will be tested. Or 2) if model is created using a formula, `hypotheses` will be created according to `design_info`. 1) and 2) is equivalent if no additional variables are created by the formula (e.g. dummy variables for categorical variables and interaction terms) | | Returns: | **results** | | Return type: | [MultivariateTestResults](statsmodels.multivariate.multivariate_ols.multivariatetestresults#statsmodels.multivariate.multivariate_ols.MultivariateTestResults "statsmodels.multivariate.multivariate_ols.MultivariateTestResults") | #### Notes Testing the linear hypotheses L \* params \* M = 0 where `params` is the regression coefficient matrix for the linear model y = x \* params statsmodels statsmodels.imputation.mice.MICEData.update statsmodels.imputation.mice.MICEData.update =========================================== `MICEData.update(vname)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/imputation/mice.html#MICEData.update) Impute missing values for a single variable. This is a two-step process in which first the parameters are perturbed, then the missing values are re-imputed. | Parameters: | **vname** (*string*) – The name of the variable to be updated. | statsmodels statsmodels.regression.linear_model.RegressionResults.cov_HC3 statsmodels.regression.linear\_model.RegressionResults.cov\_HC3 =============================================================== `RegressionResults.cov_HC3()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#RegressionResults.cov_HC3) See statsmodels.RegressionResults statsmodels statsmodels.genmod.bayes_mixed_glm.BinomialBayesMixedGLM statsmodels.genmod.bayes\_mixed\_glm.BinomialBayesMixedGLM ========================================================== `class statsmodels.genmod.bayes_mixed_glm.BinomialBayesMixedGLM(endog, exog, exog_vc, ident, vcp_p=1, fe_p=2, fep_names=None, vcp_names=None, vc_names=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/bayes_mixed_glm.html#BinomialBayesMixedGLM) Fit a generalized linear mixed model using Bayesian methods. The class implements the Laplace approximation to the posterior distribution (`fit_map`) and a variational Bayes approximation to the posterior (`fit_vb`). See the two fit method docstrings for more information about the fitting approaches. | Parameters: | * **endog** (*array-like*) – Vector of response values. * **exog** (*array-like*) – Array of covariates for the fixed effects part of the mean structure. * **exog\_vc** (*array-like*) – Array of covariates for the random part of the model. A scipy.sparse array may be provided, or else the passed array will be converted to sparse internally. * **ident** (*array-like*) – Array of labels showing which random terms (columns of `exog_vc`) have a common variance. * **vc\_p** (*float*) – Prior standard deviation for variance component parameters (the prior standard deviation of log(s) is vc\_p, where s is the standard deviation of a random effect). * **fe\_p** (*float*) – Prior standard deviation for fixed effects parameters. * **family** (*statsmodels.genmod.families instance*) – The GLM family. * **fep\_names** (*list of strings*) – The names of the fixed effects parameters (corresponding to columns of exog). If None, default names are constructed. * **vcp\_names** (*list of strings*) – The names of the variance component parameters (corresponding to distinct labels in ident). If None, default names are constructed. * **vc\_names** (*list of strings*) – The names of the random effect realizations. | | Returns: | | | Return type: | MixedGLMResults object | #### Notes There are three types of values in the posterior distribution: fixed effects parameters (fep), corresponding to the columns of `exog`, random effects realizations (vc), corresponding to the columns of `exog_vc`, and the standard deviations of the random effects realizations (vcp), corresponding to the unique labels in `ident`. All random effects are modeled as being independent Gaussian values (given the variance parameters). Every column of `exog_vc` has a distinct realized random effect that is used to form the linear predictors. The elements of `ident` determine the distinct random effect variance parameters. Two random effect realizations that have the same value in `ident` are constrained to have the same variance. When fitting with a formula, `ident` is constructed internally (each element of `vc_formulas` yields a distinct label in `ident`). The random effect standard deviation parameters (vcp) have log-normal prior distributions with mean 0 and standard deviation `vcp_p`. Note that for some families, e.g. Binomial, the posterior mode may be difficult to find numerically if `vcp_p` is set to too large of a value. Setting `vcp_p` to 0.5 seems to work well. The prior for the fixed effects parameters is Gaussian with mean 0 and standard deviation `fe_p`. #### Examples A binomial (logistic) random effects model with random intercepts for villages and random slopes for each year within each village: ``` >>> data['year_cen'] = data['Year'] - data.Year.mean() >>> random = ['0 + C(Village)', '0 + C(Village)*year_cen'] >>> model = BinomialBayesMixedGLM.from_formula('y ~ year_cen', random, data) >>> result = model.fit() ``` #### References Introduction to generalized linear mixed models: <https://stats.idre.ucla.edu/other/mult-pkg/introduction-to-generalized-linear-mixed-models> SAS documentation: <https://support.sas.com/documentation/cdl/en/statug/63033/HTML/default/viewer.htm#statug_intromix_a0000000215.htm> An assessment of estimation methods for generalized linear mixed models with binary outcomes <https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3866838/> #### Methods | | | | --- | --- | | [`fit`](statsmodels.genmod.bayes_mixed_glm.binomialbayesmixedglm.fit#statsmodels.genmod.bayes_mixed_glm.BinomialBayesMixedGLM.fit "statsmodels.genmod.bayes_mixed_glm.BinomialBayesMixedGLM.fit")() | Fit a model to data. | | [`fit_map`](statsmodels.genmod.bayes_mixed_glm.binomialbayesmixedglm.fit_map#statsmodels.genmod.bayes_mixed_glm.BinomialBayesMixedGLM.fit_map "statsmodels.genmod.bayes_mixed_glm.BinomialBayesMixedGLM.fit_map")([method, minim\_opts]) | Construct the Laplace approximation to the posterior distribution. | | [`fit_vb`](statsmodels.genmod.bayes_mixed_glm.binomialbayesmixedglm.fit_vb#statsmodels.genmod.bayes_mixed_glm.BinomialBayesMixedGLM.fit_vb "statsmodels.genmod.bayes_mixed_glm.BinomialBayesMixedGLM.fit_vb")([mean, sd, fit\_method, minim\_opts, …]) | Fit a model using the variational Bayes mean field approximation. | | [`from_formula`](statsmodels.genmod.bayes_mixed_glm.binomialbayesmixedglm.from_formula#statsmodels.genmod.bayes_mixed_glm.BinomialBayesMixedGLM.from_formula "statsmodels.genmod.bayes_mixed_glm.BinomialBayesMixedGLM.from_formula")(formula, vc\_formulas, data[, …]) | Fit a BayesMixedGLM using a formula. | | [`logposterior`](statsmodels.genmod.bayes_mixed_glm.binomialbayesmixedglm.logposterior#statsmodels.genmod.bayes_mixed_glm.BinomialBayesMixedGLM.logposterior "statsmodels.genmod.bayes_mixed_glm.BinomialBayesMixedGLM.logposterior")(params) | The overall log-density: log p(y, fe, vc, vcp). | | [`logposterior_grad`](statsmodels.genmod.bayes_mixed_glm.binomialbayesmixedglm.logposterior_grad#statsmodels.genmod.bayes_mixed_glm.BinomialBayesMixedGLM.logposterior_grad "statsmodels.genmod.bayes_mixed_glm.BinomialBayesMixedGLM.logposterior_grad")(params) | The gradient of the log posterior. | | [`predict`](statsmodels.genmod.bayes_mixed_glm.binomialbayesmixedglm.predict#statsmodels.genmod.bayes_mixed_glm.BinomialBayesMixedGLM.predict "statsmodels.genmod.bayes_mixed_glm.BinomialBayesMixedGLM.predict")(params[, exog]) | After a model has been fit predict returns the fitted values. | | [`vb_elbo`](statsmodels.genmod.bayes_mixed_glm.binomialbayesmixedglm.vb_elbo#statsmodels.genmod.bayes_mixed_glm.BinomialBayesMixedGLM.vb_elbo "statsmodels.genmod.bayes_mixed_glm.BinomialBayesMixedGLM.vb_elbo")(vb\_mean, vb\_sd) | Returns the evidence lower bound (ELBO) for the model. | | [`vb_elbo_base`](statsmodels.genmod.bayes_mixed_glm.binomialbayesmixedglm.vb_elbo_base#statsmodels.genmod.bayes_mixed_glm.BinomialBayesMixedGLM.vb_elbo_base "statsmodels.genmod.bayes_mixed_glm.BinomialBayesMixedGLM.vb_elbo_base")(h, tm, fep\_mean, vcp\_mean, …) | Returns the evidence lower bound (ELBO) for the model. | | [`vb_elbo_grad`](statsmodels.genmod.bayes_mixed_glm.binomialbayesmixedglm.vb_elbo_grad#statsmodels.genmod.bayes_mixed_glm.BinomialBayesMixedGLM.vb_elbo_grad "statsmodels.genmod.bayes_mixed_glm.BinomialBayesMixedGLM.vb_elbo_grad")(vb\_mean, vb\_sd) | Returns the gradient of the model’s evidence lower bound (ELBO). | | [`vb_elbo_grad_base`](statsmodels.genmod.bayes_mixed_glm.binomialbayesmixedglm.vb_elbo_grad_base#statsmodels.genmod.bayes_mixed_glm.BinomialBayesMixedGLM.vb_elbo_grad_base "statsmodels.genmod.bayes_mixed_glm.BinomialBayesMixedGLM.vb_elbo_grad_base")(h, tm, tv, fep\_mean, …) | Return the gradient of the ELBO function. | #### Attributes | | | | --- | --- | | `endog_names` | Names of endogenous variables | | `exog_names` | Names of exogenous variables | | `rng` | | | `verbose` | |
programming_docs
statsmodels statsmodels.tsa.vector_ar.vecm.VECMResults.pvalues_beta statsmodels.tsa.vector\_ar.vecm.VECMResults.pvalues\_beta ========================================================= `VECMResults.pvalues_beta()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/vecm.html#VECMResults.pvalues_beta) statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.HC1_se statsmodels.sandbox.regression.gmm.IVRegressionResults.HC1\_se ============================================================== `IVRegressionResults.HC1_se()` See statsmodels.RegressionResults statsmodels statsmodels.regression.recursive_ls.RecursiveLSResults.tvalues statsmodels.regression.recursive\_ls.RecursiveLSResults.tvalues =============================================================== `RecursiveLSResults.tvalues()` Return the t-statistic for a given parameter estimate. statsmodels statsmodels.genmod.families.links.probit.deriv statsmodels.genmod.families.links.probit.deriv ============================================== `probit.deriv(p)` Derivative of CDF link | Parameters: | **p** (*array-like*) – mean parameters | | Returns: | **g’(p)** – The derivative of CDF transform at `p` | | Return type: | array | #### Notes g’(`p`) = 1./ `dbn`.pdf(`dbn`.ppf(`p`)) statsmodels statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.loglikeobs statsmodels.tsa.regime\_switching.markov\_regression.MarkovRegression.loglikeobs ================================================================================ `MarkovRegression.loglikeobs(params, transformed=True)` Loglikelihood evaluation for each period | Parameters: | * **params** (*array\_like*) – Array of parameters at which to evaluate the loglikelihood function. * **transformed** (*boolean**,* *optional*) – Whether or not `params` is already transformed. Default is True. | statsmodels statsmodels.discrete.discrete_model.CountResults.remove_data statsmodels.discrete.discrete\_model.CountResults.remove\_data ============================================================== `CountResults.remove_data()` remove data arrays, all nobs arrays from result and model This reduces the size of the instance, so it can be pickled with less memory. Currently tested for use with predict from an unpickled results and model instance. Warning Since data and some intermediate results have been removed calculating new statistics that require them will raise exceptions. The exception will occur the first time an attribute is accessed that has been set to None. Not fully tested for time series models, tsa, and might delete too much for prediction or not all that would be possible. The lists of arrays to delete are maintained as attributes of the result and model instance, except for cached values. These lists could be changed before calling remove\_data. The attributes to remove are named in: `model._data_attr : arrays attached to both the model instance` and the results instance with the same attribute name. `result.data_in_cache : arrays that may exist as values in` result.\_cache (TODO : should privatize name) `result._data_attr_model : arrays attached to the model` instance but not to the results instance statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.score statsmodels.tsa.statespace.dynamic\_factor.DynamicFactor.score ============================================================== `DynamicFactor.score(params, *args, **kwargs)` Compute the score function at params. | Parameters: | * **params** (*array\_like*) – Array of parameters at which to evaluate the score. * **args** – Additional positional arguments to the `loglike` method. * **kwargs** – Additional keyword arguments to the `loglike` method. | | Returns: | **score** – Score, evaluated at `params`. | | Return type: | array | #### Notes This is a numerical approximation, calculated using first-order complex step differentiation on the `loglike` method. Both \*args and \*\*kwargs are necessary because the optimizer from `fit` must call this function and only supports passing arguments via \*args (for example `scipy.optimize.fmin_l_bfgs`). statsmodels statsmodels.genmod.families.family.Gaussian statsmodels.genmod.families.family.Gaussian =========================================== `class statsmodels.genmod.families.family.Gaussian(link=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/family.html#Gaussian) Gaussian exponential family distribution. | Parameters: | **link** (*a link instance**,* *optional*) – The default link for the Gaussian family is the identity link. Available links are log, identity, and inverse. See statsmodels.genmod.families.links for more information. | `link` *a link instance* – The link function of the Gaussian instance `variance` *varfunc instance* – `variance` is an instance of statsmodels.genmod.families.varfuncs.constant See also [`statsmodels.genmod.families.family.Family`](statsmodels.genmod.families.family.family#statsmodels.genmod.families.family.Family "statsmodels.genmod.families.family.Family"), [Link Functions](../glm#links) #### Methods | | | | --- | --- | | [`deviance`](statsmodels.genmod.families.family.gaussian.deviance#statsmodels.genmod.families.family.Gaussian.deviance "statsmodels.genmod.families.family.Gaussian.deviance")(endog, mu[, var\_weights, …]) | The deviance function evaluated at (endog, mu, var\_weights, freq\_weights, scale) for the distribution. | | [`fitted`](statsmodels.genmod.families.family.gaussian.fitted#statsmodels.genmod.families.family.Gaussian.fitted "statsmodels.genmod.families.family.Gaussian.fitted")(lin\_pred) | Fitted values based on linear predictors lin\_pred. | | [`loglike`](statsmodels.genmod.families.family.gaussian.loglike#statsmodels.genmod.families.family.Gaussian.loglike "statsmodels.genmod.families.family.Gaussian.loglike")(endog, mu[, var\_weights, …]) | The log-likelihood function in terms of the fitted mean response. | | [`loglike_obs`](statsmodels.genmod.families.family.gaussian.loglike_obs#statsmodels.genmod.families.family.Gaussian.loglike_obs "statsmodels.genmod.families.family.Gaussian.loglike_obs")(endog, mu[, var\_weights, scale]) | The log-likelihood function for each observation in terms of the fitted mean response for the Gaussian distribution. | | [`predict`](statsmodels.genmod.families.family.gaussian.predict#statsmodels.genmod.families.family.Gaussian.predict "statsmodels.genmod.families.family.Gaussian.predict")(mu) | Linear predictors based on given mu values. | | [`resid_anscombe`](statsmodels.genmod.families.family.gaussian.resid_anscombe#statsmodels.genmod.families.family.Gaussian.resid_anscombe "statsmodels.genmod.families.family.Gaussian.resid_anscombe")(endog, mu[, var\_weights, scale]) | The Anscombe residuals | | [`resid_dev`](statsmodels.genmod.families.family.gaussian.resid_dev#statsmodels.genmod.families.family.Gaussian.resid_dev "statsmodels.genmod.families.family.Gaussian.resid_dev")(endog, mu[, var\_weights, scale]) | The deviance residuals | | [`starting_mu`](statsmodels.genmod.families.family.gaussian.starting_mu#statsmodels.genmod.families.family.Gaussian.starting_mu "statsmodels.genmod.families.family.Gaussian.starting_mu")(y) | Starting value for mu in the IRLS algorithm. | | [`weights`](statsmodels.genmod.families.family.gaussian.weights#statsmodels.genmod.families.family.Gaussian.weights "statsmodels.genmod.families.family.Gaussian.weights")(mu) | Weights for IRLS steps | statsmodels statsmodels.genmod.generalized_linear_model.GLMResults.load statsmodels.genmod.generalized\_linear\_model.GLMResults.load ============================================================= `classmethod GLMResults.load(fname)` load a pickle, (class method) | Parameters: | **fname** (*string* *or* *filehandle*) – fname can be a string to a file path or filename, or a filehandle. | | Returns: | | | Return type: | unpickled instance | statsmodels statsmodels.sandbox.regression.gmm.LinearIVGMM.start_weights statsmodels.sandbox.regression.gmm.LinearIVGMM.start\_weights ============================================================= `LinearIVGMM.start_weights(inv=True)` statsmodels statsmodels.stats.moment_helpers.mvsk2mnc statsmodels.stats.moment\_helpers.mvsk2mnc ========================================== `statsmodels.stats.moment_helpers.mvsk2mnc(args)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/moment_helpers.html#mvsk2mnc) convert mean, variance, skew, kurtosis to non-central moments statsmodels statsmodels.regression.mixed_linear_model.MixedLM.score statsmodels.regression.mixed\_linear\_model.MixedLM.score ========================================================= `MixedLM.score(params, profile_fe=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/mixed_linear_model.html#MixedLM.score) Returns the score vector of the profile log-likelihood. #### Notes The score vector that is returned is computed with respect to the parameterization defined by this model instance’s `use_sqrt` attribute. statsmodels statsmodels.tsa.kalmanf.kalmanfilter.KalmanFilter.R statsmodels.tsa.kalmanf.kalmanfilter.KalmanFilter.R =================================================== `classmethod KalmanFilter.R(params, r, k, q, p)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/kalmanf/kalmanfilter.html#KalmanFilter.R) The coefficient matrix for the state vector in the observation equation. Its dimension is r+k x 1. | Parameters: | * **r** (*int*) – In the context of the ARMA model r is max(p,q+1) where p is the AR order and q is the MA order. * **k** (*int*) – The number of exogenous variables in the ARMA model, including the constant if appropriate. * **q** (*int*) – The MA order in an ARMA model. * **p** (*int*) – The AR order in an ARMA model. | #### References Durbin and Koopman Section 3.7. statsmodels statsmodels.regression.quantile_regression.QuantRegResults.HC2_se statsmodels.regression.quantile\_regression.QuantRegResults.HC2\_se =================================================================== `QuantRegResults.HC2_se()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/quantile_regression.html#QuantRegResults.HC2_se) See statsmodels.RegressionResults statsmodels statsmodels.tsa.statespace.varmax.VARMAXResults.get_forecast statsmodels.tsa.statespace.varmax.VARMAXResults.get\_forecast ============================================================= `VARMAXResults.get_forecast(steps=1, **kwargs)` Out-of-sample forecasts | Parameters: | * **steps** (*int**,* *str**, or* *datetime**,* *optional*) – If an integer, the number of steps to forecast from the end of the sample. Can also be a date string to parse or a datetime type. However, if the dates index does not have a fixed frequency, steps must be an integer. Default * **\*\*kwargs** – Additional arguments may required for forecasting beyond the end of the sample. See `FilterResults.predict` for more details. | | Returns: | **forecast** – Array of out of sample forecasts. A (steps x k\_endog) array. | | Return type: | array | statsmodels statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.tvalues statsmodels.discrete.count\_model.ZeroInflatedGeneralizedPoissonResults.tvalues =============================================================================== `ZeroInflatedGeneralizedPoissonResults.tvalues()` Return the t-statistic for a given parameter estimate. statsmodels statsmodels.tsa.statespace.varmax.VARMAX.smooth statsmodels.tsa.statespace.varmax.VARMAX.smooth =============================================== `VARMAX.smooth(params, transformed=True, complex_step=False, cov_type=None, cov_kwds=None, return_ssm=False, results_class=None, results_wrapper_class=None, **kwargs)` Kalman smoothing | Parameters: | * **params** (*array\_like*) – Array of parameters at which to evaluate the loglikelihood function. * **transformed** (*boolean**,* *optional*) – Whether or not `params` is already transformed. Default is True. * **return\_ssm** (*boolean**,**optional*) – Whether or not to return only the state space output or a full results object. Default is to return a full results object. * **cov\_type** (*str**,* *optional*) – See `MLEResults.fit` for a description of covariance matrix types for results object. * **cov\_kwds** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)") *or* *None**,* *optional*) – See `MLEResults.get_robustcov_results` for a description required keywords for alternative covariance estimators * **\*\*kwargs** – Additional keyword arguments to pass to the Kalman filter. See `KalmanFilter.filter` for more details. | statsmodels statsmodels.genmod.families.family.Gamma.loglike_obs statsmodels.genmod.families.family.Gamma.loglike\_obs ===================================================== `Gamma.loglike_obs(endog, mu, var_weights=1.0, scale=1.0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/family.html#Gamma.loglike_obs) The log-likelihood function for each observation in terms of the fitted mean response for the Gamma distribution. | Parameters: | * **endog** (*array*) – Usually the endogenous response variable. * **mu** (*array*) – Usually but not always the fitted mean response variable. * **var\_weights** (*array-like*) – 1d array of variance (analytic) weights. The default is 1. * **scale** (*float*) – The scale parameter. The default is 1. | | Returns: | **ll\_i** – The value of the loglikelihood evaluated at (endog, mu, var\_weights, scale) as defined below. | | Return type: | float | #### Notes \[ll\_i = var\\_weights\_i / scale \* (\ln(var\\_weights\_i \* endog\_i / (scale \* \mu\_i)) - (var\\_weights\_i \* endog\_i) / (scale \* \mu\_i)) - \ln \Gamma(var\\_weights\_i / scale) - \ln(\mu\_i)\] statsmodels statsmodels.regression.recursive_ls.RecursiveLSResults statsmodels.regression.recursive\_ls.RecursiveLSResults ======================================================= `class statsmodels.regression.recursive_ls.RecursiveLSResults(model, params, filter_results, cov_type='opg', **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/recursive_ls.html#RecursiveLSResults) Class to hold results from fitting a recursive least squares model. | Parameters: | **model** (*RecursiveLS instance*) – The fitted model instance | `specification` *dictionary* – Dictionary including all attributes from the recursive least squares model instance. See also [`statsmodels.tsa.statespace.kalman_filter.FilterResults`](statsmodels.tsa.statespace.kalman_filter.filterresults#statsmodels.tsa.statespace.kalman_filter.FilterResults "statsmodels.tsa.statespace.kalman_filter.FilterResults"), [`statsmodels.tsa.statespace.mlemodel.MLEResults`](statsmodels.tsa.statespace.mlemodel.mleresults#statsmodels.tsa.statespace.mlemodel.MLEResults "statsmodels.tsa.statespace.mlemodel.MLEResults") #### Methods | | | | --- | --- | | [`aic`](statsmodels.regression.recursive_ls.recursivelsresults.aic#statsmodels.regression.recursive_ls.RecursiveLSResults.aic "statsmodels.regression.recursive_ls.RecursiveLSResults.aic")() | (float) Akaike Information Criterion | | [`bic`](statsmodels.regression.recursive_ls.recursivelsresults.bic#statsmodels.regression.recursive_ls.RecursiveLSResults.bic "statsmodels.regression.recursive_ls.RecursiveLSResults.bic")() | (float) Bayes Information Criterion | | [`bse`](statsmodels.regression.recursive_ls.recursivelsresults.bse#statsmodels.regression.recursive_ls.RecursiveLSResults.bse "statsmodels.regression.recursive_ls.RecursiveLSResults.bse")() | | | [`conf_int`](statsmodels.regression.recursive_ls.recursivelsresults.conf_int#statsmodels.regression.recursive_ls.RecursiveLSResults.conf_int "statsmodels.regression.recursive_ls.RecursiveLSResults.conf_int")([alpha, cols, method]) | Returns the confidence interval of the fitted parameters. | | [`cov_params`](statsmodels.regression.recursive_ls.recursivelsresults.cov_params#statsmodels.regression.recursive_ls.RecursiveLSResults.cov_params "statsmodels.regression.recursive_ls.RecursiveLSResults.cov_params")([r\_matrix, column, scale, cov\_p, …]) | Returns the variance/covariance matrix. | | [`cov_params_approx`](statsmodels.regression.recursive_ls.recursivelsresults.cov_params_approx#statsmodels.regression.recursive_ls.RecursiveLSResults.cov_params_approx "statsmodels.regression.recursive_ls.RecursiveLSResults.cov_params_approx")() | (array) The variance / covariance matrix. | | [`cov_params_oim`](statsmodels.regression.recursive_ls.recursivelsresults.cov_params_oim#statsmodels.regression.recursive_ls.RecursiveLSResults.cov_params_oim "statsmodels.regression.recursive_ls.RecursiveLSResults.cov_params_oim")() | (array) The variance / covariance matrix. | | [`cov_params_opg`](statsmodels.regression.recursive_ls.recursivelsresults.cov_params_opg#statsmodels.regression.recursive_ls.RecursiveLSResults.cov_params_opg "statsmodels.regression.recursive_ls.RecursiveLSResults.cov_params_opg")() | (array) The variance / covariance matrix. | | [`cov_params_robust`](statsmodels.regression.recursive_ls.recursivelsresults.cov_params_robust#statsmodels.regression.recursive_ls.RecursiveLSResults.cov_params_robust "statsmodels.regression.recursive_ls.RecursiveLSResults.cov_params_robust")() | (array) The QMLE variance / covariance matrix. | | [`cov_params_robust_approx`](statsmodels.regression.recursive_ls.recursivelsresults.cov_params_robust_approx#statsmodels.regression.recursive_ls.RecursiveLSResults.cov_params_robust_approx "statsmodels.regression.recursive_ls.RecursiveLSResults.cov_params_robust_approx")() | (array) The QMLE variance / covariance matrix. | | [`cov_params_robust_oim`](statsmodels.regression.recursive_ls.recursivelsresults.cov_params_robust_oim#statsmodels.regression.recursive_ls.RecursiveLSResults.cov_params_robust_oim "statsmodels.regression.recursive_ls.RecursiveLSResults.cov_params_robust_oim")() | (array) The QMLE variance / covariance matrix. | | [`cusum`](statsmodels.regression.recursive_ls.recursivelsresults.cusum#statsmodels.regression.recursive_ls.RecursiveLSResults.cusum "statsmodels.regression.recursive_ls.RecursiveLSResults.cusum")() | Cumulative sum of standardized recursive residuals statistics | | [`cusum_squares`](statsmodels.regression.recursive_ls.recursivelsresults.cusum_squares#statsmodels.regression.recursive_ls.RecursiveLSResults.cusum_squares "statsmodels.regression.recursive_ls.RecursiveLSResults.cusum_squares")() | Cumulative sum of squares of standardized recursive residuals statistics | | [`f_test`](statsmodels.regression.recursive_ls.recursivelsresults.f_test#statsmodels.regression.recursive_ls.RecursiveLSResults.f_test "statsmodels.regression.recursive_ls.RecursiveLSResults.f_test")(r\_matrix[, cov\_p, scale, invcov]) | Compute the F-test for a joint linear hypothesis. | | [`fittedvalues`](statsmodels.regression.recursive_ls.recursivelsresults.fittedvalues#statsmodels.regression.recursive_ls.RecursiveLSResults.fittedvalues "statsmodels.regression.recursive_ls.RecursiveLSResults.fittedvalues")() | (array) The predicted values of the model. | | [`forecast`](statsmodels.regression.recursive_ls.recursivelsresults.forecast#statsmodels.regression.recursive_ls.RecursiveLSResults.forecast "statsmodels.regression.recursive_ls.RecursiveLSResults.forecast")([steps]) | Out-of-sample forecasts | | [`get_forecast`](statsmodels.regression.recursive_ls.recursivelsresults.get_forecast#statsmodels.regression.recursive_ls.RecursiveLSResults.get_forecast "statsmodels.regression.recursive_ls.RecursiveLSResults.get_forecast")([steps]) | Out-of-sample forecasts | | [`get_prediction`](statsmodels.regression.recursive_ls.recursivelsresults.get_prediction#statsmodels.regression.recursive_ls.RecursiveLSResults.get_prediction "statsmodels.regression.recursive_ls.RecursiveLSResults.get_prediction")([start, end, dynamic, index]) | In-sample prediction and out-of-sample forecasting | | [`hqic`](statsmodels.regression.recursive_ls.recursivelsresults.hqic#statsmodels.regression.recursive_ls.RecursiveLSResults.hqic "statsmodels.regression.recursive_ls.RecursiveLSResults.hqic")() | (float) Hannan-Quinn Information Criterion | | [`impulse_responses`](statsmodels.regression.recursive_ls.recursivelsresults.impulse_responses#statsmodels.regression.recursive_ls.RecursiveLSResults.impulse_responses "statsmodels.regression.recursive_ls.RecursiveLSResults.impulse_responses")([steps, impulse, …]) | Impulse response function | | [`info_criteria`](statsmodels.regression.recursive_ls.recursivelsresults.info_criteria#statsmodels.regression.recursive_ls.RecursiveLSResults.info_criteria "statsmodels.regression.recursive_ls.RecursiveLSResults.info_criteria")(criteria[, method]) | Information criteria | | [`initialize`](statsmodels.regression.recursive_ls.recursivelsresults.initialize#statsmodels.regression.recursive_ls.RecursiveLSResults.initialize "statsmodels.regression.recursive_ls.RecursiveLSResults.initialize")(model, params, \*\*kwd) | | | [`llf`](statsmodels.regression.recursive_ls.recursivelsresults.llf#statsmodels.regression.recursive_ls.RecursiveLSResults.llf "statsmodels.regression.recursive_ls.RecursiveLSResults.llf")() | (float) The value of the log-likelihood function evaluated at `params`. | | [`llf_obs`](statsmodels.regression.recursive_ls.recursivelsresults.llf_obs#statsmodels.regression.recursive_ls.RecursiveLSResults.llf_obs "statsmodels.regression.recursive_ls.RecursiveLSResults.llf_obs")() | (float) The value of the log-likelihood function evaluated at `params`. | | [`load`](statsmodels.regression.recursive_ls.recursivelsresults.load#statsmodels.regression.recursive_ls.RecursiveLSResults.load "statsmodels.regression.recursive_ls.RecursiveLSResults.load")(fname) | load a pickle, (class method) | | [`loglikelihood_burn`](statsmodels.regression.recursive_ls.recursivelsresults.loglikelihood_burn#statsmodels.regression.recursive_ls.RecursiveLSResults.loglikelihood_burn "statsmodels.regression.recursive_ls.RecursiveLSResults.loglikelihood_burn")() | (float) The number of observations during which the likelihood is not evaluated. | | [`normalized_cov_params`](statsmodels.regression.recursive_ls.recursivelsresults.normalized_cov_params#statsmodels.regression.recursive_ls.RecursiveLSResults.normalized_cov_params "statsmodels.regression.recursive_ls.RecursiveLSResults.normalized_cov_params")() | | | [`plot_cusum`](statsmodels.regression.recursive_ls.recursivelsresults.plot_cusum#statsmodels.regression.recursive_ls.RecursiveLSResults.plot_cusum "statsmodels.regression.recursive_ls.RecursiveLSResults.plot_cusum")([alpha, legend\_loc, fig, figsize]) | Plot the CUSUM statistic and significance bounds. | | [`plot_cusum_squares`](statsmodels.regression.recursive_ls.recursivelsresults.plot_cusum_squares#statsmodels.regression.recursive_ls.RecursiveLSResults.plot_cusum_squares "statsmodels.regression.recursive_ls.RecursiveLSResults.plot_cusum_squares")([alpha, legend\_loc, fig, …]) | Plot the CUSUM of squares statistic and significance bounds. | | [`plot_diagnostics`](statsmodels.regression.recursive_ls.recursivelsresults.plot_diagnostics#statsmodels.regression.recursive_ls.RecursiveLSResults.plot_diagnostics "statsmodels.regression.recursive_ls.RecursiveLSResults.plot_diagnostics")([variable, lags, fig, figsize]) | Diagnostic plots for standardized residuals of one endogenous variable | | [`plot_recursive_coefficient`](statsmodels.regression.recursive_ls.recursivelsresults.plot_recursive_coefficient#statsmodels.regression.recursive_ls.RecursiveLSResults.plot_recursive_coefficient "statsmodels.regression.recursive_ls.RecursiveLSResults.plot_recursive_coefficient")([variables, …]) | Plot the recursively estimated coefficients on a given variable | | [`predict`](statsmodels.regression.recursive_ls.recursivelsresults.predict#statsmodels.regression.recursive_ls.RecursiveLSResults.predict "statsmodels.regression.recursive_ls.RecursiveLSResults.predict")([start, end, dynamic]) | In-sample prediction and out-of-sample forecasting | | [`pvalues`](statsmodels.regression.recursive_ls.recursivelsresults.pvalues#statsmodels.regression.recursive_ls.RecursiveLSResults.pvalues "statsmodels.regression.recursive_ls.RecursiveLSResults.pvalues")() | (array) The p-values associated with the z-statistics of the coefficients. | | [`remove_data`](statsmodels.regression.recursive_ls.recursivelsresults.remove_data#statsmodels.regression.recursive_ls.RecursiveLSResults.remove_data "statsmodels.regression.recursive_ls.RecursiveLSResults.remove_data")() | remove data arrays, all nobs arrays from result and model | | [`resid`](statsmodels.regression.recursive_ls.recursivelsresults.resid#statsmodels.regression.recursive_ls.RecursiveLSResults.resid "statsmodels.regression.recursive_ls.RecursiveLSResults.resid")() | (array) The model residuals. | | [`resid_recursive`](statsmodels.regression.recursive_ls.recursivelsresults.resid_recursive#statsmodels.regression.recursive_ls.RecursiveLSResults.resid_recursive "statsmodels.regression.recursive_ls.RecursiveLSResults.resid_recursive")() | Recursive residuals | | [`save`](statsmodels.regression.recursive_ls.recursivelsresults.save#statsmodels.regression.recursive_ls.RecursiveLSResults.save "statsmodels.regression.recursive_ls.RecursiveLSResults.save")(fname[, remove\_data]) | save a pickle of this instance | | [`simulate`](statsmodels.regression.recursive_ls.recursivelsresults.simulate#statsmodels.regression.recursive_ls.RecursiveLSResults.simulate "statsmodels.regression.recursive_ls.RecursiveLSResults.simulate")(nsimulations[, measurement\_shocks, …]) | Simulate a new time series following the state space model | | [`summary`](statsmodels.regression.recursive_ls.recursivelsresults.summary#statsmodels.regression.recursive_ls.RecursiveLSResults.summary "statsmodels.regression.recursive_ls.RecursiveLSResults.summary")([alpha, start, title, model\_name, …]) | Summarize the Model | | [`t_test`](statsmodels.regression.recursive_ls.recursivelsresults.t_test#statsmodels.regression.recursive_ls.RecursiveLSResults.t_test "statsmodels.regression.recursive_ls.RecursiveLSResults.t_test")(r\_matrix[, cov\_p, scale, use\_t]) | Compute a t-test for a each linear hypothesis of the form Rb = q | | [`t_test_pairwise`](statsmodels.regression.recursive_ls.recursivelsresults.t_test_pairwise#statsmodels.regression.recursive_ls.RecursiveLSResults.t_test_pairwise "statsmodels.regression.recursive_ls.RecursiveLSResults.t_test_pairwise")(term\_name[, method, alpha, …]) | perform pairwise t\_test with multiple testing corrected p-values | | [`test_heteroskedasticity`](statsmodels.regression.recursive_ls.recursivelsresults.test_heteroskedasticity#statsmodels.regression.recursive_ls.RecursiveLSResults.test_heteroskedasticity "statsmodels.regression.recursive_ls.RecursiveLSResults.test_heteroskedasticity")(method[, …]) | Test for heteroskedasticity of standardized residuals | | [`test_normality`](statsmodels.regression.recursive_ls.recursivelsresults.test_normality#statsmodels.regression.recursive_ls.RecursiveLSResults.test_normality "statsmodels.regression.recursive_ls.RecursiveLSResults.test_normality")(method) | Test for normality of standardized residuals. | | [`test_serial_correlation`](statsmodels.regression.recursive_ls.recursivelsresults.test_serial_correlation#statsmodels.regression.recursive_ls.RecursiveLSResults.test_serial_correlation "statsmodels.regression.recursive_ls.RecursiveLSResults.test_serial_correlation")(method[, lags]) | Ljung-box test for no serial correlation of standardized residuals | | [`tvalues`](statsmodels.regression.recursive_ls.recursivelsresults.tvalues#statsmodels.regression.recursive_ls.RecursiveLSResults.tvalues "statsmodels.regression.recursive_ls.RecursiveLSResults.tvalues")() | Return the t-statistic for a given parameter estimate. | | [`wald_test`](statsmodels.regression.recursive_ls.recursivelsresults.wald_test#statsmodels.regression.recursive_ls.RecursiveLSResults.wald_test "statsmodels.regression.recursive_ls.RecursiveLSResults.wald_test")(r\_matrix[, cov\_p, scale, invcov, …]) | Compute a Wald-test for a joint linear hypothesis. | | [`wald_test_terms`](statsmodels.regression.recursive_ls.recursivelsresults.wald_test_terms#statsmodels.regression.recursive_ls.RecursiveLSResults.wald_test_terms "statsmodels.regression.recursive_ls.RecursiveLSResults.wald_test_terms")([skip\_single, …]) | Compute a sequence of Wald tests for terms over multiple columns | | [`zvalues`](statsmodels.regression.recursive_ls.recursivelsresults.zvalues#statsmodels.regression.recursive_ls.RecursiveLSResults.zvalues "statsmodels.regression.recursive_ls.RecursiveLSResults.zvalues")() | (array) The z-statistics for the coefficients. | #### Attributes | | | | --- | --- | | `recursive_coefficients` | Estimates of regression coefficients, recursively estimated | | `use_t` | |
programming_docs
statsmodels statsmodels.genmod.generalized_estimating_equations.GEEResults.t_test_pairwise statsmodels.genmod.generalized\_estimating\_equations.GEEResults.t\_test\_pairwise ================================================================================== `GEEResults.t_test_pairwise(term_name, method='hs', alpha=0.05, factor_labels=None)` perform pairwise t\_test with multiple testing corrected p-values This uses the formula design\_info encoding contrast matrix and should work for all encodings of a main effect. | Parameters: | * **result** (*result instance*) – The results of an estimated model with a categorical main effect. * **term\_name** (*str*) – name of the term for which pairwise comparisons are computed. Term names for categorical effects are created by patsy and correspond to the main part of the exog names. * **method** (*str* *or* *list of strings*) – multiple testing p-value correction, default is ‘hs’, see stats.multipletesting * **alpha** (*float*) – significance level for multiple testing reject decision. * **factor\_labels** (*None**,* *list of str*) – Labels for the factor levels used for pairwise labels. If not provided, then the labels from the formula design\_info are used. | | Returns: | **results** – The results are stored as attributes, the main attributes are the following two. Other attributes are added for debugging purposes or as background information.* result\_frame : pandas DataFrame with t\_test results and multiple testing corrected p-values. * contrasts : matrix of constraints of the null hypothesis in the t\_test. | | Return type: | instance of a simple Results class | #### Notes Status: experimental. Currently only checked for treatment coding with and without specified reference level. Currently there are no multiple testing corrected confidence intervals available. #### Examples ``` >>> res = ols("np.log(Days+1) ~ C(Weight) + C(Duration)", data).fit() >>> pw = res.t_test_pairwise("C(Weight)") >>> pw.result_frame coef std err t P>|t| Conf. Int. Low 2-1 0.632315 0.230003 2.749157 8.028083e-03 0.171563 3-1 1.302555 0.230003 5.663201 5.331513e-07 0.841803 3-2 0.670240 0.230003 2.914044 5.119126e-03 0.209488 Conf. Int. Upp. pvalue-hs reject-hs 2-1 1.093067 0.010212 True 3-1 1.763307 0.000002 True 3-2 1.130992 0.010212 True ``` statsmodels statsmodels.sandbox.regression.gmm.IVGMMResults.cov_params statsmodels.sandbox.regression.gmm.IVGMMResults.cov\_params =========================================================== `IVGMMResults.cov_params(r_matrix=None, column=None, scale=None, cov_p=None, other=None)` Returns the variance/covariance matrix. The variance/covariance matrix can be of a linear contrast of the estimates of params or all params multiplied by scale which will usually be an estimate of sigma^2. Scale is assumed to be a scalar. | Parameters: | * **r\_matrix** (*array-like*) – Can be 1d, or 2d. Can be used alone or with other. * **column** (*array-like**,* *optional*) – Must be used on its own. Can be 0d or 1d see below. * **scale** (*float**,* *optional*) – Can be specified or not. Default is None, which means that the scale argument is taken from the model. * **other** (*array-like**,* *optional*) – Can be used when r\_matrix is specified. | | Returns: | **cov** – covariance matrix of the parameter estimates or of linear combination of parameter estimates. See Notes. | | Return type: | ndarray | #### Notes (The below are assumed to be in matrix notation.) If no argument is specified returns the covariance matrix of a model `(scale)*(X.T X)^(-1)` If contrast is specified it pre and post-multiplies as follows `(scale) * r_matrix (X.T X)^(-1) r_matrix.T` If contrast and other are specified returns `(scale) * r_matrix (X.T X)^(-1) other.T` If column is specified returns `(scale) * (X.T X)^(-1)[column,column]` if column is 0d OR `(scale) * (X.T X)^(-1)[column][:,column]` if column is 1d statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.wald_test_terms statsmodels.sandbox.regression.gmm.IVRegressionResults.wald\_test\_terms ======================================================================== `IVRegressionResults.wald_test_terms(skip_single=False, extra_constraints=None, combine_terms=None)` Compute a sequence of Wald tests for terms over multiple columns This computes joined Wald tests for the hypothesis that all coefficients corresponding to a `term` are zero. `Terms` are defined by the underlying formula or by string matching. | Parameters: | * **skip\_single** (*boolean*) – If true, then terms that consist only of a single column and, therefore, refers only to a single parameter is skipped. If false, then all terms are included. * **extra\_constraints** (*ndarray*) – not tested yet * **combine\_terms** (*None* *or* *list of strings*) – Each string in this list is matched to the name of the terms or the name of the exogenous variables. All columns whose name includes that string are combined in one joint test. | | Returns: | **test\_result** – The result instance contains `table` which is a pandas DataFrame with the test results: test statistic, degrees of freedom and pvalues. | | Return type: | result instance | #### Examples ``` >>> res_ols = ols("np.log(Days+1) ~ C(Duration, Sum)*C(Weight, Sum)", data).fit() >>> res_ols.wald_test_terms() <class 'statsmodels.stats.contrast.WaldTestResults'> F P>F df constraint df denom Intercept 279.754525 2.37985521351e-22 1 51 C(Duration, Sum) 5.367071 0.0245738436636 1 51 C(Weight, Sum) 12.432445 3.99943118767e-05 2 51 C(Duration, Sum):C(Weight, Sum) 0.176002 0.83912310946 2 51 ``` ``` >>> res_poi = Poisson.from_formula("Days ~ C(Weight) * C(Duration)", data).fit(cov_type='HC0') >>> wt = res_poi.wald_test_terms(skip_single=False, combine_terms=['Duration', 'Weight']) >>> print(wt) chi2 P>chi2 df constraint Intercept 15.695625 7.43960374424e-05 1 C(Weight) 16.132616 0.000313940174705 2 C(Duration) 1.009147 0.315107378931 1 C(Weight):C(Duration) 0.216694 0.897315972824 2 Duration 11.187849 0.010752286833 3 Weight 30.263368 4.32586407145e-06 4 ``` statsmodels statsmodels.stats.weightstats.DescrStatsW.std_mean statsmodels.stats.weightstats.DescrStatsW.std\_mean =================================================== `DescrStatsW.std_mean()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/weightstats.html#DescrStatsW.std_mean) standard deviation of weighted mean statsmodels statsmodels.discrete.discrete_model.Poisson.information statsmodels.discrete.discrete\_model.Poisson.information ======================================================== `Poisson.information(params)` Fisher information matrix of model Returns -Hessian of loglike evaluated at params. statsmodels statsmodels.robust.norms.TrimmedMean.rho statsmodels.robust.norms.TrimmedMean.rho ======================================== `TrimmedMean.rho(z)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/norms.html#TrimmedMean.rho) The robust criterion function for least trimmed mean. | Parameters: | **z** (*array-like*) – 1d array | | Returns: | **rho** – rho(z) = (1/2.)\*z\*\*2 for |z| <= crho(z) = 0 for |z| > c | | Return type: | array | statsmodels statsmodels.sandbox.regression.try_ols_anova.dropname statsmodels.sandbox.regression.try\_ols\_anova.dropname ======================================================= `statsmodels.sandbox.regression.try_ols_anova.dropname(ss, li)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/try_ols_anova.html#dropname) drop names from a list of strings, names to drop are in space delimeted list does not change original list statsmodels statsmodels.duration.hazard_regression.PHReg.breslow_hessian statsmodels.duration.hazard\_regression.PHReg.breslow\_hessian ============================================================== `PHReg.breslow_hessian(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/duration/hazard_regression.html#PHReg.breslow_hessian) Returns the Hessian of the log partial likelihood evaluated at `params`, using the Breslow method to handle tied times. statsmodels statsmodels.discrete.discrete_model.BinaryResults.normalized_cov_params statsmodels.discrete.discrete\_model.BinaryResults.normalized\_cov\_params ========================================================================== `BinaryResults.normalized_cov_params()` statsmodels statsmodels.stats.power.tt_ind_solve_power statsmodels.stats.power.tt\_ind\_solve\_power ============================================= `statsmodels.stats.power.tt_ind_solve_power = <bound method TTestIndPower.solve_power of <statsmodels.stats.power.TTestIndPower object>>` solve for any one parameter of the power of a two sample t-test for t-test the keywords are: effect\_size, nobs1, alpha, power, ratio exactly one needs to be `None`, all others need numeric values | Parameters: | * **effect\_size** (*float*) – standardized effect size, difference between the two means divided by the standard deviation. `effect_size` has to be positive. * **nobs1** (*int* *or* *float*) – number of observations of sample 1. The number of observations of sample two is ratio times the size of sample 1, i.e. `nobs2 = nobs1 * ratio` * **alpha** (*float in interval* *(**0**,**1**)*) – significance level, e.g. 0.05, is the probability of a type I error, that is wrong rejections if the Null Hypothesis is true. * **power** (*float in interval* *(**0**,**1**)*) – power of the test, e.g. 0.8, is one minus the probability of a type II error. Power is the probability that the test correctly rejects the Null Hypothesis if the Alternative Hypothesis is true. * **ratio** (*float*) – ratio of the number of observations in sample 2 relative to sample 1. see description of nobs1 The default for ratio is 1; to solve for ratio given the other arguments it has to be explicitly set to None. * **alternative** (*string**,* *'two-sided'* *(**default**)**,* *'larger'**,* *'smaller'*) – extra argument to choose whether the power is calculated for a two-sided (default) or one sided test. The one-sided test can be either ‘larger’, ‘smaller’. | | Returns: | **value** – The value of the parameter that was set to None in the call. The value solves the power equation given the remaining parameters. | | Return type: | float | #### Notes The function uses scipy.optimize for finding the value that satisfies the power equation. It first uses `brentq` with a prior search for bounds. If this fails to find a root, `fsolve` is used. If `fsolve` also fails, then, for `alpha`, `power` and `effect_size`, `brentq` with fixed bounds is used. However, there can still be cases where this fails. statsmodels statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialResults.t_test_pairwise statsmodels.discrete.count\_model.ZeroInflatedNegativeBinomialResults.t\_test\_pairwise ======================================================================================= `ZeroInflatedNegativeBinomialResults.t_test_pairwise(term_name, method='hs', alpha=0.05, factor_labels=None)` perform pairwise t\_test with multiple testing corrected p-values This uses the formula design\_info encoding contrast matrix and should work for all encodings of a main effect. | Parameters: | * **result** (*result instance*) – The results of an estimated model with a categorical main effect. * **term\_name** (*str*) – name of the term for which pairwise comparisons are computed. Term names for categorical effects are created by patsy and correspond to the main part of the exog names. * **method** (*str* *or* *list of strings*) – multiple testing p-value correction, default is ‘hs’, see stats.multipletesting * **alpha** (*float*) – significance level for multiple testing reject decision. * **factor\_labels** (*None**,* *list of str*) – Labels for the factor levels used for pairwise labels. If not provided, then the labels from the formula design\_info are used. | | Returns: | **results** – The results are stored as attributes, the main attributes are the following two. Other attributes are added for debugging purposes or as background information.* result\_frame : pandas DataFrame with t\_test results and multiple testing corrected p-values. * contrasts : matrix of constraints of the null hypothesis in the t\_test. | | Return type: | instance of a simple Results class | #### Notes Status: experimental. Currently only checked for treatment coding with and without specified reference level. Currently there are no multiple testing corrected confidence intervals available. #### Examples ``` >>> res = ols("np.log(Days+1) ~ C(Weight) + C(Duration)", data).fit() >>> pw = res.t_test_pairwise("C(Weight)") >>> pw.result_frame coef std err t P>|t| Conf. Int. Low 2-1 0.632315 0.230003 2.749157 8.028083e-03 0.171563 3-1 1.302555 0.230003 5.663201 5.331513e-07 0.841803 3-2 0.670240 0.230003 2.914044 5.119126e-03 0.209488 Conf. Int. Upp. pvalue-hs reject-hs 2-1 1.093067 0.010212 True 3-1 1.763307 0.000002 True 3-2 1.130992 0.010212 True ``` statsmodels statsmodels.tsa.vector_ar.vecm.VECMResults.conf_int_det_coef statsmodels.tsa.vector\_ar.vecm.VECMResults.conf\_int\_det\_coef ================================================================ `VECMResults.conf_int_det_coef(alpha=0.05)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/vecm.html#VECMResults.conf_int_det_coef) statsmodels statsmodels.discrete.discrete_model.BinaryResults.bic statsmodels.discrete.discrete\_model.BinaryResults.bic ====================================================== `BinaryResults.bic()` statsmodels statsmodels.multivariate.factor_rotation.promax statsmodels.multivariate.factor\_rotation.promax ================================================ `statsmodels.multivariate.factor_rotation.promax(A, k=2)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/multivariate/factor_rotation/_analytic_rotation.html#promax) Performs promax rotation of the matrix \(A\). This method was not very clear to me from the literature, this implementation is as I understand it should work. Promax rotation is performed in the following steps: * Deterine varimax rotated patterns \(V\). * Construct a rotation target matrix \(|V\_{ij}|^k/V\_{ij}\) * Perform procrustes rotation towards the target to obtain T * Determine the patterns First, varimax rotation a target matrix \(H\) is determined with orthogonal varimax rotation. Then, oblique target rotation is performed towards the target. | Parameters: | * **A** (*numpy matrix*) – non rotated factors * **k** (*float*) – parameter, should be positive | #### References [1] Browne (2001) - An overview of analytic rotation in exploratory factor analysis [2] Navarra, Simoncini (2010) - A guide to emprirical orthogonal functions for climate data analysis statsmodels statsmodels.tsa.varma_process.VarmaPoly.hstackarma_minus1 statsmodels.tsa.varma\_process.VarmaPoly.hstackarma\_minus1 =========================================================== `VarmaPoly.hstackarma_minus1()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/varma_process.html#VarmaPoly.hstackarma_minus1) stack ar and lagpolynomial vertically in 2d array this is the Kalman Filter representation, I think statsmodels statsmodels.tools.eval_measures.medianbias statsmodels.tools.eval\_measures.medianbias =========================================== `statsmodels.tools.eval_measures.medianbias(x1, x2, axis=0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tools/eval_measures.html#medianbias) median bias, median error | Parameters: | * **x2** (*x1**,*) – The performance measure depends on the difference between these two arrays. * **axis** (*int*) – axis along which the summary statistic is calculated | | Returns: | **medianbias** – median bias, or median difference along given axis. | | Return type: | ndarray or float | #### Notes If `x1` and `x2` have different shapes, then they need to broadcast. This uses `numpy.asanyarray` to convert the input. Whether this is the desired result or not depends on the array subclass. statsmodels statsmodels.stats.contingency_tables.Table.from_data statsmodels.stats.contingency\_tables.Table.from\_data ====================================================== `classmethod Table.from_data(data, shift_zeros=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table.from_data) Construct a Table object from data. | Parameters: | * **data** (*array-like*) – The raw data, from which a contingency table is constructed using the first two columns. * **shift\_zeros** (*boolean*) – If True and any cell count is zero, add 0.5 to all values in the table. | | Returns: | | | Return type: | A Table instance. | statsmodels statsmodels.miscmodels.count.PoissonGMLE.hessian_factor statsmodels.miscmodels.count.PoissonGMLE.hessian\_factor ======================================================== `PoissonGMLE.hessian_factor(params, scale=None, observed=True)` Weights for calculating Hessian | Parameters: | * **params** (*ndarray*) – parameter at which Hessian is evaluated * **scale** (*None* *or* *float*) – If scale is None, then the default scale will be calculated. Default scale is defined by `self.scaletype` and set in fit. If scale is not None, then it is used as a fixed scale. * **observed** (*bool*) – If True, then the observed Hessian is returned. If false then the expected information matrix is returned. | | Returns: | **hessian\_factor** – A 1d weight vector used in the calculation of the Hessian. The hessian is obtained by `(exog.T * hessian_factor).dot(exog)` | | Return type: | ndarray, 1d | statsmodels statsmodels.discrete.count_model.ZeroInflatedPoissonResults.remove_data statsmodels.discrete.count\_model.ZeroInflatedPoissonResults.remove\_data ========================================================================= `ZeroInflatedPoissonResults.remove_data()` remove data arrays, all nobs arrays from result and model This reduces the size of the instance, so it can be pickled with less memory. Currently tested for use with predict from an unpickled results and model instance. Warning Since data and some intermediate results have been removed calculating new statistics that require them will raise exceptions. The exception will occur the first time an attribute is accessed that has been set to None. Not fully tested for time series models, tsa, and might delete too much for prediction or not all that would be possible. The lists of arrays to delete are maintained as attributes of the result and model instance, except for cached values. These lists could be changed before calling remove\_data. The attributes to remove are named in: `model._data_attr : arrays attached to both the model instance` and the results instance with the same attribute name. `result.data_in_cache : arrays that may exist as values in` result.\_cache (TODO : should privatize name) `result._data_attr_model : arrays attached to the model` instance but not to the results instance
programming_docs
statsmodels statsmodels.discrete.discrete_model.MultinomialModel.score statsmodels.discrete.discrete\_model.MultinomialModel.score =========================================================== `MultinomialModel.score(params)` Score vector of model. The gradient of logL with respect to each parameter. statsmodels statsmodels.iolib.table.SimpleTable.append statsmodels.iolib.table.SimpleTable.append ========================================== `SimpleTable.append(object) → None -- append object to end` statsmodels statsmodels.tsa.vector_ar.vecm.VECMResults.tvalues_gamma statsmodels.tsa.vector\_ar.vecm.VECMResults.tvalues\_gamma ========================================================== `VECMResults.tvalues_gamma()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/vecm.html#VECMResults.tvalues_gamma) statsmodels statsmodels.stats.outliers_influence.OLSInfluence.params_not_obsi statsmodels.stats.outliers\_influence.OLSInfluence.params\_not\_obsi ==================================================================== `OLSInfluence.params_not_obsi()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/outliers_influence.html#OLSInfluence.params_not_obsi) (cached attribute) parameter estimates for all LOOO regressions uses results from leave-one-observation-out loop statsmodels statsmodels.miscmodels.count.PoissonGMLE.from_formula statsmodels.miscmodels.count.PoissonGMLE.from\_formula ====================================================== `classmethod PoissonGMLE.from_formula(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** (*extra arguments*) – These are passed to the model * **kwargs** (*extra keyword arguments*) – These are passed to the model with one exception. The `eval_env` keyword is passed to patsy. It can be either a [`patsy.EvalEnvironment`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.EvalEnvironment "(in patsy v0.5.0+dev)") 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** | | Return type: | 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 statsmodels.genmod.cov_struct.Exchangeable statsmodels.genmod.cov\_struct.Exchangeable =========================================== `class statsmodels.genmod.cov_struct.Exchangeable` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/cov_struct.html#Exchangeable) An exchangeable working dependence structure. #### Methods | | | | --- | --- | | [`covariance_matrix`](statsmodels.genmod.cov_struct.exchangeable.covariance_matrix#statsmodels.genmod.cov_struct.Exchangeable.covariance_matrix "statsmodels.genmod.cov_struct.Exchangeable.covariance_matrix")(expval, index) | Returns the working covariance or correlation matrix for a given cluster of data. | | [`covariance_matrix_solve`](statsmodels.genmod.cov_struct.exchangeable.covariance_matrix_solve#statsmodels.genmod.cov_struct.Exchangeable.covariance_matrix_solve "statsmodels.genmod.cov_struct.Exchangeable.covariance_matrix_solve")(expval, index, …) | Solves matrix equations of the form `covmat * soln = rhs` and returns the values of `soln`, where `covmat` is the covariance matrix represented by this class. | | [`initialize`](statsmodels.genmod.cov_struct.exchangeable.initialize#statsmodels.genmod.cov_struct.Exchangeable.initialize "statsmodels.genmod.cov_struct.Exchangeable.initialize")(model) | Called by GEE, used by implementations that need additional setup prior to running `fit`. | | [`summary`](statsmodels.genmod.cov_struct.exchangeable.summary#statsmodels.genmod.cov_struct.Exchangeable.summary "statsmodels.genmod.cov_struct.Exchangeable.summary")() | Returns a text summary of the current estimate of the dependence structure. | | [`update`](statsmodels.genmod.cov_struct.exchangeable.update#statsmodels.genmod.cov_struct.Exchangeable.update "statsmodels.genmod.cov_struct.Exchangeable.update")(params) | Updates the association parameter values based on the current regression coefficients. | statsmodels statsmodels.tsa.statespace.structural.UnobservedComponents.initialize_approximate_diffuse statsmodels.tsa.statespace.structural.UnobservedComponents.initialize\_approximate\_diffuse =========================================================================================== `UnobservedComponents.initialize_approximate_diffuse(variance=None)` statsmodels statsmodels.regression.linear_model.RegressionResults.cov_HC2 statsmodels.regression.linear\_model.RegressionResults.cov\_HC2 =============================================================== `RegressionResults.cov_HC2()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#RegressionResults.cov_HC2) See statsmodels.RegressionResults statsmodels statsmodels.graphics.correlation.plot_corr statsmodels.graphics.correlation.plot\_corr =========================================== `statsmodels.graphics.correlation.plot_corr(dcorr, xnames=None, ynames=None, title=None, normcolor=False, ax=None, cmap='RdYlBu_r')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/graphics/correlation.html#plot_corr) Plot correlation of many variables in a tight color grid. | Parameters: | * **dcorr** (*ndarray*) – Correlation matrix, square 2-D array. * **xnames** (*list of str**,* *optional*) – Labels for the horizontal axis. If not given (None), then the matplotlib defaults (integers) are used. If it is an empty list, [], then no ticks and labels are added. * **ynames** (*list of str**,* *optional*) – Labels for the vertical axis. Works the same way as `xnames`. If not given, the same names as for `xnames` are re-used. * **title** (*str**,* *optional*) – The figure title. If None, the default (‘Correlation Matrix’) is used. If `title=''`, then no title is added. * **normcolor** (*bool* *or* *tuple of scalars**,* *optional*) – If False (default), then the color coding range corresponds to the range of `dcorr`. If True, then the color range is normalized to (-1, 1). If this is a tuple of two numbers, then they define the range for the color bar. * **ax** (*Matplotlib AxesSubplot instance**,* *optional*) – If `ax` is None, then a figure is created. If an axis instance is given, then only the main plot but not the colorbar is created. * **cmap** (*str* *or* *Matplotlib Colormap instance**,* *optional*) – The colormap for the plot. Can be any valid Matplotlib Colormap instance or name. | | Returns: | **fig** – If `ax` is None, the created figure. Otherwise the figure to which `ax` is connected. | | Return type: | Matplotlib figure instance | #### Examples ``` >>> import numpy as np >>> import matplotlib.pyplot as plt >>> import statsmodels.graphics.api as smg ``` ``` >>> hie_data = sm.datasets.randhie.load_pandas() >>> corr_matrix = np.corrcoef(hie_data.data.T) >>> smg.plot_corr(corr_matrix, xnames=hie_data.names) >>> plt.show() ``` statsmodels statsmodels.stats.contingency_tables.SquareTable.from_data statsmodels.stats.contingency\_tables.SquareTable.from\_data ============================================================ `classmethod SquareTable.from_data(data, shift_zeros=True)` Construct a Table object from data. | Parameters: | * **data** (*array-like*) – The raw data, from which a contingency table is constructed using the first two columns. * **shift\_zeros** (*boolean*) – If True and any cell count is zero, add 0.5 to all values in the table. | | Returns: | | | Return type: | A Table instance. | statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.set_stability_method statsmodels.tsa.statespace.dynamic\_factor.DynamicFactor.set\_stability\_method =============================================================================== `DynamicFactor.set_stability_method(stability_method=None, **kwargs)` Set the numerical stability method The Kalman filter is a recursive algorithm that may in some cases suffer issues with numerical stability. The stability method controls what, if any, measures are taken to promote stability. | Parameters: | * **stability\_method** (*integer**,* *optional*) – Bitmask value to set the stability method to. See notes for details. * **\*\*kwargs** – Keyword arguments may be used to influence the stability method by setting individual boolean flags. See notes for details. | #### Notes This method is rarely used. See the corresponding function in the `KalmanFilter` class for details. statsmodels statsmodels.stats.correlation_tools.FactoredPSDMatrix statsmodels.stats.correlation\_tools.FactoredPSDMatrix ====================================================== `class statsmodels.stats.correlation_tools.FactoredPSDMatrix(diag, root)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/correlation_tools.html#FactoredPSDMatrix) Representation of a positive semidefinite matrix in factored form. The representation is constructed based on a vector `diag` and rectangular matrix `root`, such that the PSD matrix represented by the class instance is Diag + root \* root’, where Diag is the square diagonal matrix with `diag` on its main diagonal. | Parameters: | * **diag** (*1d array-like*) – See above * **root** (*2d array-like*) – See above | #### Notes The matrix is represented internally in the form Diag^{1/2}(I + factor \* scales \* factor’)Diag^{1/2}, where `Diag` and `scales` are diagonal matrices, and `factor` is an orthogonal matrix. #### Methods | | | | --- | --- | | [`decorrelate`](statsmodels.stats.correlation_tools.factoredpsdmatrix.decorrelate#statsmodels.stats.correlation_tools.FactoredPSDMatrix.decorrelate "statsmodels.stats.correlation_tools.FactoredPSDMatrix.decorrelate")(rhs) | Decorrelate the columns of `rhs`. | | [`logdet`](statsmodels.stats.correlation_tools.factoredpsdmatrix.logdet#statsmodels.stats.correlation_tools.FactoredPSDMatrix.logdet "statsmodels.stats.correlation_tools.FactoredPSDMatrix.logdet")() | Returns the logarithm of the determinant of a factor-structured matrix. | | [`solve`](statsmodels.stats.correlation_tools.factoredpsdmatrix.solve#statsmodels.stats.correlation_tools.FactoredPSDMatrix.solve "statsmodels.stats.correlation_tools.FactoredPSDMatrix.solve")(rhs) | Solve a linear system of equations with factor-structured coefficients. | | [`to_matrix`](statsmodels.stats.correlation_tools.factoredpsdmatrix.to_matrix#statsmodels.stats.correlation_tools.FactoredPSDMatrix.to_matrix "statsmodels.stats.correlation_tools.FactoredPSDMatrix.to_matrix")() | Returns the PSD matrix represented by this instance as a full (square) matrix. | statsmodels statsmodels.discrete.discrete_model.CountResults.tvalues statsmodels.discrete.discrete\_model.CountResults.tvalues ========================================================= `CountResults.tvalues()` Return the t-statistic for a given parameter estimate. statsmodels statsmodels.sandbox.tsa.fftarma.ArmaFft.spdroots statsmodels.sandbox.tsa.fftarma.ArmaFft.spdroots ================================================ `ArmaFft.spdroots(w)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/tsa/fftarma.html#ArmaFft.spdroots) spectral density for frequency using polynomial roots builds two arrays (number of roots, number of frequencies) statsmodels statsmodels.tsa.vector_ar.vecm.VECMResults.stderr_coint statsmodels.tsa.vector\_ar.vecm.VECMResults.stderr\_coint ========================================================= `VECMResults.stderr_coint()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/vecm.html#VECMResults.stderr_coint) Standard errors of beta and deterministic terms inside the cointegration relation. #### Notes See p. 297 in [[1]](#id3). Using the rule \[vec(B R) = (B' \otimes I) vec(R)\] for two matrices B and R which are compatible for multiplication. This is rule (3) on p. 662 in [[1]](#id3). #### References | | | | --- | --- | | [1] | *([1](#id1), [2](#id2))* Lütkepohl, H. 2005. *New Introduction to Multiple Time Series Analysis*. Springer. | statsmodels statsmodels.iolib.summary.Summary.add_extra_txt statsmodels.iolib.summary.Summary.add\_extra\_txt ================================================= `Summary.add_extra_txt(etext)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/iolib/summary.html#Summary.add_extra_txt) add additional text that will be added at the end in text format | Parameters: | **etext** (*list**[**str**]*) – string with lines that are added to the text output. | statsmodels statsmodels.discrete.discrete_model.BinaryResults.f_test statsmodels.discrete.discrete\_model.BinaryResults.f\_test ========================================================== `BinaryResults.f_test(r_matrix, cov_p=None, scale=1.0, invcov=None)` Compute the F-test for a joint linear hypothesis. This is a special case of `wald_test` that always uses the F distribution. | Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) – + array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length k row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – Default is 1.0 for no scaling. * **invcov** (*array-like**,* *optional*) – A q x q array to specify an inverse covariance matrix based on a restrictions matrix. | | Returns: | **res** – The results for the test are attributes of this results instance. | | Return type: | ContrastResults instance | #### Examples ``` >>> import numpy as np >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> A = np.identity(len(results.params)) >>> A = A[1:,:] ``` This tests that each coefficient is jointly statistically significantly different from zero. ``` >>> print(results.f_test(A)) <F test: F=array([[ 330.28533923]]), p=4.984030528700946e-10, df_denom=9, df_num=6> ``` Compare this to ``` >>> results.fvalue 330.2853392346658 >>> results.f_pvalue 4.98403096572e-10 ``` ``` >>> B = np.array(([0,0,1,-1,0,0,0],[0,0,0,0,0,1,-1])) ``` This tests that the coefficient on the 2nd and 3rd regressors are equal and jointly that the coefficient on the 5th and 6th regressors are equal. ``` >>> print(results.f_test(B)) <F test: F=array([[ 9.74046187]]), p=0.005605288531708235, df_denom=9, df_num=2> ``` Alternatively, you can specify the hypothesis tests using a string ``` >>> from statsmodels.datasets import longley >>> from statsmodels.formula.api import ols >>> dta = longley.load_pandas().data >>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' >>> results = ols(formula, dta).fit() >>> hypotheses = '(GNPDEFL = GNP), (UNEMP = 2), (YEAR/1829 = 1)' >>> f_test = results.f_test(hypotheses) >>> print(f_test) <F test: F=array([[ 144.17976065]]), p=6.322026217355609e-08, df_denom=9, df_num=3> ``` See also [`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`wald_test`](statsmodels.discrete.discrete_model.binaryresults.wald_test#statsmodels.discrete.discrete_model.BinaryResults.wald_test "statsmodels.discrete.discrete_model.BinaryResults.wald_test"), [`t_test`](statsmodels.discrete.discrete_model.binaryresults.t_test#statsmodels.discrete.discrete_model.BinaryResults.t_test "statsmodels.discrete.discrete_model.BinaryResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") #### Notes The matrix `r_matrix` is assumed to be non-singular. More precisely, r\_matrix (pX pX.T) r\_matrix.T is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full. statsmodels statsmodels.sandbox.regression.gmm.IV2SLS.fit statsmodels.sandbox.regression.gmm.IV2SLS.fit ============================================= `IV2SLS.fit()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#IV2SLS.fit) estimate model using 2SLS IV regression | Returns: | **results** – regression result | | Return type: | instance of RegressionResults | #### Notes This returns a generic RegressioResults instance as defined for the linear models. Parameter estimates and covariance are correct, but other results haven’t been tested yet, to seee whether they apply without changes. statsmodels statsmodels.tsa.statespace.mlemodel.MLEModel.set_inversion_method statsmodels.tsa.statespace.mlemodel.MLEModel.set\_inversion\_method =================================================================== `MLEModel.set_inversion_method(inversion_method=None, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEModel.set_inversion_method) Set the inversion method The Kalman filter may contain one matrix inversion: that of the forecast error covariance matrix. The inversion method controls how and if that inverse is performed. | Parameters: | * **inversion\_method** (*integer**,* *optional*) – Bitmask value to set the inversion method to. See notes for details. * **\*\*kwargs** – Keyword arguments may be used to influence the inversion method by setting individual boolean flags. See notes for details. | #### Notes This method is rarely used. See the corresponding function in the `KalmanFilter` class for details. statsmodels statsmodels.tsa.vector_ar.vecm.VECMResults.stderr_det_coef_coint statsmodels.tsa.vector\_ar.vecm.VECMResults.stderr\_det\_coef\_coint ==================================================================== `VECMResults.stderr_det_coef_coint()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/vecm.html#VECMResults.stderr_det_coef_coint) statsmodels statsmodels.sandbox.distributions.extras.SkewNorm2_gen.cdf statsmodels.sandbox.distributions.extras.SkewNorm2\_gen.cdf =========================================================== `SkewNorm2_gen.cdf(x, *args, **kwds)` Cumulative distribution function of the given RV. | Parameters: | * **x** (*array\_like*) – quantiles * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **cdf** – Cumulative distribution function evaluated at `x` | | Return type: | ndarray |
programming_docs
statsmodels statsmodels.emplike.descriptive.DescStatMV.test_corr statsmodels.emplike.descriptive.DescStatMV.test\_corr ===================================================== `DescStatMV.test_corr(corr0, return_weights=0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/emplike/descriptive.html#DescStatMV.test_corr) Returns -2 x log-likelihood ratio and p-value for the correlation coefficient between 2 variables | Parameters: | * **corr0** (*float*) – Hypothesized value to be tested * **return\_weights** (*bool*) – If true, returns the weights that maximize the log-likelihood at the hypothesized value | statsmodels statsmodels.regression.recursive_ls.RecursiveLSResults.llf_obs statsmodels.regression.recursive\_ls.RecursiveLSResults.llf\_obs ================================================================ `RecursiveLSResults.llf_obs()` (float) The value of the log-likelihood function evaluated at `params`. statsmodels statsmodels.genmod.generalized_linear_model.GLMResults.resid_anscombe_unscaled statsmodels.genmod.generalized\_linear\_model.GLMResults.resid\_anscombe\_unscaled ================================================================================== `GLMResults.resid_anscombe_unscaled()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_linear_model.html#GLMResults.resid_anscombe_unscaled) statsmodels statsmodels.discrete.discrete_model.BinaryResults.resid_response statsmodels.discrete.discrete\_model.BinaryResults.resid\_response ================================================================== `BinaryResults.resid_response()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#BinaryResults.resid_response) The response residuals #### Notes Response residuals are defined to be \[y - p\] where \(p=cdf(X\beta)\). statsmodels statsmodels.robust.norms.RobustNorm statsmodels.robust.norms.RobustNorm =================================== `class statsmodels.robust.norms.RobustNorm` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/norms.html#RobustNorm) The parent class for the norms used for robust regression. Lays out the methods expected of the robust norms to be used by statsmodels.RLM. | Parameters: | **None** – Some subclasses have optional tuning constants. | #### References PJ Huber. ‘Robust Statistics’ John Wiley and Sons, Inc., New York, 1981. DC Montgomery, EA Peck. ‘Introduction to Linear Regression Analysis’, John Wiley and Sons, Inc., New York, 2001. R Venables, B Ripley. ‘Modern Applied Statistics in S’ Springer, New York, 2002. See also [`statsmodels.rlm`](../rlm_techn1#module-statsmodels.rlm "statsmodels.rlm: Outlier robust linear models"), `and` #### Notes Currently only M-estimators are available. #### Methods | | | | --- | --- | | [`psi`](statsmodels.robust.norms.robustnorm.psi#statsmodels.robust.norms.RobustNorm.psi "statsmodels.robust.norms.RobustNorm.psi")(z) | Derivative of rho. | | [`psi_deriv`](statsmodels.robust.norms.robustnorm.psi_deriv#statsmodels.robust.norms.RobustNorm.psi_deriv "statsmodels.robust.norms.RobustNorm.psi_deriv")(z) | Deriative of psi. | | [`rho`](statsmodels.robust.norms.robustnorm.rho#statsmodels.robust.norms.RobustNorm.rho "statsmodels.robust.norms.RobustNorm.rho")(z) | The robust criterion estimator function. | | [`weights`](statsmodels.robust.norms.robustnorm.weights#statsmodels.robust.norms.RobustNorm.weights "statsmodels.robust.norms.RobustNorm.weights")(z) | Returns the value of psi(z) / z | statsmodels statsmodels.tsa.vector_ar.var_model.VARResults.llf statsmodels.tsa.vector\_ar.var\_model.VARResults.llf ==================================================== `VARResults.llf()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/var_model.html#VARResults.llf) Compute VAR(p) loglikelihood statsmodels statsmodels.tsa.statespace.structural.UnobservedComponents.set_filter_method statsmodels.tsa.statespace.structural.UnobservedComponents.set\_filter\_method ============================================================================== `UnobservedComponents.set_filter_method(filter_method=None, **kwargs)` Set the filtering method The filtering method controls aspects of which Kalman filtering approach will be used. | Parameters: | * **filter\_method** (*integer**,* *optional*) – Bitmask value to set the filter method to. See notes for details. * **\*\*kwargs** – Keyword arguments may be used to influence the filter method by setting individual boolean flags. See notes for details. | #### Notes This method is rarely used. See the corresponding function in the `KalmanFilter` class for details. statsmodels statsmodels.tsa.statespace.sarimax.SARIMAXResults.normalized_cov_params statsmodels.tsa.statespace.sarimax.SARIMAXResults.normalized\_cov\_params ========================================================================= `SARIMAXResults.normalized_cov_params()` statsmodels statsmodels.regression.linear_model.RegressionResults.wresid statsmodels.regression.linear\_model.RegressionResults.wresid ============================================================= `RegressionResults.wresid()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#RegressionResults.wresid) statsmodels statsmodels.tsa.statespace.structural.UnobservedComponentsResults.impulse_responses statsmodels.tsa.statespace.structural.UnobservedComponentsResults.impulse\_responses ==================================================================================== `UnobservedComponentsResults.impulse_responses(steps=1, impulse=0, orthogonalized=False, cumulative=False, **kwargs)` Impulse response function | Parameters: | * **steps** (*int**,* *optional*) – The number of steps for which impulse responses are calculated. Default is 1. Note that the initial impulse is not counted as a step, so if `steps=1`, the output will have 2 entries. * **impulse** (*int* *or* *array\_like*) – If an integer, the state innovation to pulse; must be between 0 and `k_posdef-1`. Alternatively, a custom impulse vector may be provided; must be shaped `k_posdef x 1`. * **orthogonalized** (*boolean**,* *optional*) – Whether or not to perform impulse using orthogonalized innovations. Note that this will also affect custum `impulse` vectors. Default is False. * **cumulative** (*boolean**,* *optional*) – Whether or not to return cumulative impulse responses. Default is False. * **\*\*kwargs** – If the model is time-varying and `steps` is greater than the number of observations, any of the state space representation matrices that are time-varying must have updated values provided for the out-of-sample steps. For example, if `design` is a time-varying component, `nobs` is 10, and `steps` is 15, a (`k_endog` x `k_states` x 5) matrix must be provided with the new design matrix values. | | Returns: | **impulse\_responses** – Responses for each endogenous variable due to the impulse given by the `impulse` argument. A (steps + 1 x k\_endog) array. | | Return type: | array | #### Notes Intercepts in the measurement and state equation are ignored when calculating impulse responses. statsmodels statsmodels.genmod.families.family.Gaussian.weights statsmodels.genmod.families.family.Gaussian.weights =================================================== `Gaussian.weights(mu)` Weights for IRLS steps | Parameters: | **mu** (*array-like*) – The transformed mean response variable in the exponential family | | Returns: | **w** – The weights for the IRLS steps | | Return type: | array | #### Notes \[w = 1 / (g'(\mu)^2 \* Var(\mu))\] statsmodels statsmodels.genmod.families.links.identity.inverse_deriv statsmodels.genmod.families.links.identity.inverse\_deriv ========================================================= `identity.inverse_deriv(z)` Derivative of the inverse of the power transform | Parameters: | **z** (*array-like*) – `z` is usually the linear predictor for a GLM or GEE model. | | Returns: | * **g^(-1)’(z)** (*array*) – The value of the derivative of the inverse of the power transform * *function* | statsmodels statsmodels.genmod.families.family.Gamma.fitted statsmodels.genmod.families.family.Gamma.fitted =============================================== `Gamma.fitted(lin_pred)` Fitted values based on linear predictors lin\_pred. | Parameters: | **lin\_pred** (*array*) – Values of the linear predictor of the model. \(X \cdot \beta\) in a classical linear model. | | Returns: | **mu** – The mean response variables given by the inverse of the link function. | | Return type: | array | statsmodels statsmodels.stats.contingency_tables.Table2x2.cumulative_oddsratios statsmodels.stats.contingency\_tables.Table2x2.cumulative\_oddsratios ===================================================================== `Table2x2.cumulative_oddsratios()` statsmodels statsmodels.discrete.discrete_model.BinaryModel.hessian statsmodels.discrete.discrete\_model.BinaryModel.hessian ======================================================== `BinaryModel.hessian(params)` The Hessian matrix of the model statsmodels statsmodels.sandbox.distributions.transformed.SquareFunc.derivplus statsmodels.sandbox.distributions.transformed.SquareFunc.derivplus ================================================================== `SquareFunc.derivplus(x)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/distributions/transformed.html#SquareFunc.derivplus) statsmodels statsmodels.tsa.statespace.structural.UnobservedComponentsResults.initialize statsmodels.tsa.statespace.structural.UnobservedComponentsResults.initialize ============================================================================ `UnobservedComponentsResults.initialize(model, params, **kwd)` statsmodels statsmodels.multivariate.factor_rotation.target_rotation statsmodels.multivariate.factor\_rotation.target\_rotation ========================================================== `statsmodels.multivariate.factor_rotation.target_rotation(A, H, full_rank=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/multivariate/factor_rotation/_analytic_rotation.html#target_rotation) Analytically performs orthogonal rotations towards a target matrix, i.e., we minimize: \[\phi(L) =\frac{1}{2}\|AT-H\|^2.\] where \(T\) is an orthogonal matrix. This problem is also known as an orthogonal Procrustes problem. Under the assumption that \(A^\*H\) has full rank, the analytical solution \(T\) is given by: \[T = (A^\*HH^\*A)^{-\frac{1}{2}}A^\*H,\] see Green (1952). In other cases the solution is given by \(T = UV\), where \(U\) and \(V\) result from the singular value decomposition of \(A^\*H\): \[A^\*H = U\Sigma V,\] see Schonemann (1966). | Parameters: | * **A** (*numpy matrix* *(**default None**)*) – non rotated factors * **H** (*numpy matrix*) – target matrix * **full\_rank** (*boolean* *(**default FAlse**)*) – if set to true full rank is assumed | | Returns: | | | Return type: | The matrix \(T\). | #### References [1] Green (1952, Psychometrika) - The orthogonal approximation of an oblique structure in factor analysis [2] Schonemann (1966) - A generalized solution of the orthogonal procrustes problem [3] Gower, Dijksterhuis (2004) - Procustes problems statsmodels statsmodels.genmod.families.family.Binomial.predict statsmodels.genmod.families.family.Binomial.predict =================================================== `Binomial.predict(mu)` Linear predictors based on given mu values. | Parameters: | **mu** (*array*) – The mean response variables | | Returns: | **lin\_pred** – Linear predictors based on the mean response variables. The value of the link function at the given mu. | | Return type: | array | statsmodels statsmodels.tsa.arima_process.ArmaProcess.periodogram statsmodels.tsa.arima\_process.ArmaProcess.periodogram ====================================================== `ArmaProcess.periodogram(nobs=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_process.html#ArmaProcess.periodogram) Periodogram for ARMA process given by lag-polynomials ar and ma | Parameters: | * **ar** (*array\_like*) – autoregressive lag-polynomial with leading 1 and lhs sign * **ma** (*array\_like*) – moving average lag-polynomial with leading 1 * **worN** (*{None**,* *int}**,* *optional*) – option for scipy.signal.freqz (read “w or N”) If None, then compute at 512 frequencies around the unit circle. If a single integer, the compute at that many frequencies. Otherwise, compute the response at frequencies given in worN * **whole** (*{0**,**1}**,* *optional*) – options for scipy.signal.freqz Normally, frequencies are computed from 0 to pi (upper-half of unit-circle. If whole is non-zero compute frequencies from 0 to 2\*pi. | | Returns: | * **w** (*array*) – frequencies * **sd** (*array*) – periodogram, spectral density | #### Notes Normalization ? This uses signal.freqz, which does not use fft. There is a fft version somewhere. statsmodels statsmodels.sandbox.distributions.transformed.ExpTransf_gen.cdf statsmodels.sandbox.distributions.transformed.ExpTransf\_gen.cdf ================================================================ `ExpTransf_gen.cdf(x, *args, **kwds)` Cumulative distribution function of the given RV. | Parameters: | * **x** (*array\_like*) – quantiles * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **cdf** – Cumulative distribution function evaluated at `x` | | Return type: | ndarray | statsmodels statsmodels.tsa.vector_ar.var_model.VARResults.reorder statsmodels.tsa.vector\_ar.var\_model.VARResults.reorder ======================================================== `VARResults.reorder(order)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/var_model.html#VARResults.reorder) Reorder variables for structural specification statsmodels statsmodels.multivariate.multivariate_ols._MultivariateOLS.fit statsmodels.multivariate.multivariate\_ols.\_MultivariateOLS.fit ================================================================ `_MultivariateOLS.fit(method='svd')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/multivariate/multivariate_ols.html#_MultivariateOLS.fit) Fit a model to data. statsmodels statsmodels.sandbox.distributions.transformed.TransfTwo_gen.fit statsmodels.sandbox.distributions.transformed.TransfTwo\_gen.fit ================================================================ `TransfTwo_gen.fit(data, *args, **kwds)` Return MLEs for shape (if applicable), location, and scale parameters from data. MLE stands for Maximum Likelihood Estimate. Starting estimates for the fit are given by input arguments; for any arguments not provided with starting estimates, `self._fitstart(data)` is called to generate such. One can hold some parameters fixed to specific values by passing in keyword arguments `f0`, `f1`, …, `fn` (for shape parameters) and `floc` and `fscale` (for location and scale parameters, respectively). | Parameters: | * **data** (*array\_like*) – Data to use in calculating the MLEs. * **args** (*floats**,* *optional*) – Starting value(s) for any shape-characterizing arguments (those not provided will be determined by a call to `_fitstart(data)`). No default value. * **kwds** (*floats**,* *optional*) – Starting values for the location and scale parameters; no default. Special keyword arguments are recognized as holding certain parameters fixed: + f0…fn : hold respective shape parameters fixed. Alternatively, shape parameters to fix can be specified by name. For example, if `self.shapes == "a, b"`, `fa``and ``fix_a` are equivalent to `f0`, and `fb` and `fix_b` are equivalent to `f1`. + floc : hold location parameter fixed to specified value. + fscale : hold scale parameter fixed to specified value. + optimizer : The optimizer to use. The optimizer must take `func`, and starting position as the first two arguments, plus `args` (for extra arguments to pass to the function to be optimized) and `disp=0` to suppress output as keyword arguments. | | Returns: | **mle\_tuple** – MLEs for any shape parameters (if applicable), followed by those for location and scale. For most random variables, shape statistics will be returned, but there are exceptions (e.g. `norm`). | | Return type: | tuple of floats | #### Notes This fit is computed by maximizing a log-likelihood function, with penalty applied for samples outside of range of the distribution. The returned answer is not guaranteed to be the globally optimal MLE, it may only be locally optimal, or the optimization may fail altogether. #### Examples Generate some data to fit: draw random variates from the `beta` distribution ``` >>> from scipy.stats import beta >>> a, b = 1., 2. >>> x = beta.rvs(a, b, size=1000) ``` Now we can fit all four parameters (`a`, `b`, `loc` and `scale`): ``` >>> a1, b1, loc1, scale1 = beta.fit(x) ``` We can also use some prior knowledge about the dataset: let’s keep `loc` and `scale` fixed: ``` >>> a1, b1, loc1, scale1 = beta.fit(x, floc=0, fscale=1) >>> loc1, scale1 (0, 1) ``` We can also keep shape parameters fixed by using `f`-keywords. To keep the zero-th shape parameter `a` equal 1, use `f0=1` or, equivalently, `fa=1`: ``` >>> a1, b1, loc1, scale1 = beta.fit(x, fa=1, floc=0, fscale=1) >>> a1 1 ``` Not all distributions return estimates for the shape parameters. `norm` for example just returns estimates for location and scale: ``` >>> from scipy.stats import norm >>> x = norm.rvs(a, b, size=1000, random_state=123) >>> loc1, scale1 = norm.fit(x) >>> loc1, scale1 (0.92087172783841631, 2.0015750750324668) ``` statsmodels statsmodels.regression.linear_model.RegressionResults.wald_test statsmodels.regression.linear\_model.RegressionResults.wald\_test ================================================================= `RegressionResults.wald_test(r_matrix, cov_p=None, scale=1.0, invcov=None, use_f=None)` Compute a Wald-test for a joint linear hypothesis. | Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) – + array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length p row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – Default is 1.0 for no scaling. * **invcov** (*array-like**,* *optional*) – A q x q array to specify an inverse covariance matrix based on a restrictions matrix. * **use\_f** (*bool*) – If True, then the F-distribution is used. If False, then the asymptotic distribution, chisquare is used. If use\_f is None, then the F distribution is used if the model specifies that use\_t is True. The test statistic is proportionally adjusted for the distribution by the number of constraints in the hypothesis. | | Returns: | **res** – The results for the test are attributes of this results instance. | | Return type: | ContrastResults instance | See also [`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`f_test`](statsmodels.regression.linear_model.regressionresults.f_test#statsmodels.regression.linear_model.RegressionResults.f_test "statsmodels.regression.linear_model.RegressionResults.f_test"), [`t_test`](statsmodels.regression.linear_model.regressionresults.t_test#statsmodels.regression.linear_model.RegressionResults.t_test "statsmodels.regression.linear_model.RegressionResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") #### Notes The matrix `r_matrix` is assumed to be non-singular. More precisely, r\_matrix (pX pX.T) r\_matrix.T is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full.
programming_docs
statsmodels statsmodels.regression.linear_model.OLSResults.cov_HC2 statsmodels.regression.linear\_model.OLSResults.cov\_HC2 ======================================================== `OLSResults.cov_HC2()` See statsmodels.RegressionResults statsmodels statsmodels.sandbox.regression.gmm.NonlinearIVGMM.score_cu statsmodels.sandbox.regression.gmm.NonlinearIVGMM.score\_cu =========================================================== `NonlinearIVGMM.score_cu(params, epsilon=None, centered=True)` statsmodels statsmodels.tsa.statespace.structural.UnobservedComponentsResults.pvalues statsmodels.tsa.statespace.structural.UnobservedComponentsResults.pvalues ========================================================================= `UnobservedComponentsResults.pvalues()` (array) The p-values associated with the z-statistics of the coefficients. Note that the coefficients are assumed to have a Normal distribution. statsmodels statsmodels.stats.weightstats.DescrStatsW.get_compare statsmodels.stats.weightstats.DescrStatsW.get\_compare ====================================================== `DescrStatsW.get_compare(other, weights=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/weightstats.html#DescrStatsW.get_compare) return an instance of CompareMeans with self and other | Parameters: | * **other** (*array\_like* *or* *instance of DescrStatsW*) – If array\_like then this creates an instance of DescrStatsW with the given weights. * **weights** (*None* *or* *array*) – weights are only used if other is not an instance of DescrStatsW | | Returns: | **cm** – the instance has self attached as d1 and other as d2. | | Return type: | instance of CompareMeans | See also [`CompareMeans`](statsmodels.stats.weightstats.comparemeans#statsmodels.stats.weightstats.CompareMeans "statsmodels.stats.weightstats.CompareMeans") statsmodels statsmodels.sandbox.regression.gmm.NonlinearIVGMM.fititer statsmodels.sandbox.regression.gmm.NonlinearIVGMM.fititer ========================================================= `NonlinearIVGMM.fititer(start, maxiter=2, start_invweights=None, weights_method='cov', wargs=(), optim_method='bfgs', optim_args=None)` iterative estimation with updating of optimal weighting matrix stopping criteria are maxiter or change in parameter estimate less than self.epsilon\_iter, with default 1e-6. | Parameters: | * **start** (*array*) – starting value for parameters * **maxiter** (*int*) – maximum number of iterations * **start\_weights** (*array* *(**nmoms**,* *nmoms**)*) – initial weighting matrix; if None, then the identity matrix is used * **weights\_method** (*{'cov'**,* *..}*) – method to use to estimate the optimal weighting matrix, see calc\_weightmatrix for details | | Returns: | * **params** (*array*) – estimated parameters * **weights** (*array*) – optimal weighting matrix calculated with final parameter estimates | #### Notes statsmodels statsmodels.stats.contingency_tables.cochrans_q statsmodels.stats.contingency\_tables.cochrans\_q ================================================= `statsmodels.stats.contingency_tables.cochrans_q(x, return_object=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#cochrans_q) Cochran’s Q test for identical binomial proportions. | Parameters: | * **x** (*array\_like**,* *2d* *(**N**,* *k**)*) – data with N cases and k variables * **return\_object** (*boolean*) – Return values as bunch instead of as individual values. | | Returns: | * *Returns a bunch containing the following attributes, or the* * individual values according to the value of `return_object`. * **statistic** (*float*) – test statistic * **pvalue** (*float*) – pvalue from the chisquare distribution | #### Notes Cochran’s Q is a k-sample extension of the McNemar test. If there are only two groups, then Cochran’s Q test and the McNemar test are equivalent. The procedure tests that the probability of success is the same for every group. The alternative hypothesis is that at least two groups have a different probability of success. In Wikipedia terminology, rows are blocks and columns are treatments. The number of rows N, should be large for the chisquare distribution to be a good approximation. The Null hypothesis of the test is that all treatments have the same effect. #### References <http://en.wikipedia.org/wiki/Cochran_test> SAS Manual for NPAR TESTS statsmodels statsmodels.duration.hazard_regression.PHRegResults.weighted_covariate_averages statsmodels.duration.hazard\_regression.PHRegResults.weighted\_covariate\_averages ================================================================================== `PHRegResults.weighted_covariate_averages()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/duration/hazard_regression.html#PHRegResults.weighted_covariate_averages) The average covariate values within the at-risk set at each event time point, weighted by hazard. statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.cov_HC3 statsmodels.sandbox.regression.gmm.IVRegressionResults.cov\_HC3 =============================================================== `IVRegressionResults.cov_HC3()` See statsmodels.RegressionResults statsmodels statsmodels.regression.quantile_regression.QuantRegResults.fvalue statsmodels.regression.quantile\_regression.QuantRegResults.fvalue ================================================================== `QuantRegResults.fvalue()` statsmodels statsmodels.sandbox.regression.gmm.LinearIVGMM.calc_weightmatrix statsmodels.sandbox.regression.gmm.LinearIVGMM.calc\_weightmatrix ================================================================= `LinearIVGMM.calc_weightmatrix(moms, weights_method='cov', wargs=(), params=None)` calculate omega or the weighting matrix | Parameters: | * **moms** (*array*) – moment conditions (nobs x nmoms) for all observations evaluated at a parameter value * **weights\_method** (*string 'cov'*) – If method=’cov’ is cov then the matrix is calculated as simple covariance of the moment conditions. see fit method for available aoptions for the weight and covariance matrix * **wargs** (*tuple* *or* [dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")) – parameters that are required by some kernel methods to estimate the long-run covariance. Not used yet. | | Returns: | **w** – estimate for the weighting matrix or covariance of the moment condition | | Return type: | array (nmoms, nmoms) | #### Notes currently a constant cutoff window is used TODO: implement long-run cov estimators, kernel-based Newey-West Andrews Andrews-Moy???? #### References Greene Hansen, Bruce statsmodels statsmodels.discrete.count_model.ZeroInflatedPoisson.information statsmodels.discrete.count\_model.ZeroInflatedPoisson.information ================================================================= `ZeroInflatedPoisson.information(params)` Fisher information matrix of model Returns -Hessian of loglike evaluated at params. statsmodels statsmodels.nonparametric.kernel_regression.KernelReg.r_squared statsmodels.nonparametric.kernel\_regression.KernelReg.r\_squared ================================================================= `KernelReg.r_squared()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/nonparametric/kernel_regression.html#KernelReg.r_squared) Returns the R-Squared for the nonparametric regression. #### Notes For more details see p.45 in [2] The R-Squared is calculated by: \[R^{2}=\frac{\left[\sum\_{i=1}^{n} (Y\_{i}-\bar{y})(\hat{Y\_{i}}-\bar{y}\right]^{2}}{\sum\_{i=1}^{n} (Y\_{i}-\bar{y})^{2}\sum\_{i=1}^{n}(\hat{Y\_{i}}-\bar{y})^{2}},\] where \(\hat{Y\_{i}}\) is the mean calculated in `fit` at the exog points. statsmodels statsmodels.tsa.holtwinters.ExponentialSmoothing.predict statsmodels.tsa.holtwinters.ExponentialSmoothing.predict ======================================================== `ExponentialSmoothing.predict(params, start=None, end=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/holtwinters.html#ExponentialSmoothing.predict) Returns in-sample and out-of-sample prediction. | Parameters: | * **params** (*array*) – The fitted model parameters. * **start** (*int**,* *str**, or* *datetime*) – Zero-indexed observation number at which to start forecasting, ie., the first forecast is start. Can also be a date string to parse or a datetime type. * **end** (*int**,* *str**, or* *datetime*) – Zero-indexed observation number at which to end forecasting, ie., the first forecast is start. Can also be a date string to parse or a datetime type. | | Returns: | **predicted values** | | Return type: | array | statsmodels statsmodels.discrete.discrete_model.GeneralizedPoisson.cdf statsmodels.discrete.discrete\_model.GeneralizedPoisson.cdf =========================================================== `GeneralizedPoisson.cdf(X)` The cumulative distribution function of the model. statsmodels statsmodels.discrete.discrete_model.MultinomialModel.pdf statsmodels.discrete.discrete\_model.MultinomialModel.pdf ========================================================= `MultinomialModel.pdf(X)` The probability density (mass) function of the model. statsmodels statsmodels.tsa.statespace.sarimax.SARIMAXResults.llf statsmodels.tsa.statespace.sarimax.SARIMAXResults.llf ===================================================== `SARIMAXResults.llf()` (float) The value of the log-likelihood function evaluated at `params`. statsmodels statsmodels.sandbox.regression.gmm.IVGMM.set_param_names statsmodels.sandbox.regression.gmm.IVGMM.set\_param\_names ========================================================== `IVGMM.set_param_names(param_names, k_params=None)` set the parameter names in the model | Parameters: | * **param\_names** (*list of strings*) – param\_names should have the same length as the number of params * **k\_params** (*None* *or* *int*) – If k\_params is None, then the k\_params attribute is used, unless it is None. If k\_params is not None, then it will also set the k\_params attribute. | statsmodels statsmodels.discrete.discrete_model.NegativeBinomialResults.cov_params statsmodels.discrete.discrete\_model.NegativeBinomialResults.cov\_params ======================================================================== `NegativeBinomialResults.cov_params(r_matrix=None, column=None, scale=None, cov_p=None, other=None)` Returns the variance/covariance matrix. The variance/covariance matrix can be of a linear contrast of the estimates of params or all params multiplied by scale which will usually be an estimate of sigma^2. Scale is assumed to be a scalar. | Parameters: | * **r\_matrix** (*array-like*) – Can be 1d, or 2d. Can be used alone or with other. * **column** (*array-like**,* *optional*) – Must be used on its own. Can be 0d or 1d see below. * **scale** (*float**,* *optional*) – Can be specified or not. Default is None, which means that the scale argument is taken from the model. * **other** (*array-like**,* *optional*) – Can be used when r\_matrix is specified. | | Returns: | **cov** – covariance matrix of the parameter estimates or of linear combination of parameter estimates. See Notes. | | Return type: | ndarray | #### Notes (The below are assumed to be in matrix notation.) If no argument is specified returns the covariance matrix of a model `(scale)*(X.T X)^(-1)` If contrast is specified it pre and post-multiplies as follows `(scale) * r_matrix (X.T X)^(-1) r_matrix.T` If contrast and other are specified returns `(scale) * r_matrix (X.T X)^(-1) other.T` If column is specified returns `(scale) * (X.T X)^(-1)[column,column]` if column is 0d OR `(scale) * (X.T X)^(-1)[column][:,column]` if column is 1d statsmodels statsmodels.miscmodels.count.PoissonGMLE.fit statsmodels.miscmodels.count.PoissonGMLE.fit ============================================ `PoissonGMLE.fit(start_params=None, method='nm', maxiter=500, full_output=1, disp=1, callback=None, retall=0, **kwargs)` Fit the model using maximum likelihood. The rest of the docstring is from statsmodels.LikelihoodModel.fit statsmodels statsmodels.genmod.generalized_estimating_equations.GEEMargins.pvalues statsmodels.genmod.generalized\_estimating\_equations.GEEMargins.pvalues ======================================================================== `GEEMargins.pvalues()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_estimating_equations.html#GEEMargins.pvalues) statsmodels statsmodels.regression.linear_model.GLS.score statsmodels.regression.linear\_model.GLS.score ============================================== `GLS.score(params)` Score vector of model. The gradient of logL with respect to each parameter. statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.rsquared_adj statsmodels.sandbox.regression.gmm.IVRegressionResults.rsquared\_adj ==================================================================== `IVRegressionResults.rsquared_adj()` statsmodels statsmodels.genmod.generalized_linear_model.PredictionResults statsmodels.genmod.generalized\_linear\_model.PredictionResults =============================================================== `class statsmodels.genmod.generalized_linear_model.PredictionResults(predicted_mean, var_pred_mean, var_resid=None, df=None, dist=None, row_labels=None, linpred=None, link=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/_prediction.html#PredictionResults) #### Methods | | | | --- | --- | | [`conf_int`](statsmodels.genmod.generalized_linear_model.predictionresults.conf_int#statsmodels.genmod.generalized_linear_model.PredictionResults.conf_int "statsmodels.genmod.generalized_linear_model.PredictionResults.conf_int")([method, alpha]) | Returns the confidence interval of the value, `effect` of the constraint. | | [`summary_frame`](statsmodels.genmod.generalized_linear_model.predictionresults.summary_frame#statsmodels.genmod.generalized_linear_model.PredictionResults.summary_frame "statsmodels.genmod.generalized_linear_model.PredictionResults.summary_frame")([what, alpha]) | | | [`t_test`](statsmodels.genmod.generalized_linear_model.predictionresults.t_test#statsmodels.genmod.generalized_linear_model.PredictionResults.t_test "statsmodels.genmod.generalized_linear_model.PredictionResults.t_test")([value, alternative]) | z- or t-test for hypothesis that mean is equal to value | #### Attributes | | | | --- | --- | | `se_mean` | | | `se_obs` | | | `tvalues` | | statsmodels statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression.score_obs statsmodels.tsa.regime\_switching.markov\_autoregression.MarkovAutoregression.score\_obs ======================================================================================== `MarkovAutoregression.score_obs(params, transformed=True)` Compute the score per observation, evaluated at params | Parameters: | * **params** (*array\_like*) – Array of parameters at which to evaluate the score function. * **transformed** (*boolean**,* *optional*) – Whether or not `params` is already transformed. Default is True. | statsmodels statsmodels.genmod.generalized_linear_model.GLMResults.resid_response statsmodels.genmod.generalized\_linear\_model.GLMResults.resid\_response ======================================================================== `GLMResults.resid_response()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_linear_model.html#GLMResults.resid_response) statsmodels statsmodels.sandbox.stats.multicomp.StepDown.get_distance_matrix statsmodels.sandbox.stats.multicomp.StepDown.get\_distance\_matrix ================================================================== `StepDown.get_distance_matrix()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/multicomp.html#StepDown.get_distance_matrix) studentized range statistic statsmodels statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialP.fit statsmodels.discrete.count\_model.ZeroInflatedNegativeBinomialP.fit =================================================================== `ZeroInflatedNegativeBinomialP.fit(start_params=None, method='bfgs', maxiter=35, full_output=1, disp=1, callback=None, cov_type='nonrobust', cov_kwds=None, use_t=None, **kwargs)` Fit the model using maximum likelihood. The rest of the docstring is from statsmodels.base.model.LikelihoodModel.fit Fit method for likelihood based models | Parameters: | * **start\_params** (*array-like**,* *optional*) – Initial guess of the solution for the loglikelihood maximization. The default is an array of zeros. * **method** (*str**,* *optional*) – The `method` determines which solver from `scipy.optimize` is used, and it can be chosen from among the following strings: + ’newton’ for Newton-Raphson, ‘nm’ for Nelder-Mead + ’bfgs’ for Broyden-Fletcher-Goldfarb-Shanno (BFGS) + ’lbfgs’ for limited-memory BFGS with optional box constraints + ’powell’ for modified Powell’s method + ’cg’ for conjugate gradient + ’ncg’ for Newton-conjugate gradient + ’basinhopping’ for global basin-hopping solver + ’minimize’ for generic wrapper of scipy minimize (BFGS by default)The explicit arguments in `fit` are passed to the solver, with the exception of the basin-hopping solver. Each solver has several optional arguments that are not the same across solvers. See the notes section below (or scipy.optimize) for the available arguments and for the list of explicit arguments that the basin-hopping solver supports. * **maxiter** (*int**,* *optional*) – The maximum number of iterations to perform. * **full\_output** (*bool**,* *optional*) – Set to True to have all available output in the Results object’s mle\_retvals attribute. The output is dependent on the solver. See LikelihoodModelResults notes section for more information. * **disp** (*bool**,* *optional*) – Set to True to print convergence messages. * **fargs** (*tuple**,* *optional*) – Extra arguments passed to the likelihood function, i.e., loglike(x,\*args) * **callback** (*callable callback**(**xk**)**,* *optional*) – Called after each iteration, as callback(xk), where xk is the current parameter vector. * **retall** (*bool**,* *optional*) – Set to True to return list of solutions at each iteration. Available in Results object’s mle\_retvals attribute. * **skip\_hessian** (*bool**,* *optional*) – If False (default), then the negative inverse hessian is calculated after the optimization. If True, then the hessian will not be calculated. However, it will be available in methods that use the hessian in the optimization (currently only with `“newton”`). * **kwargs** (*keywords*) – All kwargs are passed to the chosen solver with one exception. The following keyword controls what happens after the fit: ``` warn_convergence : bool, optional If True, checks the model for the converged flag. If the converged flag is False, a ConvergenceWarning is issued. ``` | #### Notes The ‘basinhopping’ solver ignores `maxiter`, `retall`, `full_output` explicit arguments. Optional arguments for solvers (see returned Results.mle\_settings): ``` 'newton' tol : float Relative error in params acceptable for convergence. 'nm' -- Nelder Mead xtol : float Relative error in params acceptable for convergence ftol : float Relative error in loglike(params) acceptable for convergence maxfun : int Maximum number of function evaluations to make. 'bfgs' gtol : float Stop when norm of gradient is less than gtol. norm : float Order of norm (np.Inf is max, -np.Inf is min) epsilon If fprime is approximated, use this value for the step size. Only relevant if LikelihoodModel.score is None. 'lbfgs' m : int This many terms are used for the Hessian approximation. factr : float A stop condition that is a variant of relative error. pgtol : float A stop condition that uses the projected gradient. epsilon If fprime is approximated, use this value for the step size. Only relevant if LikelihoodModel.score is None. maxfun : int Maximum number of function evaluations to make. bounds : sequence (min, max) pairs for each element in x, defining the bounds on that parameter. Use None for one of min or max when there is no bound in that direction. 'cg' gtol : float Stop when norm of gradient is less than gtol. norm : float Order of norm (np.Inf is max, -np.Inf is min) epsilon : float If fprime is approximated, use this value for the step size. Can be scalar or vector. Only relevant if Likelihoodmodel.score is None. 'ncg' fhess_p : callable f'(x,*args) Function which computes the Hessian of f times an arbitrary vector, p. Should only be supplied if LikelihoodModel.hessian is None. avextol : float Stop when the average relative error in the minimizer falls below this amount. epsilon : float or ndarray If fhess is approximated, use this value for the step size. Only relevant if Likelihoodmodel.hessian is None. 'powell' xtol : float Line-search error tolerance ftol : float Relative error in loglike(params) for acceptable for convergence. maxfun : int Maximum number of function evaluations to make. start_direc : ndarray Initial direction set. 'basinhopping' niter : integer The number of basin hopping iterations. niter_success : integer Stop the run if the global minimum candidate remains the same for this number of iterations. T : float The "temperature" parameter for the accept or reject criterion. Higher "temperatures" mean that larger jumps in function value will be accepted. For best results `T` should be comparable to the separation (in function value) between local minima. stepsize : float Initial step size for use in the random displacement. interval : integer The interval for how often to update the `stepsize`. minimizer : dict Extra keyword arguments to be passed to the minimizer `scipy.optimize.minimize()`, for example 'method' - the minimization method (e.g. 'L-BFGS-B'), or 'tol' - the tolerance for termination. Other arguments are mapped from explicit argument of `fit`: - `args` <- `fargs` - `jac` <- `score` - `hess` <- `hess` 'minimize' min_method : str, optional Name of minimization method to use. Any method specific arguments can be passed directly. For a list of methods and their arguments, see documentation of `scipy.optimize.minimize`. If no method is specified, then BFGS is used. ```
programming_docs
statsmodels statsmodels.sandbox.tsa.fftarma.ArmaFft.fftarma statsmodels.sandbox.tsa.fftarma.ArmaFft.fftarma =============================================== `ArmaFft.fftarma(n=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/tsa/fftarma.html#ArmaFft.fftarma) Fourier transform of ARMA polynomial, zero-padded at end to n The Fourier transform of the ARMA process is calculated as the ratio of the fft of the MA polynomial divided by the fft of the AR polynomial. | Parameters: | **n** (*int*) – length of array after zero-padding | | Returns: | **fftarma** – fft of zero-padded arma polynomial | | Return type: | ndarray | statsmodels statsmodels.stats.contingency_tables.Table2x2.local_oddsratios statsmodels.stats.contingency\_tables.Table2x2.local\_oddsratios ================================================================ `Table2x2.local_oddsratios()` statsmodels statsmodels.regression.linear_model.RegressionResults statsmodels.regression.linear\_model.RegressionResults ====================================================== `class statsmodels.regression.linear_model.RegressionResults(model, params, normalized_cov_params=None, scale=1.0, cov_type='nonrobust', cov_kwds=None, use_t=None, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#RegressionResults) This class summarizes the fit of a linear regression model. It handles the output of contrasts, estimates of covariance, etc. | Returns: | * *\*\*Attributes\*\** * *aic* – Akaike’s information criteria. For a model with a constant \(-2llf + 2(df\\_model + 1)\). For a model without a constant \(-2llf + 2(df\\_model)\). * *bic* – Bayes’ information criteria. For a model with a constant \(-2llf + \log(n)(df\\_model+1)\). For a model without a constant \(-2llf + \log(n)(df\\_model)\) * *bse* – The standard errors of the parameter estimates. * *pinv\_wexog* – See specific model class docstring * *centered\_tss* – The total (weighted) sum of squares centered about the mean. * *cov\_HC0* – Heteroscedasticity robust covariance matrix. See HC0\_se below. * *cov\_HC1* – Heteroscedasticity robust covariance matrix. See HC1\_se below. * *cov\_HC2* – Heteroscedasticity robust covariance matrix. See HC2\_se below. * *cov\_HC3* – Heteroscedasticity robust covariance matrix. See HC3\_se below. * *cov\_type* – Parameter covariance estimator used for standard errors and t-stats * *df\_model* – Model degrees of freedom. The number of regressors `p`. Does not include the constant if one is present * *df\_resid* – Residual degrees of freedom. `n - p - 1`, if a constant is present. `n - p` if a constant is not included. * *ess* – Explained sum of squares. If a constant is present, the centered total sum of squares minus the sum of squared residuals. If there is no constant, the uncentered total sum of squares is used. * *fvalue* – F-statistic of the fully specified model. Calculated as the mean squared error of the model divided by the mean squared error of the residuals. * *f\_pvalue* – p-value of the F-statistic * *fittedvalues* – The predicted values for the original (unwhitened) design. * *het\_scale* – adjusted squared residuals for heteroscedasticity robust standard errors. Is only available after `HC#_se` or `cov_HC#` is called. See HC#\_se for more information. * *history* – Estimation history for iterative estimators * *HC0\_se* – White’s (1980) heteroskedasticity robust standard errors. Defined as sqrt(diag(X.T X)^(-1)X.T diag(e\_i^(2)) X(X.T X)^(-1) where e\_i = resid[i] HC0\_se is a cached property. When HC0\_se or cov\_HC0 is called the RegressionResults instance will then have another attribute `het_scale`, which is in this case is just resid\*\*2. * *HC1\_se* – MacKinnon and White’s (1985) alternative heteroskedasticity robust standard errors. Defined as sqrt(diag(n/(n-p)\*HC\_0) HC1\_see is a cached property. When HC1\_se or cov\_HC1 is called the RegressionResults instance will then have another attribute `het_scale`, which is in this case is n/(n-p)\*resid\*\*2. * *HC2\_se* – MacKinnon and White’s (1985) alternative heteroskedasticity robust standard errors. Defined as (X.T X)^(-1)X.T diag(e\_i^(2)/(1-h\_ii)) X(X.T X)^(-1) where h\_ii = x\_i(X.T X)^(-1)x\_i.T HC2\_see is a cached property. When HC2\_se or cov\_HC2 is called the RegressionResults instance will then have another attribute `het_scale`, which is in this case is resid^(2)/(1-h\_ii). * *HC3\_se* – MacKinnon and White’s (1985) alternative heteroskedasticity robust standard errors. Defined as (X.T X)^(-1)X.T diag(e\_i^(2)/(1-h\_ii)^(2)) X(X.T X)^(-1) where h\_ii = x\_i(X.T X)^(-1)x\_i.T HC3\_see is a cached property. When HC3\_se or cov\_HC3 is called the RegressionResults instance will then have another attribute `het_scale`, which is in this case is resid^(2)/(1-h\_ii)^(2). * *model* – A pointer to the model instance that called fit() or results. * *mse\_model* – Mean squared error the model. This is the explained sum of squares divided by the model degrees of freedom. * *mse\_resid* – Mean squared error of the residuals. The sum of squared residuals divided by the residual degrees of freedom. * *mse\_total* – Total mean squared error. Defined as the uncentered total sum of squares divided by n the number of observations. * *nobs* – Number of observations n. * *normalized\_cov\_params* – See specific model class docstring * *params* – The linear coefficients that minimize the least squares criterion. This is usually called Beta for the classical linear model. * *pvalues* – The two-tailed p values for the t-stats of the params. * *resid* – The residuals of the model. * *resid\_pearson* – `wresid` normalized to have unit variance. * *rsquared* – R-squared of a model with an intercept. This is defined here as 1 - `ssr`/`centered_tss` if the constant is included in the model and 1 - `ssr`/`uncentered_tss` if the constant is omitted. * *rsquared\_adj* – Adjusted R-squared. This is defined here as 1 - (`nobs`-1)/`df_resid` \* (1-`rsquared`) if a constant is included and 1 - `nobs`/`df_resid` \* (1-`rsquared`) if no constant is included. * *scale* – A scale factor for the covariance matrix. Default value is ssr/(n-p). Note that the square root of `scale` is often called the standard error of the regression. * *ssr* – Sum of squared (whitened) residuals. * *uncentered\_tss* – Uncentered sum of squares. Sum of the squared values of the (whitened) endogenous response variable. * *wresid* – The residuals of the transformed/whitened regressand and regressor(s) | #### Methods | | | | --- | --- | | [`HC0_se`](statsmodels.regression.linear_model.regressionresults.hc0_se#statsmodels.regression.linear_model.RegressionResults.HC0_se "statsmodels.regression.linear_model.RegressionResults.HC0_se")() | See statsmodels.RegressionResults | | [`HC1_se`](statsmodels.regression.linear_model.regressionresults.hc1_se#statsmodels.regression.linear_model.RegressionResults.HC1_se "statsmodels.regression.linear_model.RegressionResults.HC1_se")() | See statsmodels.RegressionResults | | [`HC2_se`](statsmodels.regression.linear_model.regressionresults.hc2_se#statsmodels.regression.linear_model.RegressionResults.HC2_se "statsmodels.regression.linear_model.RegressionResults.HC2_se")() | See statsmodels.RegressionResults | | [`HC3_se`](statsmodels.regression.linear_model.regressionresults.hc3_se#statsmodels.regression.linear_model.RegressionResults.HC3_se "statsmodels.regression.linear_model.RegressionResults.HC3_se")() | See statsmodels.RegressionResults | | [`aic`](statsmodels.regression.linear_model.regressionresults.aic#statsmodels.regression.linear_model.RegressionResults.aic "statsmodels.regression.linear_model.RegressionResults.aic")() | | | [`bic`](statsmodels.regression.linear_model.regressionresults.bic#statsmodels.regression.linear_model.RegressionResults.bic "statsmodels.regression.linear_model.RegressionResults.bic")() | | | [`bse`](statsmodels.regression.linear_model.regressionresults.bse#statsmodels.regression.linear_model.RegressionResults.bse "statsmodels.regression.linear_model.RegressionResults.bse")() | | | [`centered_tss`](statsmodels.regression.linear_model.regressionresults.centered_tss#statsmodels.regression.linear_model.RegressionResults.centered_tss "statsmodels.regression.linear_model.RegressionResults.centered_tss")() | | | [`compare_f_test`](statsmodels.regression.linear_model.regressionresults.compare_f_test#statsmodels.regression.linear_model.RegressionResults.compare_f_test "statsmodels.regression.linear_model.RegressionResults.compare_f_test")(restricted) | use F test to test whether restricted model is correct | | [`compare_lm_test`](statsmodels.regression.linear_model.regressionresults.compare_lm_test#statsmodels.regression.linear_model.RegressionResults.compare_lm_test "statsmodels.regression.linear_model.RegressionResults.compare_lm_test")(restricted[, demean, use\_lr]) | Use Lagrange Multiplier test to test whether restricted model is correct | | [`compare_lr_test`](statsmodels.regression.linear_model.regressionresults.compare_lr_test#statsmodels.regression.linear_model.RegressionResults.compare_lr_test "statsmodels.regression.linear_model.RegressionResults.compare_lr_test")(restricted[, large\_sample]) | Likelihood ratio test to test whether restricted model is correct | | [`condition_number`](statsmodels.regression.linear_model.regressionresults.condition_number#statsmodels.regression.linear_model.RegressionResults.condition_number "statsmodels.regression.linear_model.RegressionResults.condition_number")() | Return condition number of exogenous matrix. | | [`conf_int`](statsmodels.regression.linear_model.regressionresults.conf_int#statsmodels.regression.linear_model.RegressionResults.conf_int "statsmodels.regression.linear_model.RegressionResults.conf_int")([alpha, cols]) | Returns the confidence interval of the fitted parameters. | | [`cov_HC0`](statsmodels.regression.linear_model.regressionresults.cov_hc0#statsmodels.regression.linear_model.RegressionResults.cov_HC0 "statsmodels.regression.linear_model.RegressionResults.cov_HC0")() | See statsmodels.RegressionResults | | [`cov_HC1`](statsmodels.regression.linear_model.regressionresults.cov_hc1#statsmodels.regression.linear_model.RegressionResults.cov_HC1 "statsmodels.regression.linear_model.RegressionResults.cov_HC1")() | See statsmodels.RegressionResults | | [`cov_HC2`](statsmodels.regression.linear_model.regressionresults.cov_hc2#statsmodels.regression.linear_model.RegressionResults.cov_HC2 "statsmodels.regression.linear_model.RegressionResults.cov_HC2")() | See statsmodels.RegressionResults | | [`cov_HC3`](statsmodels.regression.linear_model.regressionresults.cov_hc3#statsmodels.regression.linear_model.RegressionResults.cov_HC3 "statsmodels.regression.linear_model.RegressionResults.cov_HC3")() | See statsmodels.RegressionResults | | [`cov_params`](statsmodels.regression.linear_model.regressionresults.cov_params#statsmodels.regression.linear_model.RegressionResults.cov_params "statsmodels.regression.linear_model.RegressionResults.cov_params")([r\_matrix, column, scale, cov\_p, …]) | Returns the variance/covariance matrix. | | [`eigenvals`](statsmodels.regression.linear_model.regressionresults.eigenvals#statsmodels.regression.linear_model.RegressionResults.eigenvals "statsmodels.regression.linear_model.RegressionResults.eigenvals")() | Return eigenvalues sorted in decreasing order. | | [`ess`](statsmodels.regression.linear_model.regressionresults.ess#statsmodels.regression.linear_model.RegressionResults.ess "statsmodels.regression.linear_model.RegressionResults.ess")() | | | [`f_pvalue`](statsmodels.regression.linear_model.regressionresults.f_pvalue#statsmodels.regression.linear_model.RegressionResults.f_pvalue "statsmodels.regression.linear_model.RegressionResults.f_pvalue")() | | | [`f_test`](statsmodels.regression.linear_model.regressionresults.f_test#statsmodels.regression.linear_model.RegressionResults.f_test "statsmodels.regression.linear_model.RegressionResults.f_test")(r\_matrix[, cov\_p, scale, invcov]) | Compute the F-test for a joint linear hypothesis. | | [`fittedvalues`](statsmodels.regression.linear_model.regressionresults.fittedvalues#statsmodels.regression.linear_model.RegressionResults.fittedvalues "statsmodels.regression.linear_model.RegressionResults.fittedvalues")() | | | [`fvalue`](statsmodels.regression.linear_model.regressionresults.fvalue#statsmodels.regression.linear_model.RegressionResults.fvalue "statsmodels.regression.linear_model.RegressionResults.fvalue")() | | | [`get_prediction`](statsmodels.regression.linear_model.regressionresults.get_prediction#statsmodels.regression.linear_model.RegressionResults.get_prediction "statsmodels.regression.linear_model.RegressionResults.get_prediction")([exog, transform, weights, …]) | compute prediction results | | [`get_robustcov_results`](statsmodels.regression.linear_model.regressionresults.get_robustcov_results#statsmodels.regression.linear_model.RegressionResults.get_robustcov_results "statsmodels.regression.linear_model.RegressionResults.get_robustcov_results")([cov\_type, use\_t]) | create new results instance with robust covariance as default | | [`initialize`](statsmodels.regression.linear_model.regressionresults.initialize#statsmodels.regression.linear_model.RegressionResults.initialize "statsmodels.regression.linear_model.RegressionResults.initialize")(model, params, \*\*kwd) | | | [`llf`](statsmodels.regression.linear_model.regressionresults.llf#statsmodels.regression.linear_model.RegressionResults.llf "statsmodels.regression.linear_model.RegressionResults.llf")() | | | [`load`](statsmodels.regression.linear_model.regressionresults.load#statsmodels.regression.linear_model.RegressionResults.load "statsmodels.regression.linear_model.RegressionResults.load")(fname) | load a pickle, (class method) | | [`mse_model`](statsmodels.regression.linear_model.regressionresults.mse_model#statsmodels.regression.linear_model.RegressionResults.mse_model "statsmodels.regression.linear_model.RegressionResults.mse_model")() | | | [`mse_resid`](statsmodels.regression.linear_model.regressionresults.mse_resid#statsmodels.regression.linear_model.RegressionResults.mse_resid "statsmodels.regression.linear_model.RegressionResults.mse_resid")() | | | [`mse_total`](statsmodels.regression.linear_model.regressionresults.mse_total#statsmodels.regression.linear_model.RegressionResults.mse_total "statsmodels.regression.linear_model.RegressionResults.mse_total")() | | | [`nobs`](statsmodels.regression.linear_model.regressionresults.nobs#statsmodels.regression.linear_model.RegressionResults.nobs "statsmodels.regression.linear_model.RegressionResults.nobs")() | | | [`normalized_cov_params`](statsmodels.regression.linear_model.regressionresults.normalized_cov_params#statsmodels.regression.linear_model.RegressionResults.normalized_cov_params "statsmodels.regression.linear_model.RegressionResults.normalized_cov_params")() | | | [`predict`](statsmodels.regression.linear_model.regressionresults.predict#statsmodels.regression.linear_model.RegressionResults.predict "statsmodels.regression.linear_model.RegressionResults.predict")([exog, transform]) | Call self.model.predict with self.params as the first argument. | | [`pvalues`](statsmodels.regression.linear_model.regressionresults.pvalues#statsmodels.regression.linear_model.RegressionResults.pvalues "statsmodels.regression.linear_model.RegressionResults.pvalues")() | | | [`remove_data`](statsmodels.regression.linear_model.regressionresults.remove_data#statsmodels.regression.linear_model.RegressionResults.remove_data "statsmodels.regression.linear_model.RegressionResults.remove_data")() | remove data arrays, all nobs arrays from result and model | | [`resid`](statsmodels.regression.linear_model.regressionresults.resid#statsmodels.regression.linear_model.RegressionResults.resid "statsmodels.regression.linear_model.RegressionResults.resid")() | | | [`resid_pearson`](statsmodels.regression.linear_model.regressionresults.resid_pearson#statsmodels.regression.linear_model.RegressionResults.resid_pearson "statsmodels.regression.linear_model.RegressionResults.resid_pearson")() | Residuals, normalized to have unit variance. | | [`rsquared`](statsmodels.regression.linear_model.regressionresults.rsquared#statsmodels.regression.linear_model.RegressionResults.rsquared "statsmodels.regression.linear_model.RegressionResults.rsquared")() | | | [`rsquared_adj`](statsmodels.regression.linear_model.regressionresults.rsquared_adj#statsmodels.regression.linear_model.RegressionResults.rsquared_adj "statsmodels.regression.linear_model.RegressionResults.rsquared_adj")() | | | [`save`](statsmodels.regression.linear_model.regressionresults.save#statsmodels.regression.linear_model.RegressionResults.save "statsmodels.regression.linear_model.RegressionResults.save")(fname[, remove\_data]) | save a pickle of this instance | | [`scale`](statsmodels.regression.linear_model.regressionresults.scale#statsmodels.regression.linear_model.RegressionResults.scale "statsmodels.regression.linear_model.RegressionResults.scale")() | | | [`ssr`](statsmodels.regression.linear_model.regressionresults.ssr#statsmodels.regression.linear_model.RegressionResults.ssr "statsmodels.regression.linear_model.RegressionResults.ssr")() | | | [`summary`](statsmodels.regression.linear_model.regressionresults.summary#statsmodels.regression.linear_model.RegressionResults.summary "statsmodels.regression.linear_model.RegressionResults.summary")([yname, xname, title, alpha]) | Summarize the Regression Results | | [`summary2`](statsmodels.regression.linear_model.regressionresults.summary2#statsmodels.regression.linear_model.RegressionResults.summary2 "statsmodels.regression.linear_model.RegressionResults.summary2")([yname, xname, title, alpha, …]) | Experimental summary function to summarize the regression results | | [`t_test`](statsmodels.regression.linear_model.regressionresults.t_test#statsmodels.regression.linear_model.RegressionResults.t_test "statsmodels.regression.linear_model.RegressionResults.t_test")(r\_matrix[, cov\_p, scale, use\_t]) | Compute a t-test for a each linear hypothesis of the form Rb = q | | [`t_test_pairwise`](statsmodels.regression.linear_model.regressionresults.t_test_pairwise#statsmodels.regression.linear_model.RegressionResults.t_test_pairwise "statsmodels.regression.linear_model.RegressionResults.t_test_pairwise")(term\_name[, method, alpha, …]) | perform pairwise t\_test with multiple testing corrected p-values | | [`tvalues`](statsmodels.regression.linear_model.regressionresults.tvalues#statsmodels.regression.linear_model.RegressionResults.tvalues "statsmodels.regression.linear_model.RegressionResults.tvalues")() | Return the t-statistic for a given parameter estimate. | | [`uncentered_tss`](statsmodels.regression.linear_model.regressionresults.uncentered_tss#statsmodels.regression.linear_model.RegressionResults.uncentered_tss "statsmodels.regression.linear_model.RegressionResults.uncentered_tss")() | | | [`wald_test`](statsmodels.regression.linear_model.regressionresults.wald_test#statsmodels.regression.linear_model.RegressionResults.wald_test "statsmodels.regression.linear_model.RegressionResults.wald_test")(r\_matrix[, cov\_p, scale, invcov, …]) | Compute a Wald-test for a joint linear hypothesis. | | [`wald_test_terms`](statsmodels.regression.linear_model.regressionresults.wald_test_terms#statsmodels.regression.linear_model.RegressionResults.wald_test_terms "statsmodels.regression.linear_model.RegressionResults.wald_test_terms")([skip\_single, …]) | Compute a sequence of Wald tests for terms over multiple columns | | [`wresid`](statsmodels.regression.linear_model.regressionresults.wresid#statsmodels.regression.linear_model.RegressionResults.wresid "statsmodels.regression.linear_model.RegressionResults.wresid")() | | #### Attributes | | | | --- | --- | | `use_t` | |
programming_docs
statsmodels statsmodels.discrete.discrete_model.BinaryResults.bse statsmodels.discrete.discrete\_model.BinaryResults.bse ====================================================== `BinaryResults.bse()` statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.initialize_statespace statsmodels.tsa.statespace.dynamic\_factor.DynamicFactor.initialize\_statespace =============================================================================== `DynamicFactor.initialize_statespace(**kwargs)` Initialize the state space representation | Parameters: | **\*\*kwargs** – Additional keyword arguments to pass to the state space class constructor. | statsmodels statsmodels.discrete.discrete_model.NegativeBinomialResults.summary statsmodels.discrete.discrete\_model.NegativeBinomialResults.summary ==================================================================== `NegativeBinomialResults.summary(yname=None, xname=None, title=None, alpha=0.05, yname_list=None)` Summarize the Regression Results | Parameters: | * **yname** (*string**,* *optional*) – Default is `y` * **xname** (*list of strings**,* *optional*) – Default is `var_##` for ## in p the number of regressors * **title** (*string**,* *optional*) – Title for the top table. If not None, then this replaces the default title * **alpha** (*float*) – significance level for the confidence intervals | | Returns: | **smry** – this holds the summary tables and text, which can be printed or converted to various output formats. | | Return type: | Summary instance | See also [`statsmodels.iolib.summary.Summary`](statsmodels.iolib.summary.summary#statsmodels.iolib.summary.Summary "statsmodels.iolib.summary.Summary") class to hold summary results statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.load statsmodels.sandbox.regression.gmm.IVRegressionResults.load =========================================================== `classmethod IVRegressionResults.load(fname)` load a pickle, (class method) | Parameters: | **fname** (*string* *or* *filehandle*) – fname can be a string to a file path or filename, or a filehandle. | | Returns: | | | Return type: | unpickled instance | statsmodels statsmodels.tsa.ar_model.ARResults.fittedvalues statsmodels.tsa.ar\_model.ARResults.fittedvalues ================================================ `ARResults.fittedvalues()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/ar_model.html#ARResults.fittedvalues) statsmodels statsmodels.tsa.statespace.sarimax.SARIMAXResults.t_test_pairwise statsmodels.tsa.statespace.sarimax.SARIMAXResults.t\_test\_pairwise =================================================================== `SARIMAXResults.t_test_pairwise(term_name, method='hs', alpha=0.05, factor_labels=None)` perform pairwise t\_test with multiple testing corrected p-values This uses the formula design\_info encoding contrast matrix and should work for all encodings of a main effect. | Parameters: | * **result** (*result instance*) – The results of an estimated model with a categorical main effect. * **term\_name** (*str*) – name of the term for which pairwise comparisons are computed. Term names for categorical effects are created by patsy and correspond to the main part of the exog names. * **method** (*str* *or* *list of strings*) – multiple testing p-value correction, default is ‘hs’, see stats.multipletesting * **alpha** (*float*) – significance level for multiple testing reject decision. * **factor\_labels** (*None**,* *list of str*) – Labels for the factor levels used for pairwise labels. If not provided, then the labels from the formula design\_info are used. | | Returns: | **results** – The results are stored as attributes, the main attributes are the following two. Other attributes are added for debugging purposes or as background information.* result\_frame : pandas DataFrame with t\_test results and multiple testing corrected p-values. * contrasts : matrix of constraints of the null hypothesis in the t\_test. | | Return type: | instance of a simple Results class | #### Notes Status: experimental. Currently only checked for treatment coding with and without specified reference level. Currently there are no multiple testing corrected confidence intervals available. #### Examples ``` >>> res = ols("np.log(Days+1) ~ C(Weight) + C(Duration)", data).fit() >>> pw = res.t_test_pairwise("C(Weight)") >>> pw.result_frame coef std err t P>|t| Conf. Int. Low 2-1 0.632315 0.230003 2.749157 8.028083e-03 0.171563 3-1 1.302555 0.230003 5.663201 5.331513e-07 0.841803 3-2 0.670240 0.230003 2.914044 5.119126e-03 0.209488 Conf. Int. Upp. pvalue-hs reject-hs 2-1 1.093067 0.010212 True 3-1 1.763307 0.000002 True 3-2 1.130992 0.010212 True ``` statsmodels statsmodels.genmod.families.links.inverse_power.inverse_deriv statsmodels.genmod.families.links.inverse\_power.inverse\_deriv =============================================================== `inverse_power.inverse_deriv(z)` Derivative of the inverse of the power transform | Parameters: | **z** (*array-like*) – `z` is usually the linear predictor for a GLM or GEE model. | | Returns: | * **g^(-1)’(z)** (*array*) – The value of the derivative of the inverse of the power transform * *function* | statsmodels statsmodels.regression.linear_model.OLSResults.wald_test_terms statsmodels.regression.linear\_model.OLSResults.wald\_test\_terms ================================================================= `OLSResults.wald_test_terms(skip_single=False, extra_constraints=None, combine_terms=None)` Compute a sequence of Wald tests for terms over multiple columns This computes joined Wald tests for the hypothesis that all coefficients corresponding to a `term` are zero. `Terms` are defined by the underlying formula or by string matching. | Parameters: | * **skip\_single** (*boolean*) – If true, then terms that consist only of a single column and, therefore, refers only to a single parameter is skipped. If false, then all terms are included. * **extra\_constraints** (*ndarray*) – not tested yet * **combine\_terms** (*None* *or* *list of strings*) – Each string in this list is matched to the name of the terms or the name of the exogenous variables. All columns whose name includes that string are combined in one joint test. | | Returns: | **test\_result** – The result instance contains `table` which is a pandas DataFrame with the test results: test statistic, degrees of freedom and pvalues. | | Return type: | result instance | #### Examples ``` >>> res_ols = ols("np.log(Days+1) ~ C(Duration, Sum)*C(Weight, Sum)", data).fit() >>> res_ols.wald_test_terms() <class 'statsmodels.stats.contrast.WaldTestResults'> F P>F df constraint df denom Intercept 279.754525 2.37985521351e-22 1 51 C(Duration, Sum) 5.367071 0.0245738436636 1 51 C(Weight, Sum) 12.432445 3.99943118767e-05 2 51 C(Duration, Sum):C(Weight, Sum) 0.176002 0.83912310946 2 51 ``` ``` >>> res_poi = Poisson.from_formula("Days ~ C(Weight) * C(Duration)", data).fit(cov_type='HC0') >>> wt = res_poi.wald_test_terms(skip_single=False, combine_terms=['Duration', 'Weight']) >>> print(wt) chi2 P>chi2 df constraint Intercept 15.695625 7.43960374424e-05 1 C(Weight) 16.132616 0.000313940174705 2 C(Duration) 1.009147 0.315107378931 1 C(Weight):C(Duration) 0.216694 0.897315972824 2 Duration 11.187849 0.010752286833 3 Weight 30.263368 4.32586407145e-06 4 ``` statsmodels statsmodels.tsa.vector_ar.vecm.select_coint_rank statsmodels.tsa.vector\_ar.vecm.select\_coint\_rank =================================================== `statsmodels.tsa.vector_ar.vecm.select_coint_rank(endog, det_order, k_ar_diff, method='trace', signif=0.05)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/vecm.html#select_coint_rank) Calculate the cointegration rank of a VECM. | Parameters: | * **endog** (*array-like* *(**nobs\_tot x neqs**)*) – The data with presample. * **det\_order** (*int*) – + -1 - no deterministic terms + 0 - constant term + 1 - linear trend * **k\_ar\_diff** (*int**,* *nonnegative*) – Number of lagged differences in the model. * **method** (str, {`"trace"`, `"maxeig"`}, default: `"trace"`) – If `"trace"`, the trace test statistic is used. If `"maxeig"`, the maximum eigenvalue test statistic is used. * **signif** (*float**,* *{0.1**,* *0.05**,* *0.01}**,* *default: 0.05*) – The test’s significance level. | | Returns: | **rank** – A [`CointRankResults`](statsmodels.tsa.vector_ar.vecm.cointrankresults#statsmodels.tsa.vector_ar.vecm.CointRankResults "statsmodels.tsa.vector_ar.vecm.CointRankResults") object containing the cointegration rank suggested by the test and allowing a summary to be printed. | | Return type: | [`CointRankResults`](statsmodels.tsa.vector_ar.vecm.cointrankresults#statsmodels.tsa.vector_ar.vecm.CointRankResults "statsmodels.tsa.vector_ar.vecm.CointRankResults") | statsmodels statsmodels.genmod.generalized_linear_model.GLM.score_test statsmodels.genmod.generalized\_linear\_model.GLM.score\_test ============================================================= `GLM.score_test(params_constrained, k_constraints=None, exog_extra=None, observed=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_linear_model.html#GLM.score_test) score test for restrictions or for omitted variables The covariance matrix for the score is based on the Hessian, i.e. observed information matrix or optionally on the expected information matrix.. | Parameters: | * **params\_constrained** (*array\_like*) – estimated parameter of the restricted model. This can be the parameter estimate for the current when testing for omitted variables. * **k\_constraints** (*int* *or* *None*) – Number of constraints that were used in the estimation of params restricted relative to the number of exog in the model. This must be provided if no exog\_extra are given. If exog\_extra is not None, then k\_constraints is assumed to be zero if it is None. * **exog\_extra** (*None* *or* *array\_like*) – Explanatory variables that are jointly tested for inclusion in the model, i.e. omitted variables. * **observed** (*bool*) – If True, then the observed Hessian is used in calculating the covariance matrix of the score. If false then the expected information matrix is used. | | Returns: | * **chi2\_stat** (*float*) – chisquare statistic for the score test * **p-value** (*float*) – P-value of the score test based on the chisquare distribution. * **df** (*int*) – Degrees of freedom used in the p-value calculation. This is equal to the number of constraints. | #### Notes not yet verified for case with scale not equal to 1. statsmodels statsmodels.tsa.vector_ar.var_model.VARProcess.plotsim statsmodels.tsa.vector\_ar.var\_model.VARProcess.plotsim ======================================================== `VARProcess.plotsim(steps=None, offset=None, seed=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/var_model.html#VARProcess.plotsim) Plot a simulation from the VAR(p) process for the desired number of steps statsmodels statsmodels.tsa.statespace.structural.UnobservedComponentsResults.cov_params_approx statsmodels.tsa.statespace.structural.UnobservedComponentsResults.cov\_params\_approx ===================================================================================== `UnobservedComponentsResults.cov_params_approx()` (array) The variance / covariance matrix. Computed using the numerical Hessian approximated by complex step or finite differences methods. statsmodels statsmodels.tsa.arima_model.ARMAResults.llf statsmodels.tsa.arima\_model.ARMAResults.llf ============================================ `ARMAResults.llf()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_model.html#ARMAResults.llf) statsmodels statsmodels.discrete.discrete_model.ProbitResults.normalized_cov_params statsmodels.discrete.discrete\_model.ProbitResults.normalized\_cov\_params ========================================================================== `ProbitResults.normalized_cov_params()` statsmodels statsmodels.regression.linear_model.WLS.whiten statsmodels.regression.linear\_model.WLS.whiten =============================================== `WLS.whiten(X)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#WLS.whiten) Whitener for WLS model, multiplies each column by sqrt(self.weights) | Parameters: | **X** (*array-like*) – Data to be whitened | | Returns: | **whitened** – sqrt(weights)\*X | | Return type: | array-like | statsmodels statsmodels.tools.eval_measures.stde statsmodels.tools.eval\_measures.stde ===================================== `statsmodels.tools.eval_measures.stde(x1, x2, ddof=0, axis=0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tools/eval_measures.html#stde) standard deviation of error | Parameters: | * **x2** (*x1**,*) – The performance measure depends on the difference between these two arrays. * **axis** (*int*) – axis along which the summary statistic is calculated | | Returns: | **stde** – standard deviation of difference along given axis. | | Return type: | ndarray or float | #### Notes If `x1` and `x2` have different shapes, then they need to broadcast. This uses `numpy.asanyarray` to convert the input. Whether this is the desired result or not depends on the array subclass. statsmodels statsmodels.iolib.table.SimpleTable.pop statsmodels.iolib.table.SimpleTable.pop ======================================= `SimpleTable.pop([index]) → item -- remove and return item at index (default last).` Raises IndexError if list is empty or index is out of range. statsmodels statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.fit statsmodels.discrete.count\_model.ZeroInflatedGeneralizedPoisson.fit ==================================================================== `ZeroInflatedGeneralizedPoisson.fit(start_params=None, method='bfgs', maxiter=35, full_output=1, disp=1, callback=None, cov_type='nonrobust', cov_kwds=None, use_t=None, **kwargs)` Fit the model using maximum likelihood. The rest of the docstring is from statsmodels.base.model.LikelihoodModel.fit Fit method for likelihood based models | Parameters: | * **start\_params** (*array-like**,* *optional*) – Initial guess of the solution for the loglikelihood maximization. The default is an array of zeros. * **method** (*str**,* *optional*) – The `method` determines which solver from `scipy.optimize` is used, and it can be chosen from among the following strings: + ’newton’ for Newton-Raphson, ‘nm’ for Nelder-Mead + ’bfgs’ for Broyden-Fletcher-Goldfarb-Shanno (BFGS) + ’lbfgs’ for limited-memory BFGS with optional box constraints + ’powell’ for modified Powell’s method + ’cg’ for conjugate gradient + ’ncg’ for Newton-conjugate gradient + ’basinhopping’ for global basin-hopping solver + ’minimize’ for generic wrapper of scipy minimize (BFGS by default)The explicit arguments in `fit` are passed to the solver, with the exception of the basin-hopping solver. Each solver has several optional arguments that are not the same across solvers. See the notes section below (or scipy.optimize) for the available arguments and for the list of explicit arguments that the basin-hopping solver supports. * **maxiter** (*int**,* *optional*) – The maximum number of iterations to perform. * **full\_output** (*bool**,* *optional*) – Set to True to have all available output in the Results object’s mle\_retvals attribute. The output is dependent on the solver. See LikelihoodModelResults notes section for more information. * **disp** (*bool**,* *optional*) – Set to True to print convergence messages. * **fargs** (*tuple**,* *optional*) – Extra arguments passed to the likelihood function, i.e., loglike(x,\*args) * **callback** (*callable callback**(**xk**)**,* *optional*) – Called after each iteration, as callback(xk), where xk is the current parameter vector. * **retall** (*bool**,* *optional*) – Set to True to return list of solutions at each iteration. Available in Results object’s mle\_retvals attribute. * **skip\_hessian** (*bool**,* *optional*) – If False (default), then the negative inverse hessian is calculated after the optimization. If True, then the hessian will not be calculated. However, it will be available in methods that use the hessian in the optimization (currently only with `“newton”`). * **kwargs** (*keywords*) – All kwargs are passed to the chosen solver with one exception. The following keyword controls what happens after the fit: ``` warn_convergence : bool, optional If True, checks the model for the converged flag. If the converged flag is False, a ConvergenceWarning is issued. ``` | #### Notes The ‘basinhopping’ solver ignores `maxiter`, `retall`, `full_output` explicit arguments. Optional arguments for solvers (see returned Results.mle\_settings): ``` 'newton' tol : float Relative error in params acceptable for convergence. 'nm' -- Nelder Mead xtol : float Relative error in params acceptable for convergence ftol : float Relative error in loglike(params) acceptable for convergence maxfun : int Maximum number of function evaluations to make. 'bfgs' gtol : float Stop when norm of gradient is less than gtol. norm : float Order of norm (np.Inf is max, -np.Inf is min) epsilon If fprime is approximated, use this value for the step size. Only relevant if LikelihoodModel.score is None. 'lbfgs' m : int This many terms are used for the Hessian approximation. factr : float A stop condition that is a variant of relative error. pgtol : float A stop condition that uses the projected gradient. epsilon If fprime is approximated, use this value for the step size. Only relevant if LikelihoodModel.score is None. maxfun : int Maximum number of function evaluations to make. bounds : sequence (min, max) pairs for each element in x, defining the bounds on that parameter. Use None for one of min or max when there is no bound in that direction. 'cg' gtol : float Stop when norm of gradient is less than gtol. norm : float Order of norm (np.Inf is max, -np.Inf is min) epsilon : float If fprime is approximated, use this value for the step size. Can be scalar or vector. Only relevant if Likelihoodmodel.score is None. 'ncg' fhess_p : callable f'(x,*args) Function which computes the Hessian of f times an arbitrary vector, p. Should only be supplied if LikelihoodModel.hessian is None. avextol : float Stop when the average relative error in the minimizer falls below this amount. epsilon : float or ndarray If fhess is approximated, use this value for the step size. Only relevant if Likelihoodmodel.hessian is None. 'powell' xtol : float Line-search error tolerance ftol : float Relative error in loglike(params) for acceptable for convergence. maxfun : int Maximum number of function evaluations to make. start_direc : ndarray Initial direction set. 'basinhopping' niter : integer The number of basin hopping iterations. niter_success : integer Stop the run if the global minimum candidate remains the same for this number of iterations. T : float The "temperature" parameter for the accept or reject criterion. Higher "temperatures" mean that larger jumps in function value will be accepted. For best results `T` should be comparable to the separation (in function value) between local minima. stepsize : float Initial step size for use in the random displacement. interval : integer The interval for how often to update the `stepsize`. minimizer : dict Extra keyword arguments to be passed to the minimizer `scipy.optimize.minimize()`, for example 'method' - the minimization method (e.g. 'L-BFGS-B'), or 'tol' - the tolerance for termination. Other arguments are mapped from explicit argument of `fit`: - `args` <- `fargs` - `jac` <- `score` - `hess` <- `hess` 'minimize' min_method : str, optional Name of minimization method to use. Any method specific arguments can be passed directly. For a list of methods and their arguments, see documentation of `scipy.optimize.minimize`. If no method is specified, then BFGS is used. ```
programming_docs
statsmodels statsmodels.discrete.discrete_model.LogitResults.normalized_cov_params statsmodels.discrete.discrete\_model.LogitResults.normalized\_cov\_params ========================================================================= `LogitResults.normalized_cov_params()` statsmodels statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.fittedvalues statsmodels.discrete.count\_model.ZeroInflatedGeneralizedPoissonResults.fittedvalues ==================================================================================== `ZeroInflatedGeneralizedPoissonResults.fittedvalues()` statsmodels statsmodels.emplike.descriptive.DescStat statsmodels.emplike.descriptive.DescStat ======================================== `statsmodels.emplike.descriptive.DescStat(endog)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/emplike/descriptive.html#DescStat) Returns an instance to conduct inference on descriptive statistics via empirical likelihood. See DescStatUV and DescStatMV for more information. | Parameters: | * **endog** (*ndarray*) – Array of data * **Returns** (*DescStat instance*) – If k=1, the function returns a univariate instance, DescStatUV. If k>1, the function returns a multivariate instance, DescStatMV. | statsmodels statsmodels.sandbox.distributions.transformed.Transf_gen.rvs statsmodels.sandbox.distributions.transformed.Transf\_gen.rvs ============================================================= `Transf_gen.rvs(*args, **kwds)` Random variates of given type. | Parameters: | * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information). * **loc** (*array\_like**,* *optional*) – Location parameter (default=0). * **scale** (*array\_like**,* *optional*) – Scale parameter (default=1). * **size** (*int* *or* *tuple of ints**,* *optional*) – Defining number of random variates (default is 1). * **random\_state** (None or int or `np.random.RandomState` instance, optional) – If int or RandomState, use it for drawing the random variates. If None, rely on `self.random_state`. Default is None. | | Returns: | **rvs** – Random variates of given `size`. | | Return type: | ndarray or scalar | statsmodels statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression.predict_conditional statsmodels.tsa.regime\_switching.markov\_autoregression.MarkovAutoregression.predict\_conditional ================================================================================================== `MarkovAutoregression.predict_conditional(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/regime_switching/markov_autoregression.html#MarkovAutoregression.predict_conditional) In-sample prediction, conditional on the current and previous regime | Parameters: | **params** (*array\_like*) – Array of parameters at which to create predictions. | | Returns: | **predict** – Array of predictions conditional on current, and possibly past, regimes | | Return type: | array\_like | statsmodels statsmodels.regression.linear_model.GLSAR.predict statsmodels.regression.linear\_model.GLSAR.predict ================================================== `GLSAR.predict(params, exog=None)` Return linear predicted values from a design matrix. | Parameters: | * **params** (*array-like*) – Parameters of a linear model * **exog** (*array-like**,* *optional.*) – Design / exogenous data. Model exog is used if None. | | Returns: | | | Return type: | An array of fitted values | #### Notes If the model has not yet been fit, params is not optional. statsmodels statsmodels.tsa.statespace.varmax.VARMAX.hessian statsmodels.tsa.statespace.varmax.VARMAX.hessian ================================================ `VARMAX.hessian(params, *args, **kwargs)` Hessian matrix of the likelihood function, evaluated at the given parameters | Parameters: | * **params** (*array\_like*) – Array of parameters at which to evaluate the hessian. * **args** – Additional positional arguments to the `loglike` method. * **kwargs** – Additional keyword arguments to the `loglike` method. | | Returns: | **hessian** – Hessian matrix evaluated at `params` | | Return type: | array | #### Notes This is a numerical approximation. Both \*args and \*\*kwargs are necessary because the optimizer from `fit` must call this function and only supports passing arguments via \*args (for example `scipy.optimize.fmin_l_bfgs`). statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.impulse_responses statsmodels.tsa.statespace.dynamic\_factor.DynamicFactor.impulse\_responses =========================================================================== `DynamicFactor.impulse_responses(params, steps=1, impulse=0, orthogonalized=False, cumulative=False, **kwargs)` Impulse response function | Parameters: | * **params** (*array\_like*) – Array of model parameters. * **steps** (*int**,* *optional*) – The number of steps for which impulse responses are calculated. Default is 1. Note that the initial impulse is not counted as a step, so if `steps=1`, the output will have 2 entries. * **impulse** (*int* *or* *array\_like*) – If an integer, the state innovation to pulse; must be between 0 and `k_posdef-1`. Alternatively, a custom impulse vector may be provided; must be shaped `k_posdef x 1`. * **orthogonalized** (*boolean**,* *optional*) – Whether or not to perform impulse using orthogonalized innovations. Note that this will also affect custum `impulse` vectors. Default is False. * **cumulative** (*boolean**,* *optional*) – Whether or not to return cumulative impulse responses. Default is False. * **\*\*kwargs** – If the model is time-varying and `steps` is greater than the number of observations, any of the state space representation matrices that are time-varying must have updated values provided for the out-of-sample steps. For example, if `design` is a time-varying component, `nobs` is 10, and `steps` is 15, a (`k_endog` x `k_states` x 5) matrix must be provided with the new design matrix values. | | Returns: | **impulse\_responses** – Responses for each endogenous variable due to the impulse given by the `impulse` argument. A (steps + 1 x k\_endog) array. | | Return type: | array | #### Notes Intercepts in the measurement and state equation are ignored when calculating impulse responses. statsmodels statsmodels.iolib.table.SimpleTable.remove statsmodels.iolib.table.SimpleTable.remove ========================================== `SimpleTable.remove(value) → None -- remove first occurrence of value.` Raises ValueError if the value is not present. statsmodels statsmodels.tsa.vector_ar.vecm.select_order statsmodels.tsa.vector\_ar.vecm.select\_order ============================================= `statsmodels.tsa.vector_ar.vecm.select_order(data, maxlags, deterministic='nc', seasons=0, exog=None, exog_coint=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/vecm.html#select_order) Compute lag order selections based on each of the available information criteria. | Parameters: | * **data** (*array-like* *(**nobs\_tot x neqs**)*) – The observed data. * **maxlags** (*int*) – All orders until maxlag will be compared according to the information criteria listed in the Results-section of this docstring. * **deterministic** (str {`"nc"`, `"co"`, `"ci"`, `"lo"`, `"li"`}) – + `"nc"` - no deterministic terms + `"co"` - constant outside the cointegration relation + `"ci"` - constant within the cointegration relation + `"lo"` - linear trend outside the cointegration relation + `"li"` - linear trend within the cointegration relationCombinations of these are possible (e.g. `"cili"` or `"colo"` for linear trend with intercept). See the docstring of the [`VECM`](statsmodels.tsa.vector_ar.vecm.vecm#statsmodels.tsa.vector_ar.vecm.VECM "statsmodels.tsa.vector_ar.vecm.VECM")-class for more information. * **seasons** (*int**,* *default: 0*) – Number of periods in a seasonal cycle. * **exog** (ndarray (nobs\_tot x neqs) or `None`, default: `None`) – Deterministic terms outside the cointegration relation. * **exog\_coint** (ndarray (nobs\_tot x neqs) or `None`, default: `None`) – Deterministic terms inside the cointegration relation. | | Returns: | **selected\_orders** | | Return type: | [`statsmodels.tsa.vector_ar.var_model.LagOrderResults`](statsmodels.tsa.vector_ar.var_model.lagorderresults#statsmodels.tsa.vector_ar.var_model.LagOrderResults "statsmodels.tsa.vector_ar.var_model.LagOrderResults") | statsmodels statsmodels.robust.norms.TrimmedMean statsmodels.robust.norms.TrimmedMean ==================================== `class statsmodels.robust.norms.TrimmedMean(c=2.0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/norms.html#TrimmedMean) Trimmed mean function for M-estimation. | Parameters: | **c** (*float**,* *optional*) – The tuning constant for Ramsay’s Ea function. The default value is 2.0. | See also [`statsmodels.robust.norms.RobustNorm`](statsmodels.robust.norms.robustnorm#statsmodels.robust.norms.RobustNorm "statsmodels.robust.norms.RobustNorm") #### Methods | | | | --- | --- | | [`psi`](statsmodels.robust.norms.trimmedmean.psi#statsmodels.robust.norms.TrimmedMean.psi "statsmodels.robust.norms.TrimmedMean.psi")(z) | The psi function for least trimmed mean | | [`psi_deriv`](statsmodels.robust.norms.trimmedmean.psi_deriv#statsmodels.robust.norms.TrimmedMean.psi_deriv "statsmodels.robust.norms.TrimmedMean.psi_deriv")(z) | The derivative of least trimmed mean psi function | | [`rho`](statsmodels.robust.norms.trimmedmean.rho#statsmodels.robust.norms.TrimmedMean.rho "statsmodels.robust.norms.TrimmedMean.rho")(z) | The robust criterion function for least trimmed mean. | | [`weights`](statsmodels.robust.norms.trimmedmean.weights#statsmodels.robust.norms.TrimmedMean.weights "statsmodels.robust.norms.TrimmedMean.weights")(z) | Least trimmed mean weighting function for the IRLS algorithm | statsmodels statsmodels.nonparametric.kernel_density.KDEMultivariate.pdf statsmodels.nonparametric.kernel\_density.KDEMultivariate.pdf ============================================================= `KDEMultivariate.pdf(data_predict=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/nonparametric/kernel_density.html#KDEMultivariate.pdf) Evaluate the probability density function. | Parameters: | **data\_predict** (*array\_like**,* *optional*) – Points to evaluate at. If unspecified, the training data is used. | | Returns: | **pdf\_est** – Probability density function evaluated at `data_predict`. | | Return type: | array\_like | #### Notes The probability density is given by the generalized product kernel estimator: \[K\_{h}(X\_{i},X\_{j}) = \prod\_{s=1}^{q}h\_{s}^{-1}k\left(\frac{X\_{is}-X\_{js}}{h\_{s}}\right)\] statsmodels statsmodels.tsa.statespace.mlemodel.MLEResults.get_prediction statsmodels.tsa.statespace.mlemodel.MLEResults.get\_prediction ============================================================== `MLEResults.get_prediction(start=None, end=None, dynamic=False, index=None, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEResults.get_prediction) In-sample prediction and out-of-sample forecasting | Parameters: | * **start** (*int**,* *str**, or* *datetime**,* *optional*) – Zero-indexed observation number at which to start forecasting, i.e., the first forecast is start. Can also be a date string to parse or a datetime type. Default is the the zeroth observation. * **end** (*int**,* *str**, or* *datetime**,* *optional*) – Zero-indexed observation number at which to end forecasting, i.e., the last forecast is end. Can also be a date string to parse or a datetime type. However, if the dates index does not have a fixed frequency, end must be an integer index if you want out of sample prediction. Default is the last observation in the sample. * **dynamic** (*boolean**,* *int**,* *str**, or* *datetime**,* *optional*) – Integer offset relative to `start` at which to begin dynamic prediction. Can also be an absolute date string to parse or a datetime type (these are not interpreted as offsets). Prior to this observation, true endogenous values will be used for prediction; starting with this observation and continuing through the end of prediction, forecasted endogenous values will be used instead. * **\*\*kwargs** – Additional arguments may required for forecasting beyond the end of the sample. See `FilterResults.predict` for more details. | | Returns: | **forecast** – Array of out of in-sample predictions and / or out-of-sample forecasts. An (npredict x k\_endog) array. | | Return type: | array | statsmodels statsmodels.sandbox.regression.gmm.GMMResults.f_test statsmodels.sandbox.regression.gmm.GMMResults.f\_test ===================================================== `GMMResults.f_test(r_matrix, cov_p=None, scale=1.0, invcov=None)` Compute the F-test for a joint linear hypothesis. This is a special case of `wald_test` that always uses the F distribution. | Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) – + array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length k row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – Default is 1.0 for no scaling. * **invcov** (*array-like**,* *optional*) – A q x q array to specify an inverse covariance matrix based on a restrictions matrix. | | Returns: | **res** – The results for the test are attributes of this results instance. | | Return type: | ContrastResults instance | #### Examples ``` >>> import numpy as np >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> A = np.identity(len(results.params)) >>> A = A[1:,:] ``` This tests that each coefficient is jointly statistically significantly different from zero. ``` >>> print(results.f_test(A)) <F test: F=array([[ 330.28533923]]), p=4.984030528700946e-10, df_denom=9, df_num=6> ``` Compare this to ``` >>> results.fvalue 330.2853392346658 >>> results.f_pvalue 4.98403096572e-10 ``` ``` >>> B = np.array(([0,0,1,-1,0,0,0],[0,0,0,0,0,1,-1])) ``` This tests that the coefficient on the 2nd and 3rd regressors are equal and jointly that the coefficient on the 5th and 6th regressors are equal. ``` >>> print(results.f_test(B)) <F test: F=array([[ 9.74046187]]), p=0.005605288531708235, df_denom=9, df_num=2> ``` Alternatively, you can specify the hypothesis tests using a string ``` >>> from statsmodels.datasets import longley >>> from statsmodels.formula.api import ols >>> dta = longley.load_pandas().data >>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' >>> results = ols(formula, dta).fit() >>> hypotheses = '(GNPDEFL = GNP), (UNEMP = 2), (YEAR/1829 = 1)' >>> f_test = results.f_test(hypotheses) >>> print(f_test) <F test: F=array([[ 144.17976065]]), p=6.322026217355609e-08, df_denom=9, df_num=3> ``` See also [`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`wald_test`](statsmodels.sandbox.regression.gmm.gmmresults.wald_test#statsmodels.sandbox.regression.gmm.GMMResults.wald_test "statsmodels.sandbox.regression.gmm.GMMResults.wald_test"), [`t_test`](statsmodels.sandbox.regression.gmm.gmmresults.t_test#statsmodels.sandbox.regression.gmm.GMMResults.t_test "statsmodels.sandbox.regression.gmm.GMMResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") #### Notes The matrix `r_matrix` is assumed to be non-singular. More precisely, r\_matrix (pX pX.T) r\_matrix.T is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full. statsmodels statsmodels.tsa.arima_model.ARIMAResults.summary2 statsmodels.tsa.arima\_model.ARIMAResults.summary2 ================================================== `ARIMAResults.summary2(title=None, alpha=0.05, float_format='%.4f')` Experimental summary function for ARIMA Results | Parameters: | * **title** (*string**,* *optional*) – Title for the top table. If not None, then this replaces the default title * **alpha** (*float*) – significance level for the confidence intervals * **float\_format** (*string*) – print format for floats in parameters summary | | Returns: | **smry** – This holds the summary table and text, which can be printed or converted to various output formats. | | Return type: | Summary instance | See also [`statsmodels.iolib.summary2.Summary`](statsmodels.iolib.summary2.summary#statsmodels.iolib.summary2.Summary "statsmodels.iolib.summary2.Summary") class to hold summary results statsmodels statsmodels.discrete.discrete_model.NegativeBinomialP.fit statsmodels.discrete.discrete\_model.NegativeBinomialP.fit ========================================================== `NegativeBinomialP.fit(start_params=None, method='bfgs', maxiter=35, full_output=1, disp=1, callback=None, use_transparams=False, cov_type='nonrobust', cov_kwds=None, use_t=None, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#NegativeBinomialP.fit) | Parameters: | * **use\_transparams** (*bool*) – This parameter enable internal transformation to impose non-negativity. True to enable. Default is False. use\_transparams=True imposes the no underdispersion (alpha > 0) constaint. In case use\_transparams=True and method=”newton” or “ncg” transformation is ignored. * **the model using maximum likelihood.** (*Fit*) – * **rest of the docstring is from** (*The*) – * **statsmodels.base.model.LikelihoodModel.fit** – * **method for likelihood based models** (*Fit*) – * **start\_params** (*array-like**,* *optional*) – Initial guess of the solution for the loglikelihood maximization. The default is an array of zeros. * **method** (*str**,* *optional*) – The `method` determines which solver from `scipy.optimize` is used, and it can be chosen from among the following strings: + ’newton’ for Newton-Raphson, ‘nm’ for Nelder-Mead + ’bfgs’ for Broyden-Fletcher-Goldfarb-Shanno (BFGS) + ’lbfgs’ for limited-memory BFGS with optional box constraints + ’powell’ for modified Powell’s method + ’cg’ for conjugate gradient + ’ncg’ for Newton-conjugate gradient + ’basinhopping’ for global basin-hopping solver + ’minimize’ for generic wrapper of scipy minimize (BFGS by default)The explicit arguments in `fit` are passed to the solver, with the exception of the basin-hopping solver. Each solver has several optional arguments that are not the same across solvers. See the notes section below (or scipy.optimize) for the available arguments and for the list of explicit arguments that the basin-hopping solver supports. * **maxiter** (*int**,* *optional*) – The maximum number of iterations to perform. * **full\_output** (*bool**,* *optional*) – Set to True to have all available output in the Results object’s mle\_retvals attribute. The output is dependent on the solver. See LikelihoodModelResults notes section for more information. * **disp** (*bool**,* *optional*) – Set to True to print convergence messages. * **fargs** (*tuple**,* *optional*) – Extra arguments passed to the likelihood function, i.e., loglike(x,\*args) * **callback** (*callable callback**(**xk**)**,* *optional*) – Called after each iteration, as callback(xk), where xk is the current parameter vector. * **retall** (*bool**,* *optional*) – Set to True to return list of solutions at each iteration. Available in Results object’s mle\_retvals attribute. * **skip\_hessian** (*bool**,* *optional*) – If False (default), then the negative inverse hessian is calculated after the optimization. If True, then the hessian will not be calculated. However, it will be available in methods that use the hessian in the optimization (currently only with `“newton”`). * **kwargs** (*keywords*) – All kwargs are passed to the chosen solver with one exception. The following keyword controls what happens after the fit: ``` warn_convergence : bool, optional If True, checks the model for the converged flag. If the converged flag is False, a ConvergenceWarning is issued. ``` | #### Notes The ‘basinhopping’ solver ignores `maxiter`, `retall`, `full_output` explicit arguments. Optional arguments for solvers (see returned Results.mle\_settings): ``` 'newton' tol : float Relative error in params acceptable for convergence. 'nm' -- Nelder Mead xtol : float Relative error in params acceptable for convergence ftol : float Relative error in loglike(params) acceptable for convergence maxfun : int Maximum number of function evaluations to make. 'bfgs' gtol : float Stop when norm of gradient is less than gtol. norm : float Order of norm (np.Inf is max, -np.Inf is min) epsilon If fprime is approximated, use this value for the step size. Only relevant if LikelihoodModel.score is None. 'lbfgs' m : int This many terms are used for the Hessian approximation. factr : float A stop condition that is a variant of relative error. pgtol : float A stop condition that uses the projected gradient. epsilon If fprime is approximated, use this value for the step size. Only relevant if LikelihoodModel.score is None. maxfun : int Maximum number of function evaluations to make. bounds : sequence (min, max) pairs for each element in x, defining the bounds on that parameter. Use None for one of min or max when there is no bound in that direction. 'cg' gtol : float Stop when norm of gradient is less than gtol. norm : float Order of norm (np.Inf is max, -np.Inf is min) epsilon : float If fprime is approximated, use this value for the step size. Can be scalar or vector. Only relevant if Likelihoodmodel.score is None. 'ncg' fhess_p : callable f'(x,*args) Function which computes the Hessian of f times an arbitrary vector, p. Should only be supplied if LikelihoodModel.hessian is None. avextol : float Stop when the average relative error in the minimizer falls below this amount. epsilon : float or ndarray If fhess is approximated, use this value for the step size. Only relevant if Likelihoodmodel.hessian is None. 'powell' xtol : float Line-search error tolerance ftol : float Relative error in loglike(params) for acceptable for convergence. maxfun : int Maximum number of function evaluations to make. start_direc : ndarray Initial direction set. 'basinhopping' niter : integer The number of basin hopping iterations. niter_success : integer Stop the run if the global minimum candidate remains the same for this number of iterations. T : float The "temperature" parameter for the accept or reject criterion. Higher "temperatures" mean that larger jumps in function value will be accepted. For best results `T` should be comparable to the separation (in function value) between local minima. stepsize : float Initial step size for use in the random displacement. interval : integer The interval for how often to update the `stepsize`. minimizer : dict Extra keyword arguments to be passed to the minimizer `scipy.optimize.minimize()`, for example 'method' - the minimization method (e.g. 'L-BFGS-B'), or 'tol' - the tolerance for termination. Other arguments are mapped from explicit argument of `fit`: - `args` <- `fargs` - `jac` <- `score` - `hess` <- `hess` 'minimize' min_method : str, optional Name of minimization method to use. Any method specific arguments can be passed directly. For a list of methods and their arguments, see documentation of `scipy.optimize.minimize`. If no method is specified, then BFGS is used. ```
programming_docs
statsmodels statsmodels.sandbox.regression.gmm.NonlinearIVGMM.momcond_mean statsmodels.sandbox.regression.gmm.NonlinearIVGMM.momcond\_mean =============================================================== `NonlinearIVGMM.momcond_mean(params)` mean of moment conditions, statsmodels statsmodels.discrete.discrete_model.DiscreteResults.get_margeff statsmodels.discrete.discrete\_model.DiscreteResults.get\_margeff ================================================================= `DiscreteResults.get_margeff(at='overall', method='dydx', atexog=None, dummy=False, count=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#DiscreteResults.get_margeff) Get marginal effects of the fitted model. | Parameters: | * **at** (*str**,* *optional*) – Options are: + ’overall’, The average of the marginal effects at each observation. + ’mean’, The marginal effects at the mean of each regressor. + ’median’, The marginal effects at the median of each regressor. + ’zero’, The marginal effects at zero for each regressor. + ’all’, The marginal effects at each observation. If `at` is all only margeff will be available from the returned object.Note that if `exog` is specified, then marginal effects for all variables not specified by `exog` are calculated using the `at` option. * **method** (*str**,* *optional*) – Options are: + ’dydx’ - dy/dx - No transformation is made and marginal effects are returned. This is the default. + ’eyex’ - estimate elasticities of variables in `exog` – d(lny)/d(lnx) + ’dyex’ - estimate semielasticity – dy/d(lnx) + ’eydx’ - estimate semeilasticity – d(lny)/dxNote that tranformations are done after each observation is calculated. Semi-elasticities for binary variables are computed using the midpoint method. ‘dyex’ and ‘eyex’ do not make sense for discrete variables. * **atexog** (*array-like**,* *optional*) – Optionally, you can provide the exogenous variables over which to get the marginal effects. This should be a dictionary with the key as the zero-indexed column number and the value of the dictionary. Default is None for all independent variables less the constant. * **dummy** (*bool**,* *optional*) – If False, treats binary variables (if present) as continuous. This is the default. Else if True, treats binary variables as changing from 0 to 1. Note that any variable that is either 0 or 1 is treated as binary. Each binary variable is treated separately for now. * **count** (*bool**,* *optional*) – If False, treats count variables (if present) as continuous. This is the default. Else if True, the marginal effect is the change in probabilities when each observation is increased by one. | | Returns: | **DiscreteMargins** – Returns an object that holds the marginal effects, standard errors, confidence intervals, etc. See `statsmodels.discrete.discrete_margins.DiscreteMargins` for more information. | | Return type: | marginal effects instance | #### Notes When using after Poisson, returns the expected number of events per period, assuming that the model is loglinear. statsmodels statsmodels.regression.linear_model.PredictionResults.conf_int statsmodels.regression.linear\_model.PredictionResults.conf\_int ================================================================ `PredictionResults.conf_int(obs=False, alpha=0.05)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/_prediction.html#PredictionResults.conf_int) Returns the confidence interval of the value, `effect` of the constraint. This is currently only available for t and z tests. | Parameters: | **alpha** (*float**,* *optional*) – The significance level for the confidence interval. ie., The default `alpha` = .05 returns a 95% confidence interval. | | Returns: | **ci** – The array has the lower and the upper limit of the confidence interval in the columns. | | Return type: | ndarray, (k\_constraints, 2) | statsmodels statsmodels.tsa.holtwinters.HoltWintersResults.predict statsmodels.tsa.holtwinters.HoltWintersResults.predict ====================================================== `HoltWintersResults.predict(start=None, end=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/holtwinters.html#HoltWintersResults.predict) In-sample prediction and out-of-sample forecasting | Parameters: | * **start** (*int**,* *str**, or* *datetime**,* *optional*) – Zero-indexed observation number at which to start forecasting, ie., the first forecast is start. Can also be a date string to parse or a datetime type. Default is the the zeroth observation. * **end** (*int**,* *str**, or* *datetime**,* *optional*) – Zero-indexed observation number at which to end forecasting, ie., the first forecast is start. Can also be a date string to parse or a datetime type. However, if the dates index does not have a fixed frequency, end must be an integer index if you want out of sample prediction. Default is the last observation in the sample. | | Returns: | **forecast** – Array of out of sample forecasts. | | Return type: | array | statsmodels statsmodels.sandbox.distributions.extras.SkewNorm2_gen.freeze statsmodels.sandbox.distributions.extras.SkewNorm2\_gen.freeze ============================================================== `SkewNorm2_gen.freeze(*args, **kwds)` Freeze the distribution for the given arguments. | Parameters: | **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution. Should include all the non-optional arguments, may include `loc` and `scale`. | | Returns: | **rv\_frozen** – The frozen distribution. | | Return type: | rv\_frozen instance | statsmodels statsmodels.stats.contingency_tables.Table.fittedvalues statsmodels.stats.contingency\_tables.Table.fittedvalues ======================================================== `Table.fittedvalues()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table.fittedvalues) statsmodels statsmodels.duration.hazard_regression.PHRegResults.bse statsmodels.duration.hazard\_regression.PHRegResults.bse ======================================================== `PHRegResults.bse()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/duration/hazard_regression.html#PHRegResults.bse) Returns the standard errors of the parameter estimates. statsmodels statsmodels.nonparametric.kernel_regression.KernelReg.sig_test statsmodels.nonparametric.kernel\_regression.KernelReg.sig\_test ================================================================ `KernelReg.sig_test(var_pos, nboot=50, nested_res=25, pivot=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/nonparametric/kernel_regression.html#KernelReg.sig_test) Significance test for the variables in the regression. | Parameters: | **var\_pos** (*sequence*) – The position of the variable in exog to be tested. | | Returns: | **sig** –The level of significance:* `*` : at 90% confidence level * `**` : at 95% confidence level * `***` : at 99\* confidence level * ”Not Significant” : if not significant | | Return type: | str | statsmodels statsmodels.iolib.summary2.Summary.as_html statsmodels.iolib.summary2.Summary.as\_html =========================================== `Summary.as_html()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/iolib/summary2.html#Summary.as_html) Generate HTML Summary Table statsmodels statsmodels.stats.contingency_tables.Table2x2.test_nominal_association statsmodels.stats.contingency\_tables.Table2x2.test\_nominal\_association ========================================================================= `Table2x2.test_nominal_association()` Assess independence for nominal factors. Assessment of independence between rows and columns using chi^2 testing. The rows and columns are treated as nominal (unordered) categorical variables. | Returns: | * *A bunch containing the following attributes* * **statistic** (*float*) – The chi^2 test statistic. * **df** (*integer*) – The degrees of freedom of the reference distribution * **pvalue** (*float*) – The p-value for the test. | statsmodels statsmodels.sandbox.distributions.transformed.TransfTwo_gen.interval statsmodels.sandbox.distributions.transformed.TransfTwo\_gen.interval ===================================================================== `TransfTwo_gen.interval(alpha, *args, **kwds)` Confidence interval with equal areas around the median. | Parameters: | * **alpha** (*array\_like of float*) – Probability that an rv will be drawn from the returned range. Each value should be in the range [0, 1]. * **arg2****,** **..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information). * **loc** (*array\_like**,* *optional*) – location parameter, Default is 0. * **scale** (*array\_like**,* *optional*) – scale parameter, Default is 1. | | Returns: | **a, b** – end-points of range that contain `100 * alpha %` of the rv’s possible values. | | Return type: | ndarray of float | statsmodels statsmodels.sandbox.distributions.extras.ACSkewT_gen.median statsmodels.sandbox.distributions.extras.ACSkewT\_gen.median ============================================================ `ACSkewT_gen.median(*args, **kwds)` Median of the distribution. | Parameters: | * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – Location parameter, Default is 0. * **scale** (*array\_like**,* *optional*) – Scale parameter, Default is 1. | | Returns: | **median** – The median of the distribution. | | Return type: | float | See also `stats.distributions.rv_discrete.ppf` Inverse of the CDF statsmodels statsmodels.regression.linear_model.RegressionResults.HC2_se statsmodels.regression.linear\_model.RegressionResults.HC2\_se ============================================================== `RegressionResults.HC2_se()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#RegressionResults.HC2_se) See statsmodels.RegressionResults statsmodels statsmodels.discrete.count_model.ZeroInflatedPoissonResults.aic statsmodels.discrete.count\_model.ZeroInflatedPoissonResults.aic ================================================================ `ZeroInflatedPoissonResults.aic()` statsmodels statsmodels.regression.recursive_ls.RecursiveLS.set_smoother_output statsmodels.regression.recursive\_ls.RecursiveLS.set\_smoother\_output ====================================================================== `RecursiveLS.set_smoother_output(smoother_output=None, **kwargs)` Set the smoother output The smoother can produce several types of results. The smoother output variable controls which are calculated and returned. | Parameters: | * **smoother\_output** (*integer**,* *optional*) – Bitmask value to set the smoother output to. See notes for details. * **\*\*kwargs** – Keyword arguments may be used to influence the smoother output by setting individual boolean flags. | #### Notes This method is rarely used. See the corresponding function in the `KalmanSmoother` class for details. statsmodels statsmodels.tsa.statespace.mlemodel.MLEResults.t_test_pairwise statsmodels.tsa.statespace.mlemodel.MLEResults.t\_test\_pairwise ================================================================ `MLEResults.t_test_pairwise(term_name, method='hs', alpha=0.05, factor_labels=None)` perform pairwise t\_test with multiple testing corrected p-values This uses the formula design\_info encoding contrast matrix and should work for all encodings of a main effect. | Parameters: | * **result** (*result instance*) – The results of an estimated model with a categorical main effect. * **term\_name** (*str*) – name of the term for which pairwise comparisons are computed. Term names for categorical effects are created by patsy and correspond to the main part of the exog names. * **method** (*str* *or* *list of strings*) – multiple testing p-value correction, default is ‘hs’, see stats.multipletesting * **alpha** (*float*) – significance level for multiple testing reject decision. * **factor\_labels** (*None**,* *list of str*) – Labels for the factor levels used for pairwise labels. If not provided, then the labels from the formula design\_info are used. | | Returns: | **results** – The results are stored as attributes, the main attributes are the following two. Other attributes are added for debugging purposes or as background information.* result\_frame : pandas DataFrame with t\_test results and multiple testing corrected p-values. * contrasts : matrix of constraints of the null hypothesis in the t\_test. | | Return type: | instance of a simple Results class | #### Notes Status: experimental. Currently only checked for treatment coding with and without specified reference level. Currently there are no multiple testing corrected confidence intervals available. #### Examples ``` >>> res = ols("np.log(Days+1) ~ C(Weight) + C(Duration)", data).fit() >>> pw = res.t_test_pairwise("C(Weight)") >>> pw.result_frame coef std err t P>|t| Conf. Int. Low 2-1 0.632315 0.230003 2.749157 8.028083e-03 0.171563 3-1 1.302555 0.230003 5.663201 5.331513e-07 0.841803 3-2 0.670240 0.230003 2.914044 5.119126e-03 0.209488 Conf. Int. Upp. pvalue-hs reject-hs 2-1 1.093067 0.010212 True 3-1 1.763307 0.000002 True 3-2 1.130992 0.010212 True ``` statsmodels statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.remove_data statsmodels.discrete.count\_model.ZeroInflatedGeneralizedPoissonResults.remove\_data ==================================================================================== `ZeroInflatedGeneralizedPoissonResults.remove_data()` remove data arrays, all nobs arrays from result and model This reduces the size of the instance, so it can be pickled with less memory. Currently tested for use with predict from an unpickled results and model instance. Warning Since data and some intermediate results have been removed calculating new statistics that require them will raise exceptions. The exception will occur the first time an attribute is accessed that has been set to None. Not fully tested for time series models, tsa, and might delete too much for prediction or not all that would be possible. The lists of arrays to delete are maintained as attributes of the result and model instance, except for cached values. These lists could be changed before calling remove\_data. The attributes to remove are named in: `model._data_attr : arrays attached to both the model instance` and the results instance with the same attribute name. `result.data_in_cache : arrays that may exist as values in` result.\_cache (TODO : should privatize name) `result._data_attr_model : arrays attached to the model` instance but not to the results instance statsmodels statsmodels.regression.linear_model.GLSAR.information statsmodels.regression.linear\_model.GLSAR.information ====================================================== `GLSAR.information(params)` Fisher information matrix of model Returns -Hessian of loglike evaluated at params. statsmodels statsmodels.discrete.discrete_model.BinaryResults statsmodels.discrete.discrete\_model.BinaryResults ================================================== `class statsmodels.discrete.discrete_model.BinaryResults(model, mlefit, cov_type='nonrobust', cov_kwds=None, use_t=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#BinaryResults) A results class for binary data | Parameters: | * **model** (*A DiscreteModel instance*) – * **params** (*array-like*) – The parameters of a fitted model. * **hessian** (*array-like*) – The hessian of the fitted model. * **scale** (*float*) – A scale parameter for the covariance matrix. | | Returns: | * *\*Attributes\** * **aic** (*float*) – Akaike information criterion. `-2*(llf - p)` where `p` is the number of regressors including the intercept. * **bic** (*float*) – Bayesian information criterion. `-2*llf + ln(nobs)*p` where `p` is the number of regressors including the intercept. * **bse** (*array*) – The standard errors of the coefficients. * **df\_resid** (*float*) – See model definition. * **df\_model** (*float*) – See model definition. * **fitted\_values** (*array*) – Linear predictor XB. * **llf** (*float*) – Value of the loglikelihood * **llnull** (*float*) – Value of the constant-only loglikelihood * **llr** (*float*) – Likelihood ratio chi-squared statistic; `-2*(llnull - llf)` * **llr\_pvalue** (*float*) – The chi-squared probability of getting a log-likelihood ratio statistic greater than llr. llr has a chi-squared distribution with degrees of freedom `df_model`. * **prsquared** (*float*) – McFadden’s pseudo-R-squared. `1 - (llf / llnull)` | #### Methods | | | | --- | --- | | [`aic`](statsmodels.discrete.discrete_model.binaryresults.aic#statsmodels.discrete.discrete_model.BinaryResults.aic "statsmodels.discrete.discrete_model.BinaryResults.aic")() | | | [`bic`](statsmodels.discrete.discrete_model.binaryresults.bic#statsmodels.discrete.discrete_model.BinaryResults.bic "statsmodels.discrete.discrete_model.BinaryResults.bic")() | | | [`bse`](statsmodels.discrete.discrete_model.binaryresults.bse#statsmodels.discrete.discrete_model.BinaryResults.bse "statsmodels.discrete.discrete_model.BinaryResults.bse")() | | | [`conf_int`](statsmodels.discrete.discrete_model.binaryresults.conf_int#statsmodels.discrete.discrete_model.BinaryResults.conf_int "statsmodels.discrete.discrete_model.BinaryResults.conf_int")([alpha, cols, method]) | Returns the confidence interval of the fitted parameters. | | [`cov_params`](statsmodels.discrete.discrete_model.binaryresults.cov_params#statsmodels.discrete.discrete_model.BinaryResults.cov_params "statsmodels.discrete.discrete_model.BinaryResults.cov_params")([r\_matrix, column, scale, cov\_p, …]) | Returns the variance/covariance matrix. | | [`f_test`](statsmodels.discrete.discrete_model.binaryresults.f_test#statsmodels.discrete.discrete_model.BinaryResults.f_test "statsmodels.discrete.discrete_model.BinaryResults.f_test")(r\_matrix[, cov\_p, scale, invcov]) | Compute the F-test for a joint linear hypothesis. | | [`fittedvalues`](statsmodels.discrete.discrete_model.binaryresults.fittedvalues#statsmodels.discrete.discrete_model.BinaryResults.fittedvalues "statsmodels.discrete.discrete_model.BinaryResults.fittedvalues")() | | | [`get_margeff`](statsmodels.discrete.discrete_model.binaryresults.get_margeff#statsmodels.discrete.discrete_model.BinaryResults.get_margeff "statsmodels.discrete.discrete_model.BinaryResults.get_margeff")([at, method, atexog, dummy, count]) | Get marginal effects of the fitted model. | | [`initialize`](statsmodels.discrete.discrete_model.binaryresults.initialize#statsmodels.discrete.discrete_model.BinaryResults.initialize "statsmodels.discrete.discrete_model.BinaryResults.initialize")(model, params, \*\*kwd) | | | [`llf`](statsmodels.discrete.discrete_model.binaryresults.llf#statsmodels.discrete.discrete_model.BinaryResults.llf "statsmodels.discrete.discrete_model.BinaryResults.llf")() | | | [`llnull`](statsmodels.discrete.discrete_model.binaryresults.llnull#statsmodels.discrete.discrete_model.BinaryResults.llnull "statsmodels.discrete.discrete_model.BinaryResults.llnull")() | | | [`llr`](statsmodels.discrete.discrete_model.binaryresults.llr#statsmodels.discrete.discrete_model.BinaryResults.llr "statsmodels.discrete.discrete_model.BinaryResults.llr")() | | | [`llr_pvalue`](statsmodels.discrete.discrete_model.binaryresults.llr_pvalue#statsmodels.discrete.discrete_model.BinaryResults.llr_pvalue "statsmodels.discrete.discrete_model.BinaryResults.llr_pvalue")() | | | [`load`](statsmodels.discrete.discrete_model.binaryresults.load#statsmodels.discrete.discrete_model.BinaryResults.load "statsmodels.discrete.discrete_model.BinaryResults.load")(fname) | load a pickle, (class method) | | [`normalized_cov_params`](statsmodels.discrete.discrete_model.binaryresults.normalized_cov_params#statsmodels.discrete.discrete_model.BinaryResults.normalized_cov_params "statsmodels.discrete.discrete_model.BinaryResults.normalized_cov_params")() | | | [`pred_table`](statsmodels.discrete.discrete_model.binaryresults.pred_table#statsmodels.discrete.discrete_model.BinaryResults.pred_table "statsmodels.discrete.discrete_model.BinaryResults.pred_table")([threshold]) | Prediction table | | [`predict`](statsmodels.discrete.discrete_model.binaryresults.predict#statsmodels.discrete.discrete_model.BinaryResults.predict "statsmodels.discrete.discrete_model.BinaryResults.predict")([exog, transform]) | Call self.model.predict with self.params as the first argument. | | [`prsquared`](statsmodels.discrete.discrete_model.binaryresults.prsquared#statsmodels.discrete.discrete_model.BinaryResults.prsquared "statsmodels.discrete.discrete_model.BinaryResults.prsquared")() | | | [`pvalues`](statsmodels.discrete.discrete_model.binaryresults.pvalues#statsmodels.discrete.discrete_model.BinaryResults.pvalues "statsmodels.discrete.discrete_model.BinaryResults.pvalues")() | | | [`remove_data`](statsmodels.discrete.discrete_model.binaryresults.remove_data#statsmodels.discrete.discrete_model.BinaryResults.remove_data "statsmodels.discrete.discrete_model.BinaryResults.remove_data")() | remove data arrays, all nobs arrays from result and model | | [`resid_dev`](statsmodels.discrete.discrete_model.binaryresults.resid_dev#statsmodels.discrete.discrete_model.BinaryResults.resid_dev "statsmodels.discrete.discrete_model.BinaryResults.resid_dev")() | Deviance residuals | | [`resid_pearson`](statsmodels.discrete.discrete_model.binaryresults.resid_pearson#statsmodels.discrete.discrete_model.BinaryResults.resid_pearson "statsmodels.discrete.discrete_model.BinaryResults.resid_pearson")() | Pearson residuals | | [`resid_response`](statsmodels.discrete.discrete_model.binaryresults.resid_response#statsmodels.discrete.discrete_model.BinaryResults.resid_response "statsmodels.discrete.discrete_model.BinaryResults.resid_response")() | The response residuals | | [`save`](statsmodels.discrete.discrete_model.binaryresults.save#statsmodels.discrete.discrete_model.BinaryResults.save "statsmodels.discrete.discrete_model.BinaryResults.save")(fname[, remove\_data]) | save a pickle of this instance | | [`set_null_options`](statsmodels.discrete.discrete_model.binaryresults.set_null_options#statsmodels.discrete.discrete_model.BinaryResults.set_null_options "statsmodels.discrete.discrete_model.BinaryResults.set_null_options")([llnull, attach\_results]) | set fit options for Null (constant-only) model | | [`summary`](statsmodels.discrete.discrete_model.binaryresults.summary#statsmodels.discrete.discrete_model.BinaryResults.summary "statsmodels.discrete.discrete_model.BinaryResults.summary")([yname, xname, title, alpha, yname\_list]) | Summarize the Regression Results | | [`summary2`](statsmodels.discrete.discrete_model.binaryresults.summary2#statsmodels.discrete.discrete_model.BinaryResults.summary2 "statsmodels.discrete.discrete_model.BinaryResults.summary2")([yname, xname, title, alpha, …]) | Experimental function to summarize regression results | | [`t_test`](statsmodels.discrete.discrete_model.binaryresults.t_test#statsmodels.discrete.discrete_model.BinaryResults.t_test "statsmodels.discrete.discrete_model.BinaryResults.t_test")(r\_matrix[, cov\_p, scale, use\_t]) | Compute a t-test for a each linear hypothesis of the form Rb = q | | [`t_test_pairwise`](statsmodels.discrete.discrete_model.binaryresults.t_test_pairwise#statsmodels.discrete.discrete_model.BinaryResults.t_test_pairwise "statsmodels.discrete.discrete_model.BinaryResults.t_test_pairwise")(term\_name[, method, alpha, …]) | perform pairwise t\_test with multiple testing corrected p-values | | [`tvalues`](statsmodels.discrete.discrete_model.binaryresults.tvalues#statsmodels.discrete.discrete_model.BinaryResults.tvalues "statsmodels.discrete.discrete_model.BinaryResults.tvalues")() | Return the t-statistic for a given parameter estimate. | | [`wald_test`](statsmodels.discrete.discrete_model.binaryresults.wald_test#statsmodels.discrete.discrete_model.BinaryResults.wald_test "statsmodels.discrete.discrete_model.BinaryResults.wald_test")(r\_matrix[, cov\_p, scale, invcov, …]) | Compute a Wald-test for a joint linear hypothesis. | | [`wald_test_terms`](statsmodels.discrete.discrete_model.binaryresults.wald_test_terms#statsmodels.discrete.discrete_model.BinaryResults.wald_test_terms "statsmodels.discrete.discrete_model.BinaryResults.wald_test_terms")([skip\_single, …]) | Compute a sequence of Wald tests for terms over multiple columns | #### Attributes | | | | --- | --- | | `use_t` | |
programming_docs
statsmodels statsmodels.stats.weightstats.CompareMeans.std_meandiff_separatevar statsmodels.stats.weightstats.CompareMeans.std\_meandiff\_separatevar ===================================================================== `CompareMeans.std_meandiff_separatevar()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/weightstats.html#CompareMeans.std_meandiff_separatevar) statsmodels statsmodels.robust.norms.RobustNorm.weights statsmodels.robust.norms.RobustNorm.weights =========================================== `RobustNorm.weights(z)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/norms.html#RobustNorm.weights) Returns the value of psi(z) / z Abstract method: psi(z) / z statsmodels statsmodels.tsa.statespace.kalman_filter.KalmanFilter.simulate statsmodels.tsa.statespace.kalman\_filter.KalmanFilter.simulate =============================================================== `KalmanFilter.simulate(nsimulations, measurement_shocks=None, state_shocks=None, initial_state=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/kalman_filter.html#KalmanFilter.simulate) Simulate a new time series following the state space model | Parameters: | * **nsimulations** (*int*) – The number of observations to simulate. If the model is time-invariant this can be any number. If the model is time-varying, then this number must be less than or equal to the number * **measurement\_shocks** (*array\_like**,* *optional*) – If specified, these are the shocks to the measurement equation, \(\varepsilon\_t\). If unspecified, these are automatically generated using a pseudo-random number generator. If specified, must be shaped `nsimulations` x `k_endog`, where `k_endog` is the same as in the state space model. * **state\_shocks** (*array\_like**,* *optional*) – If specified, these are the shocks to the state equation, \(\eta\_t\). If unspecified, these are automatically generated using a pseudo-random number generator. If specified, must be shaped `nsimulations` x `k_posdef` where `k_posdef` is the same as in the state space model. * **initial\_state** (*array\_like**,* *optional*) – If specified, this is the state vector at time zero, which should be shaped (`k_states` x 1), where `k_states` is the same as in the state space model. If unspecified, but the model has been initialized, then that initialization is used. If unspecified and the model has not been initialized, then a vector of zeros is used. Note that this is not included in the returned `simulated_states` array. | | Returns: | * **simulated\_obs** (*array*) – An (nsimulations x k\_endog) array of simulated observations. * **simulated\_states** (*array*) – An (nsimulations x k\_states) array of simulated states. | statsmodels statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.loglikeobs statsmodels.discrete.count\_model.ZeroInflatedGeneralizedPoisson.loglikeobs =========================================================================== `ZeroInflatedGeneralizedPoisson.loglikeobs(params)` Loglikelihood for observations of Generic Zero Inflated model | Parameters: | **params** (*array-like*) – The parameters of the model. | | Returns: | **loglike** – The log likelihood for each observation of the model evaluated at `params`. See Notes | | Return type: | ndarray | #### Notes \[\ln L=\ln(w\_{i}+(1-w\_{i})\*P\_{main\\_model})+ \ln(1-w\_{i})+L\_{main\\_model} where P - pdf of main model, L - loglike function of main model.\] for observations \(i=1,...,n\) statsmodels statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression.initial_probabilities statsmodels.tsa.regime\_switching.markov\_autoregression.MarkovAutoregression.initial\_probabilities ==================================================================================================== `MarkovAutoregression.initial_probabilities(params, regime_transition=None)` Retrieve initial probabilities statsmodels statsmodels.miscmodels.count.PoissonGMLE.nloglikeobs statsmodels.miscmodels.count.PoissonGMLE.nloglikeobs ==================================================== `PoissonGMLE.nloglikeobs(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/miscmodels/count.html#PoissonGMLE.nloglikeobs) Loglikelihood of Poisson model | Parameters: | **params** (*array-like*) – The parameters of the model. | | Returns: | | | Return type: | The log likelihood of the model evaluated at `params` | #### Notes \[\ln L=\sum\_{i=1}^{n}\left[-\lambda\_{i}+y\_{i}x\_{i}^{\prime}\beta-\ln y\_{i}!\right]\] statsmodels statsmodels.sandbox.regression.gmm.IVGMMResults.get_bse statsmodels.sandbox.regression.gmm.IVGMMResults.get\_bse ======================================================== `IVGMMResults.get_bse(**kwds)` standard error of the parameter estimates with options | Parameters: | **kwds** (*optional keywords*) – options for calculating cov\_params | | Returns: | **bse** – estimated standard error of parameter estimates | | Return type: | ndarray | statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.remove_data statsmodels.tsa.statespace.dynamic\_factor.DynamicFactorResults.remove\_data ============================================================================ `DynamicFactorResults.remove_data()` remove data arrays, all nobs arrays from result and model This reduces the size of the instance, so it can be pickled with less memory. Currently tested for use with predict from an unpickled results and model instance. Warning Since data and some intermediate results have been removed calculating new statistics that require them will raise exceptions. The exception will occur the first time an attribute is accessed that has been set to None. Not fully tested for time series models, tsa, and might delete too much for prediction or not all that would be possible. The lists of arrays to delete are maintained as attributes of the result and model instance, except for cached values. These lists could be changed before calling remove\_data. The attributes to remove are named in: `model._data_attr : arrays attached to both the model instance` and the results instance with the same attribute name. `result.data_in_cache : arrays that may exist as values in` result.\_cache (TODO : should privatize name) `result._data_attr_model : arrays attached to the model` instance but not to the results instance statsmodels statsmodels.robust.robust_linear_model.RLM.from_formula statsmodels.robust.robust\_linear\_model.RLM.from\_formula ========================================================== `classmethod RLM.from_formula(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** (*extra arguments*) – These are passed to the model * **kwargs** (*extra keyword arguments*) – These are passed to the model with one exception. The `eval_env` keyword is passed to patsy. It can be either a [`patsy.EvalEnvironment`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.EvalEnvironment "(in patsy v0.5.0+dev)") 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** | | Return type: | 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 statsmodels.genmod.generalized_linear_model.GLM.hessian statsmodels.genmod.generalized\_linear\_model.GLM.hessian ========================================================= `GLM.hessian(params, scale=None, observed=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_linear_model.html#GLM.hessian) Hessian, second derivative of loglikelihood function | Parameters: | * **params** (*ndarray*) – parameter at which Hessian is evaluated * **scale** (*None* *or* *float*) – If scale is None, then the default scale will be calculated. Default scale is defined by `self.scaletype` and set in fit. If scale is not None, then it is used as a fixed scale. * **observed** (*bool*) – If True, then the observed Hessian is returned (default). If false then the expected information matrix is returned. | | Returns: | **hessian** – Hessian, i.e. observed information, or expected information matrix. | | Return type: | ndarray | statsmodels statsmodels.genmod.generalized_estimating_equations.GEEResults.resid_deviance statsmodels.genmod.generalized\_estimating\_equations.GEEResults.resid\_deviance ================================================================================ `GEEResults.resid_deviance()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_estimating_equations.html#GEEResults.resid_deviance) statsmodels statsmodels.discrete.discrete_model.CountResults.wald_test statsmodels.discrete.discrete\_model.CountResults.wald\_test ============================================================ `CountResults.wald_test(r_matrix, cov_p=None, scale=1.0, invcov=None, use_f=None)` Compute a Wald-test for a joint linear hypothesis. | Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) – + array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length p row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – Default is 1.0 for no scaling. * **invcov** (*array-like**,* *optional*) – A q x q array to specify an inverse covariance matrix based on a restrictions matrix. * **use\_f** (*bool*) – If True, then the F-distribution is used. If False, then the asymptotic distribution, chisquare is used. If use\_f is None, then the F distribution is used if the model specifies that use\_t is True. The test statistic is proportionally adjusted for the distribution by the number of constraints in the hypothesis. | | Returns: | **res** – The results for the test are attributes of this results instance. | | Return type: | ContrastResults instance | See also [`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`f_test`](statsmodels.discrete.discrete_model.countresults.f_test#statsmodels.discrete.discrete_model.CountResults.f_test "statsmodels.discrete.discrete_model.CountResults.f_test"), [`t_test`](statsmodels.discrete.discrete_model.countresults.t_test#statsmodels.discrete.discrete_model.CountResults.t_test "statsmodels.discrete.discrete_model.CountResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") #### Notes The matrix `r_matrix` is assumed to be non-singular. More precisely, r\_matrix (pX pX.T) r\_matrix.T is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full. statsmodels statsmodels.regression.linear_model.OLSResults.centered_tss statsmodels.regression.linear\_model.OLSResults.centered\_tss ============================================================= `OLSResults.centered_tss()` statsmodels statsmodels.discrete.discrete_model.GeneralizedPoissonResults.wald_test statsmodels.discrete.discrete\_model.GeneralizedPoissonResults.wald\_test ========================================================================= `GeneralizedPoissonResults.wald_test(r_matrix, cov_p=None, scale=1.0, invcov=None, use_f=None)` Compute a Wald-test for a joint linear hypothesis. | Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) – + array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length p row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – Default is 1.0 for no scaling. * **invcov** (*array-like**,* *optional*) – A q x q array to specify an inverse covariance matrix based on a restrictions matrix. * **use\_f** (*bool*) – If True, then the F-distribution is used. If False, then the asymptotic distribution, chisquare is used. If use\_f is None, then the F distribution is used if the model specifies that use\_t is True. The test statistic is proportionally adjusted for the distribution by the number of constraints in the hypothesis. | | Returns: | **res** – The results for the test are attributes of this results instance. | | Return type: | ContrastResults instance | See also [`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`f_test`](statsmodels.discrete.discrete_model.generalizedpoissonresults.f_test#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.f_test "statsmodels.discrete.discrete_model.GeneralizedPoissonResults.f_test"), [`t_test`](statsmodels.discrete.discrete_model.generalizedpoissonresults.t_test#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.t_test "statsmodels.discrete.discrete_model.GeneralizedPoissonResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") #### Notes The matrix `r_matrix` is assumed to be non-singular. More precisely, r\_matrix (pX pX.T) r\_matrix.T is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full. statsmodels statsmodels.graphics.functional.fboxplot statsmodels.graphics.functional.fboxplot ======================================== `statsmodels.graphics.functional.fboxplot(data, xdata=None, labels=None, depth=None, method='MBD', wfactor=1.5, ax=None, plot_opts={})` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/graphics/functional.html#fboxplot) Plot functional boxplot. A functional boxplot is the analog of a boxplot for functional data. Functional data is any type of data that varies over a continuum, i.e. curves, probabillity distributions, seasonal data, etc. The data is first ordered, the order statistic used here is `banddepth`. Plotted are then the median curve, the envelope of the 50% central region, the maximum non-outlying envelope and the outlier curves. | Parameters: | * **data** (*sequence of ndarrays* *or* *2-D ndarray*) – The vectors of functions to create a functional boxplot from. If a sequence of 1-D arrays, these should all be the same size. The first axis is the function index, the second axis the one along which the function is defined. So `data[0, :]` is the first functional curve. * **xdata** (*ndarray**,* *optional*) – The independent variable for the data. If not given, it is assumed to be an array of integers 0..N-1 with N the length of the vectors in `data`. * **labels** (*sequence of scalar* *or* *str**,* *optional*) – The labels or identifiers of the curves in `data`. If given, outliers are labeled in the plot. * **depth** (*ndarray**,* *optional*) – A 1-D array of band depths for `data`, or equivalent order statistic. If not given, it will be calculated through `banddepth`. * **method** (*{'MBD'**,* *'BD2'}**,* *optional*) – The method to use to calculate the band depth. Default is ‘MBD’. * **wfactor** (*float**,* *optional*) – Factor by which the central 50% region is multiplied to find the outer region (analog of “whiskers” of a classical boxplot). * **ax** (*Matplotlib AxesSubplot instance**,* *optional*) – If given, this subplot is used to plot in instead of a new figure being created. * **plot\_opts** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")*,* *optional*) – A dictionary with plotting options. Any of the following can be provided, if not present in `plot_opts` the defaults will be used: ``` - 'cmap_outliers', a Matplotlib LinearSegmentedColormap instance. - 'c_inner', valid MPL color. Color of the central 50% region - 'c_outer', valid MPL color. Color of the non-outlying region - 'c_median', valid MPL color. Color of the median. - 'lw_outliers', scalar. Linewidth for drawing outlier curves. - 'lw_median', scalar. Linewidth for drawing the median curve. - 'draw_nonout', bool. If True, also draw non-outlying curves. ``` | | Returns: | * **fig** (*Matplotlib figure instance*) – If `ax` is None, the created figure. Otherwise the figure to which `ax` is connected. * **depth** (*ndarray*) – 1-D array containing the calculated band depths of the curves. * **ix\_depth** (*ndarray*) – 1-D array of indices needed to order curves (or `depth`) from most to least central curve. * **ix\_outliers** (*ndarray*) – 1-D array of indices of outlying curves in `data`. | See also [`banddepth`](statsmodels.graphics.functional.banddepth#statsmodels.graphics.functional.banddepth "statsmodels.graphics.functional.banddepth"), [`rainbowplot`](statsmodels.graphics.functional.rainbowplot#statsmodels.graphics.functional.rainbowplot "statsmodels.graphics.functional.rainbowplot") #### Notes The median curve is the curve with the highest band depth. Outliers are defined as curves that fall outside the band created by multiplying the central region by `wfactor`. Note that the range over which they fall outside this band doesn’t matter, a single data point outside the band is enough. If the data is noisy, smoothing may therefore be required. The non-outlying region is defined as the band made up of all the non-outlying curves. #### References [1] Y. Sun and M.G. Genton, “Functional Boxplots”, Journal of Computational and Graphical Statistics, vol. 20, pp. 1-19, 2011. [2] R.J. Hyndman and H.L. Shang, “Rainbow Plots, Bagplots, and Boxplots for Functional Data”, vol. 19, pp. 29-45, 2010. #### Examples Load the El Nino dataset. Consists of 60 years worth of Pacific Ocean sea surface temperature data. ``` >>> import matplotlib.pyplot as plt >>> import statsmodels.api as sm >>> data = sm.datasets.elnino.load() ``` Create a functional boxplot. We see that the years 1982-83 and 1997-98 are outliers; these are the years where El Nino (a climate pattern characterized by warming up of the sea surface and higher air pressures) occurred with unusual intensity. ``` >>> fig = plt.figure() >>> ax = fig.add_subplot(111) >>> res = sm.graphics.fboxplot(data.raw_data[:, 1:], wfactor=2.58, ... labels=data.raw_data[:, 0].astype(int), ... ax=ax) ``` ``` >>> ax.set_xlabel("Month of the year") >>> ax.set_ylabel("Sea surface temperature (C)") >>> ax.set_xticks(np.arange(13, step=3) - 1) >>> ax.set_xticklabels(["", "Mar", "Jun", "Sep", "Dec"]) >>> ax.set_xlim([-0.2, 11.2]) ``` ``` >>> plt.show() ``` ([Source code](../plots/graphics_functional_fboxplot.py), [png](../plots/graphics_functional_fboxplot.png), [hires.png](../plots/graphics_functional_fboxplot.hires.png), [pdf](../plots/graphics_functional_fboxplot.pdf))
programming_docs
statsmodels statsmodels.sandbox.regression.gmm.LinearIVGMM.gmmobjective statsmodels.sandbox.regression.gmm.LinearIVGMM.gmmobjective =========================================================== `LinearIVGMM.gmmobjective(params, weights)` objective function for GMM minimization | Parameters: | * **params** (*array*) – parameter values at which objective is evaluated * **weights** (*array*) – weighting matrix | | Returns: | **jval** – value of objective function | | Return type: | float | statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.loglikeobs statsmodels.tsa.statespace.dynamic\_factor.DynamicFactor.loglikeobs =================================================================== `DynamicFactor.loglikeobs(params, transformed=True, complex_step=False, **kwargs)` Loglikelihood evaluation | Parameters: | * **params** (*array\_like*) – Array of parameters at which to evaluate the loglikelihood function. * **transformed** (*boolean**,* *optional*) – Whether or not `params` is already transformed. Default is True. * **\*\*kwargs** – Additional keyword arguments to pass to the Kalman filter. See `KalmanFilter.filter` for more details. | #### Notes [[1]](#id2) recommend maximizing the average likelihood to avoid scale issues; this is done automatically by the base Model fit method. #### References | | | | --- | --- | | [[1]](#id1) | Koopman, Siem Jan, Neil Shephard, and Jurgen A. Doornik. 1999. Statistical Algorithms for Models in State Space Using SsfPack 2.2. Econometrics Journal 2 (1): 107-60. doi:10.1111/1368-423X.00023. | See also [`update`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactor.update#statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.update "statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.update") modifies the internal state of the Model to reflect new params statsmodels statsmodels.discrete.discrete_model.MultinomialResults.fittedvalues statsmodels.discrete.discrete\_model.MultinomialResults.fittedvalues ==================================================================== `MultinomialResults.fittedvalues()` statsmodels statsmodels.genmod.generalized_linear_model.GLMResults.predict statsmodels.genmod.generalized\_linear\_model.GLMResults.predict ================================================================ `GLMResults.predict(exog=None, transform=True, *args, **kwargs)` Call self.model.predict with self.params as the first argument. | Parameters: | * **exog** (*array-like**,* *optional*) – The values for which you want to predict. see Notes below. * **transform** (*bool**,* *optional*) – If the model was fit via a formula, do you want to pass exog through the formula. Default is True. E.g., if you fit a model y ~ log(x1) + log(x2), and transform is True, then you can pass a data structure that contains x1 and x2 in their original form. Otherwise, you’d need to log the data first. * **kwargs** (*args**,*) – Some models can take additional arguments or keywords, see the predict method of the model for the details. | | Returns: | **prediction** – See self.model.predict | | Return type: | ndarray, [pandas.Series](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html#pandas.Series "(in pandas v0.22.0)") or [pandas.DataFrame](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html#pandas.DataFrame "(in pandas v0.22.0)") | #### Notes The types of exog that are supported depends on whether a formula was used in the specification of the model. If a formula was used, then exog is processed in the same way as the original data. This transformation needs to have key access to the same variable names, and can be a pandas DataFrame or a dict like object. If no formula was used, then the provided exog needs to have the same number of columns as the original exog in the model. No transformation of the data is performed except converting it to a numpy array. Row indices as in pandas data frames are supported, and added to the returned prediction. statsmodels statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.f_test statsmodels.discrete.count\_model.ZeroInflatedGeneralizedPoissonResults.f\_test =============================================================================== `ZeroInflatedGeneralizedPoissonResults.f_test(r_matrix, cov_p=None, scale=1.0, invcov=None)` Compute the F-test for a joint linear hypothesis. This is a special case of `wald_test` that always uses the F distribution. | Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) – + array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length k row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – Default is 1.0 for no scaling. * **invcov** (*array-like**,* *optional*) – A q x q array to specify an inverse covariance matrix based on a restrictions matrix. | | Returns: | **res** – The results for the test are attributes of this results instance. | | Return type: | ContrastResults instance | #### Examples ``` >>> import numpy as np >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> A = np.identity(len(results.params)) >>> A = A[1:,:] ``` This tests that each coefficient is jointly statistically significantly different from zero. ``` >>> print(results.f_test(A)) <F test: F=array([[ 330.28533923]]), p=4.984030528700946e-10, df_denom=9, df_num=6> ``` Compare this to ``` >>> results.fvalue 330.2853392346658 >>> results.f_pvalue 4.98403096572e-10 ``` ``` >>> B = np.array(([0,0,1,-1,0,0,0],[0,0,0,0,0,1,-1])) ``` This tests that the coefficient on the 2nd and 3rd regressors are equal and jointly that the coefficient on the 5th and 6th regressors are equal. ``` >>> print(results.f_test(B)) <F test: F=array([[ 9.74046187]]), p=0.005605288531708235, df_denom=9, df_num=2> ``` Alternatively, you can specify the hypothesis tests using a string ``` >>> from statsmodels.datasets import longley >>> from statsmodels.formula.api import ols >>> dta = longley.load_pandas().data >>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' >>> results = ols(formula, dta).fit() >>> hypotheses = '(GNPDEFL = GNP), (UNEMP = 2), (YEAR/1829 = 1)' >>> f_test = results.f_test(hypotheses) >>> print(f_test) <F test: F=array([[ 144.17976065]]), p=6.322026217355609e-08, df_denom=9, df_num=3> ``` See also [`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`wald_test`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoissonresults.wald_test#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.wald_test "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.wald_test"), [`t_test`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoissonresults.t_test#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.t_test "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") #### Notes The matrix `r_matrix` is assumed to be non-singular. More precisely, r\_matrix (pX pX.T) r\_matrix.T is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full. statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.from_formula statsmodels.tsa.statespace.dynamic\_factor.DynamicFactor.from\_formula ====================================================================== `classmethod DynamicFactor.from_formula(formula, data, subset=None)` Not implemented for state space models statsmodels statsmodels.tsa.vector_ar.irf.IRAnalysis.lr_effect_cov statsmodels.tsa.vector\_ar.irf.IRAnalysis.lr\_effect\_cov ========================================================= `IRAnalysis.lr_effect_cov(orth=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/irf.html#IRAnalysis.lr_effect_cov) statsmodels statsmodels.regression.quantile_regression.QuantReg.loglike statsmodels.regression.quantile\_regression.QuantReg.loglike ============================================================ `QuantReg.loglike(params)` Log-likelihood of model. statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.t_test_pairwise statsmodels.tsa.statespace.dynamic\_factor.DynamicFactorResults.t\_test\_pairwise ================================================================================= `DynamicFactorResults.t_test_pairwise(term_name, method='hs', alpha=0.05, factor_labels=None)` perform pairwise t\_test with multiple testing corrected p-values This uses the formula design\_info encoding contrast matrix and should work for all encodings of a main effect. | Parameters: | * **result** (*result instance*) – The results of an estimated model with a categorical main effect. * **term\_name** (*str*) – name of the term for which pairwise comparisons are computed. Term names for categorical effects are created by patsy and correspond to the main part of the exog names. * **method** (*str* *or* *list of strings*) – multiple testing p-value correction, default is ‘hs’, see stats.multipletesting * **alpha** (*float*) – significance level for multiple testing reject decision. * **factor\_labels** (*None**,* *list of str*) – Labels for the factor levels used for pairwise labels. If not provided, then the labels from the formula design\_info are used. | | Returns: | **results** – The results are stored as attributes, the main attributes are the following two. Other attributes are added for debugging purposes or as background information.* result\_frame : pandas DataFrame with t\_test results and multiple testing corrected p-values. * contrasts : matrix of constraints of the null hypothesis in the t\_test. | | Return type: | instance of a simple Results class | #### Notes Status: experimental. Currently only checked for treatment coding with and without specified reference level. Currently there are no multiple testing corrected confidence intervals available. #### Examples ``` >>> res = ols("np.log(Days+1) ~ C(Weight) + C(Duration)", data).fit() >>> pw = res.t_test_pairwise("C(Weight)") >>> pw.result_frame coef std err t P>|t| Conf. Int. Low 2-1 0.632315 0.230003 2.749157 8.028083e-03 0.171563 3-1 1.302555 0.230003 5.663201 5.331513e-07 0.841803 3-2 0.670240 0.230003 2.914044 5.119126e-03 0.209488 Conf. Int. Upp. pvalue-hs reject-hs 2-1 1.093067 0.010212 True 3-1 1.763307 0.000002 True 3-2 1.130992 0.010212 True ``` statsmodels statsmodels.genmod.generalized_estimating_equations.GEE.cluster_list statsmodels.genmod.generalized\_estimating\_equations.GEE.cluster\_list ======================================================================= `GEE.cluster_list(array)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_estimating_equations.html#GEE.cluster_list) Returns `array` split into subarrays corresponding to the cluster structure. statsmodels statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialResults.initialize statsmodels.discrete.count\_model.ZeroInflatedNegativeBinomialResults.initialize ================================================================================ `ZeroInflatedNegativeBinomialResults.initialize(model, params, **kwd)` statsmodels statsmodels.discrete.discrete_model.GeneralizedPoissonResults.load statsmodels.discrete.discrete\_model.GeneralizedPoissonResults.load =================================================================== `classmethod GeneralizedPoissonResults.load(fname)` load a pickle, (class method) | Parameters: | **fname** (*string* *or* *filehandle*) – fname can be a string to a file path or filename, or a filehandle. | | Returns: | | | Return type: | unpickled instance | statsmodels statsmodels.sandbox.distributions.transformed.Transf_gen.logsf statsmodels.sandbox.distributions.transformed.Transf\_gen.logsf =============================================================== `Transf_gen.logsf(x, *args, **kwds)` Log of the survival function of the given RV. Returns the log of the “survival function,” defined as (1 - `cdf`), evaluated at `x`. | Parameters: | * **x** (*array\_like*) – quantiles * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **logsf** – Log of the survival function evaluated at `x`. | | Return type: | ndarray | statsmodels statsmodels.genmod.families.family.Tweedie.deviance statsmodels.genmod.families.family.Tweedie.deviance =================================================== `Tweedie.deviance(endog, mu, var_weights=1.0, freq_weights=1.0, scale=1.0)` The deviance function evaluated at (endog, mu, var\_weights, freq\_weights, scale) for the distribution. Deviance is usually defined as twice the loglikelihood ratio. | Parameters: | * **endog** (*array-like*) – The endogenous response variable * **mu** (*array-like*) – The inverse of the link function at the linear predicted values. * **var\_weights** (*array-like*) – 1d array of variance (analytic) weights. The default is 1. * **freq\_weights** (*array-like*) – 1d array of frequency weights. The default is 1. * **scale** (*float**,* *optional*) – An optional scale argument. The default is 1. | | Returns: | **Deviance** – The value of deviance function defined below. | | Return type: | array | #### Notes Deviance is defined \[D = 2\sum\_i (freq\\_weights\_i \* var\\_weights \* (llf(endog\_i, endog\_i) - llf(endog\_i, \mu\_i)))\] where y is the endogenous variable. The deviance functions are analytically defined for each family. Internally, we calculate deviance as: \[D = \sum\_i freq\\_weights\_i \* var\\_weights \* resid\\_dev\_i / scale\] statsmodels statsmodels.genmod.generalized_linear_model.GLMResults.resid_anscombe_scaled statsmodels.genmod.generalized\_linear\_model.GLMResults.resid\_anscombe\_scaled ================================================================================ `GLMResults.resid_anscombe_scaled()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_linear_model.html#GLMResults.resid_anscombe_scaled) statsmodels statsmodels.graphics.mosaicplot.mosaic statsmodels.graphics.mosaicplot.mosaic ====================================== `statsmodels.graphics.mosaicplot.mosaic(data, index=None, ax=None, horizontal=True, gap=0.005, properties=<function <lambda>>, labelizer=None, title='', statistic=False, axes_label=True, label_rotation=0.0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/graphics/mosaicplot.html#mosaic) Create a mosaic plot from a contingency table. It allows to visualize multivariate categorical data in a rigorous and informative way. | Parameters: | * **data** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")*,* [pandas.Series](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html#pandas.Series "(in pandas v0.22.0)")*,* *np.ndarray**,* [pandas.DataFrame](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html#pandas.DataFrame "(in pandas v0.22.0)")) – The contingency table that contains the data. Each category should contain a non-negative number with a tuple as index. It expects that all the combination of keys to be representes; if that is not true, will automatically consider the missing values as 0. The order of the keys will be the same as the one of insertion. If a dict of a Series (or any other dict like object) is used, it will take the keys as labels. If a np.ndarray is provided, it will generate a simple numerical labels. * **index** (*list**,* *optional*) – Gives the preferred order for the category ordering. If not specified will default to the given order. It doesn’t support named indexes for hierarchical Series. If a DataFrame is provided, it expects a list with the name of the columns. * **ax** (*matplotlib.Axes**,* *optional*) – The graph where display the mosaic. If not given, will create a new figure * **horizontal** (*bool**,* *optional* *(**default True**)*) – The starting direction of the split (by default along the horizontal axis) * **gap** (*float* *or* *array of floats*) – The list of gaps to be applied on each subdivision. If the lenght of the given array is less of the number of subcategories (or if it’s a single number) it will extend it with exponentially decreasing gaps * **labelizer** (*function* *(**key**)* *-> string**,* *optional*) – A function that generate the text to display at the center of each tile base on the key of that tile * **properties** (*function* *(**key**)* *-> dict**,* *optional*) – A function that for each tile in the mosaic take the key of the tile and returns the dictionary of properties of the generated Rectangle, like color, hatch or similar. A default properties set will be provided fot the keys whose color has not been defined, and will use color variation to help visually separates the various categories. It should return None to indicate that it should use the default property for the tile. A dictionary of the properties for each key can be passed, and it will be internally converted to the correct function * **statistic** (*bool**,* *optional* *(**default False**)*) – if true will use a crude statistical model to give colors to the plot. If the tile has a containt that is more than 2 standard deviation from the expected value under independence hipotesys, it will go from green to red (for positive deviations, blue otherwise) and will acquire an hatching when crosses the 3 sigma. * **title** (*string**,* *optional*) – The title of the axis * **axes\_label** (*boolean**,* *optional*) – Show the name of each value of each category on the axis (default) or hide them. * **label\_rotation** (*float* *or* *list of float*) – the rotation of the axis label (if present). If a list is given each axis can have a different rotation | | Returns: | * **fig** (*matplotlib.Figure*) – The generate figure * **rects** (*dict*) – A dictionary that has the same keys of the original dataset, that holds a reference to the coordinates of the tile and the Rectangle that represent it | See also `A` Michael Friendly, York University, Psychology Department Journal of Computational and Graphical Statistics, 2001 `Mosaic` Michael Friendly, York University, Psychology Department Proceedings of the Statistical Graphics Section, 1992, 61-68. `Mosaic` Michael Friendly, York University, Psychology Department Journal of the american statistical association March 1994, Vol. 89, No. 425, Theory and Methods #### Examples The most simple use case is to take a dictionary and plot the result ``` >>> data = {'a': 10, 'b': 15, 'c': 16} >>> mosaic(data, title='basic dictionary') >>> pylab.show() ``` A more useful example is given by a dictionary with multiple indices. In this case we use a wider gap to a better visual separation of the resulting plot ``` >>> data = {('a', 'b'): 1, ('a', 'c'): 2, ('d', 'b'): 3, ('d', 'c'): 4} >>> mosaic(data, gap=0.05, title='complete dictionary') >>> pylab.show() ``` The same data can be given as a simple or hierarchical indexed Series ``` >>> rand = np.random.random >>> from itertools import product >>> >>> tuples = list(product(['bar', 'baz', 'foo', 'qux'], ['one', 'two'])) >>> index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second']) >>> data = pd.Series(rand(8), index=index) >>> mosaic(data, title='hierarchical index series') >>> pylab.show() ``` The third accepted data structureis the np array, for which a very simple index will be created. ``` >>> rand = np.random.random >>> data = 1+rand((2,2)) >>> mosaic(data, title='random non-labeled array') >>> pylab.show() ``` If you need to modify the labeling and the coloring you can give a function tocreate the labels and one with the graphical properties starting from the key tuple ``` >>> data = {'a': 10, 'b': 15, 'c': 16} >>> props = lambda key: {'color': 'r' if 'a' in key else 'gray'} >>> labelizer = lambda k: {('a',): 'first', ('b',): 'second', ('c',): 'third'}[k] >>> mosaic(data, title='colored dictionary', properties=props, labelizer=labelizer) >>> pylab.show() ``` Using a DataFrame as source, specifying the name of the columns of interest >>> gender = [‘male’, ‘male’, ‘male’, ‘female’, ‘female’, ‘female’] >>> pet = [‘cat’, ‘dog’, ‘dog’, ‘cat’, ‘dog’, ‘cat’] >>> data = pandas.DataFrame({‘gender’: gender, ‘pet’: pet}) >>> mosaic(data, [‘pet’, ‘gender’]) >>> pylab.show()
programming_docs
statsmodels statsmodels.tsa.ar_model.ARResults.fpe statsmodels.tsa.ar\_model.ARResults.fpe ======================================= `ARResults.fpe()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/ar_model.html#ARResults.fpe) statsmodels statsmodels.miscmodels.count.PoissonGMLE.hessian statsmodels.miscmodels.count.PoissonGMLE.hessian ================================================ `PoissonGMLE.hessian(params)` Hessian of log-likelihood evaluated at params statsmodels statsmodels.tsa.statespace.varmax.VARMAXResults.pvalues statsmodels.tsa.statespace.varmax.VARMAXResults.pvalues ======================================================= `VARMAXResults.pvalues()` (array) The p-values associated with the z-statistics of the coefficients. Note that the coefficients are assumed to have a Normal distribution. statsmodels statsmodels.tsa.varma_process.VarmaPoly.stacksquare statsmodels.tsa.varma\_process.VarmaPoly.stacksquare ==================================================== `VarmaPoly.stacksquare(a=None, name='ar', orientation='vertical')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/varma_process.html#VarmaPoly.stacksquare) stack lagpolynomial vertically in 2d square array with eye statsmodels statsmodels.regression.linear_model.OLSResults.conf_int_el statsmodels.regression.linear\_model.OLSResults.conf\_int\_el ============================================================= `OLSResults.conf_int_el(param_num, sig=0.05, upper_bound=None, lower_bound=None, method='nm', stochastic_exog=1)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#OLSResults.conf_int_el) Computes the confidence interval for the parameter given by param\_num using Empirical Likelihood | Parameters: | * **param\_num** (*float*) – The parameter for which the confidence interval is desired * **sig** (*float*) – The significance level. Default is .05 * **upper\_bound** (*float*) – The maximum value the upper limit can be. Default is the 99.9% confidence value under OLS assumptions. * **lower\_bound** (*float*) – The minimum value the lower limit can be. Default is the 99.9% confidence value under OLS assumptions. * **method** (*string*) – Can either be ‘nm’ for Nelder-Mead or ‘powell’ for Powell. The optimization method that optimizes over nuisance parameters. Default is ‘nm’ | | Returns: | **ci** – The confidence interval | | Return type: | tuple | See also [`el_test`](statsmodels.regression.linear_model.olsresults.el_test#statsmodels.regression.linear_model.OLSResults.el_test "statsmodels.regression.linear_model.OLSResults.el_test") #### Notes This function uses brentq to find the value of beta where test\_beta([beta], param\_num)[1] is equal to the critical value. The function returns the results of each iteration of brentq at each value of beta. The current function value of the last printed optimization should be the critical value at the desired significance level. For alpha=.05, the value is 3.841459. To ensure optimization terminated successfully, it is suggested to do el\_test([lower\_limit], [param\_num]) If the optimization does not terminate successfully, consider switching optimization algorithms. If optimization is still not successful, try changing the values of start\_int\_params. If the current function value repeatedly jumps from a number between 0 and the critical value and a very large number (>50), the starting parameters of the interior minimization need to be changed. statsmodels statsmodels.genmod.families.links.NegativeBinomial.deriv statsmodels.genmod.families.links.NegativeBinomial.deriv ======================================================== `NegativeBinomial.deriv(p)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/links.html#NegativeBinomial.deriv) Derivative of the negative binomial transform | Parameters: | **p** (*array-like*) – Mean parameters | | Returns: | **g’(p)** – The derivative of the negative binomial transform link function | | Return type: | array | #### Notes g’(x) = 1/(x+alpha\*x^2) statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.HC0_se statsmodels.sandbox.regression.gmm.IVRegressionResults.HC0\_se ============================================================== `IVRegressionResults.HC0_se()` See statsmodels.RegressionResults statsmodels statsmodels.stats.contingency_tables.Table2x2.local_log_oddsratios statsmodels.stats.contingency\_tables.Table2x2.local\_log\_oddsratios ===================================================================== `Table2x2.local_log_oddsratios()` statsmodels statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialResults.conf_int statsmodels.discrete.count\_model.ZeroInflatedNegativeBinomialResults.conf\_int =============================================================================== `ZeroInflatedNegativeBinomialResults.conf_int(alpha=0.05, cols=None, method='default')` Returns the confidence interval of the fitted parameters. | Parameters: | * **alpha** (*float**,* *optional*) – The significance level for the confidence interval. ie., The default `alpha` = .05 returns a 95% confidence interval. * **cols** (*array-like**,* *optional*) – `cols` specifies which confidence intervals to return * **method** (*string*) – Not Implemented Yet Method to estimate the confidence\_interval. “Default” : uses self.bse which is based on inverse Hessian for MLE “hjjh” : “jac” : “boot-bse” “boot\_quant” “profile” | | Returns: | **conf\_int** – Each row contains [lower, upper] limits of the confidence interval for the corresponding parameter. The first column contains all lower, the second column contains all upper limits. | | Return type: | array | #### Examples ``` >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> results.conf_int() array([[-5496529.48322745, -1467987.78596704], [ -177.02903529, 207.15277984], [ -0.1115811 , 0.03994274], [ -3.12506664, -0.91539297], [ -1.5179487 , -0.54850503], [ -0.56251721, 0.460309 ], [ 798.7875153 , 2859.51541392]]) ``` ``` >>> results.conf_int(cols=(2,3)) array([[-0.1115811 , 0.03994274], [-3.12506664, -0.91539297]]) ``` #### Notes The confidence interval is based on the standard normal distribution. Models wish to use a different distribution should overwrite this method. statsmodels statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson statsmodels.discrete.count\_model.ZeroInflatedGeneralizedPoisson ================================================================ `class statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson(endog, exog, exog_infl=None, offset=None, exposure=None, inflation='logit', p=2, missing='none', **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/count_model.html#ZeroInflatedGeneralizedPoisson) Zero Inflated Generalized Poisson model for count data | Parameters: | * **endog** (*array-like*) – 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 `statsmodels.tools.add_constant`. * **exog\_infl** (*array\_like* *or* *None*) – Explanatory variables for the binary inflation model, i.e. for mixing probability model. If None, then a constant is used. * **offset** (*array\_like*) – Offset is added to the linear prediction with coefficient equal to 1. * **exposure** (*array\_like*) – Log(exposure) is added to the linear prediction with coefficient equal to 1. * **inflation** (*string**,* *'logit'* *or* *'probit'*) – The model for the zero inflation, either Logit (default) or Probit * **p** (*float*) – dispersion power parameter for the GeneralizedPoisson model. p=1 for ZIGP-1 and p=2 for ZIGP-2. Default is p=2 * **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.’ | `endog` *array* – A reference to the endogenous response variable `exog` *array* – A reference to the exogenous design. `exog_infl` *array* – A reference to the zero-inflated exogenous design. `p` *scalar* – P denotes parametrizations for ZIGP regression. #### Methods | | | | --- | --- | | [`cdf`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoisson.cdf#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.cdf "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.cdf")(X) | The cumulative distribution function of the model. | | [`cov_params_func_l1`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoisson.cov_params_func_l1#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.cov_params_func_l1 "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.cov_params_func_l1")(likelihood\_model, xopt, …) | Computes cov\_params on a reduced parameter space corresponding to the nonzero parameters resulting from the l1 regularized fit. | | [`fit`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoisson.fit#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.fit "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.fit")([start\_params, method, maxiter, …]) | Fit the model using maximum likelihood. | | [`fit_regularized`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoisson.fit_regularized#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.fit_regularized "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.fit_regularized")([start\_params, method, …]) | Fit the model using a regularized maximum likelihood. | | [`from_formula`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoisson.from_formula#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.from_formula "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.from_formula")(formula, data[, subset, drop\_cols]) | Create a Model from a formula and dataframe. | | [`hessian`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoisson.hessian#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.hessian "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.hessian")(params) | Generic Zero Inflated model Hessian matrix of the loglikelihood | | [`information`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoisson.information#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.information "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.information")(params) | Fisher information matrix of model | | [`initialize`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoisson.initialize#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.initialize "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.initialize")() | Initialize is called by statsmodels.model.LikelihoodModel.\_\_init\_\_ and should contain any preprocessing that needs to be done for a model. | | [`loglike`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoisson.loglike#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.loglike "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.loglike")(params) | Loglikelihood of Generic Zero Inflated model | | [`loglikeobs`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoisson.loglikeobs#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.loglikeobs "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.loglikeobs")(params) | Loglikelihood for observations of Generic Zero Inflated model | | [`pdf`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoisson.pdf#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.pdf "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.pdf")(X) | The probability density (mass) function of the model. | | [`predict`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoisson.predict#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.predict "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.predict")(params[, exog, exog\_infl, exposure, …]) | Predict response variable of a count model given exogenous variables. | | [`score`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoisson.score#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.score "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.score")(params) | Score vector of model. | | [`score_obs`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoisson.score_obs#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.score_obs "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.score_obs")(params) | Generic Zero Inflated model score (gradient) vector of the log-likelihood | #### Attributes | | | | --- | --- | | `endog_names` | Names of endogenous variables | | `exog_names` | Names of exogenous variables | statsmodels statsmodels.tsa.vector_ar.var_model.VARResults.detomega statsmodels.tsa.vector\_ar.var\_model.VARResults.detomega ========================================================= `VARResults.detomega()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/var_model.html#VARResults.detomega) Return determinant of white noise covariance with degrees of freedom correction: \[\hat \Omega = \frac{T}{T - Kp - 1} \hat \Omega\_{\mathrm{MLE}}\] statsmodels statsmodels.regression.quantile_regression.QuantRegResults.HC3_se statsmodels.regression.quantile\_regression.QuantRegResults.HC3\_se =================================================================== `QuantRegResults.HC3_se()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/quantile_regression.html#QuantRegResults.HC3_se) See statsmodels.RegressionResults statsmodels statsmodels.discrete.count_model.ZeroInflatedPoissonResults.t_test statsmodels.discrete.count\_model.ZeroInflatedPoissonResults.t\_test ==================================================================== `ZeroInflatedPoissonResults.t_test(r_matrix, cov_p=None, scale=None, use_t=None)` Compute a t-test for a each linear hypothesis of the form Rb = q | Parameters: | * **r\_matrix** (*array-like**,* *str**,* *tuple*) – + array : If an array is given, a p x k 2d array or length k 1d array specifying the linear restrictions. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q). If q is given, can be either a scalar or a length p row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – An optional `scale` to use. Default is the scale specified by the model fit. * **use\_t** (*bool**,* *optional*) – If use\_t is None, then the default of the model is used. If use\_t is True, then the p-values are based on the t distribution. If use\_t is False, then the p-values are based on the normal distribution. | | Returns: | **res** – The results for the test are attributes of this results instance. The available results have the same elements as the parameter table in `summary()`. | | Return type: | ContrastResults instance | #### Examples ``` >>> import numpy as np >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> r = np.zeros_like(results.params) >>> r[5:] = [1,-1] >>> print(r) [ 0. 0. 0. 0. 0. 1. -1.] ``` r tests that the coefficients on the 5th and 6th independent variable are the same. ``` >>> T_test = results.t_test(r) >>> print(T_test) Test for Constraints ============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------ c0 -1829.2026 455.391 -4.017 0.003 -2859.368 -799.037 ============================================================================== >>> T_test.effect -1829.2025687192481 >>> T_test.sd 455.39079425193762 >>> T_test.tvalue -4.0167754636411717 >>> T_test.pvalue 0.0015163772380899498 ``` Alternatively, you can specify the hypothesis tests using a string ``` >>> from statsmodels.formula.api import ols >>> dta = sm.datasets.longley.load_pandas().data >>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' >>> results = ols(formula, dta).fit() >>> hypotheses = 'GNPDEFL = GNP, UNEMP = 2, YEAR/1829 = 1' >>> t_test = results.t_test(hypotheses) >>> print(t_test) Test for Constraints ============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------ c0 15.0977 84.937 0.178 0.863 -177.042 207.238 c1 -2.0202 0.488 -8.231 0.000 -3.125 -0.915 c2 1.0001 0.249 0.000 1.000 0.437 1.563 ============================================================================== ``` See also [`tvalues`](statsmodels.discrete.count_model.zeroinflatedpoissonresults.tvalues#statsmodels.discrete.count_model.ZeroInflatedPoissonResults.tvalues "statsmodels.discrete.count_model.ZeroInflatedPoissonResults.tvalues") individual t statistics [`f_test`](statsmodels.discrete.count_model.zeroinflatedpoissonresults.f_test#statsmodels.discrete.count_model.ZeroInflatedPoissonResults.f_test "statsmodels.discrete.count_model.ZeroInflatedPoissonResults.f_test") for F tests [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") statsmodels statsmodels.stats.contingency_tables.SquareTable.chi2_contribs statsmodels.stats.contingency\_tables.SquareTable.chi2\_contribs ================================================================ `SquareTable.chi2_contribs()` statsmodels statsmodels.stats.contingency_tables.Table.local_oddsratios statsmodels.stats.contingency\_tables.Table.local\_oddsratios ============================================================= `Table.local_oddsratios()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table.local_oddsratios) statsmodels statsmodels.tsa.statespace.sarimax.SARIMAXResults.test_heteroskedasticity statsmodels.tsa.statespace.sarimax.SARIMAXResults.test\_heteroskedasticity ========================================================================== `SARIMAXResults.test_heteroskedasticity(method, alternative='two-sided', use_f=True)` Test for heteroskedasticity of standardized residuals Tests whether the sum-of-squares in the first third of the sample is significantly different than the sum-of-squares in the last third of the sample. Analogous to a Goldfeld-Quandt test. The null hypothesis is of no heteroskedasticity. | Parameters: | * **method** (*string {'breakvar'}* *or* *None*) – The statistical test for heteroskedasticity. Must be ‘breakvar’ for test of a break in the variance. If None, an attempt is made to select an appropriate test. * **alternative** (*string**,* *'increasing'**,* *'decreasing'* *or* *'two-sided'*) – This specifies the alternative for the p-value calculation. Default is two-sided. * **use\_f** (*boolean**,* *optional*) – Whether or not to compare against the asymptotic distribution (chi-squared) or the approximate small-sample distribution (F). Default is True (i.e. default is to compare against an F distribution). | | Returns: | **output** – An array with `(test_statistic, pvalue)` for each endogenous variable. The array is then sized `(k_endog, 2)`. If the method is called as `het = res.test_heteroskedasticity()`, then `het[0]` is an array of size 2 corresponding to the first endogenous variable, where `het[0][0]` is the test statistic, and `het[0][1]` is the p-value. | | Return type: | array | #### Notes The null hypothesis is of no heteroskedasticity. That means different things depending on which alternative is selected: * Increasing: Null hypothesis is that the variance is not increasing throughout the sample; that the sum-of-squares in the later subsample is *not* greater than the sum-of-squares in the earlier subsample. * Decreasing: Null hypothesis is that the variance is not decreasing throughout the sample; that the sum-of-squares in the earlier subsample is *not* greater than the sum-of-squares in the later subsample. * Two-sided: Null hypothesis is that the variance is not changing throughout the sample. Both that the sum-of-squares in the earlier subsample is not greater than the sum-of-squares in the later subsample *and* that the sum-of-squares in the later subsample is not greater than the sum-of-squares in the earlier subsample. For \(h = [T/3]\), the test statistic is: \[H(h) = \sum\_{t=T-h+1}^T \tilde v\_t^2 \Bigg / \sum\_{t=d+1}^{d+1+h} \tilde v\_t^2\] where \(d\) is the number of periods in which the loglikelihood was burned in the parent model (usually corresponding to diffuse initialization). This statistic can be tested against an \(F(h,h)\) distribution. Alternatively, \(h H(h)\) is asymptotically distributed according to \(\chi\_h^2\); this second test can be applied by passing `asymptotic=True` as an argument. See section 5.4 of [[1]](#id2) for the above formula and discussion, as well as additional details. TODO * Allow specification of \(h\) #### References | | | | --- | --- | | [[1]](#id1) | Harvey, Andrew C. 1990. *Forecasting, Structural Time Series* *Models and the Kalman Filter.* Cambridge University Press. |
programming_docs
statsmodels statsmodels.multivariate.factor_rotation.rotate_factors statsmodels.multivariate.factor\_rotation.rotate\_factors ========================================================= `statsmodels.multivariate.factor_rotation.rotate_factors(A, method, *method_args, **algorithm_kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/multivariate/factor_rotation/_wrappers.html#rotate_factors) Subroutine for orthogonal and oblique rotation of the matrix \(A\). For orthogonal rotations \(A\) is rotated to \(L\) according to \[L = AT,\] where \(T\) is an orthogonal matrix. And, for oblique rotations \(A\) is rotated to \(L\) according to \[L = A(T^\*)^{-1},\] where \(T\) is a normal matrix. | Parameters: | * **A** (*numpy matrix* *(**default None**)*) – non rotated factors * **method** (*string*) – should be one of the methods listed below * **method\_args** (*list*) – additional arguments that should be provided with each method * **algorithm\_kwargs** (*dictionary*) – `algorithm : string (default gpa)` should be one of: + ’gpa’: a numerical method + ’gpa\_der\_free’: a derivative free numerical method + ’analytic’ : an analytic method Depending on the algorithm, there are algorithm specific keyword arguments. For the gpa and gpa\_der\_free, the following keyword arguments are available: `max_tries : integer (default 501)` maximum number of iterations `tol : float` stop criterion, algorithm stops if Frobenius norm of gradient is smaller then tol For analytic, the supporeted arguments depend on the method, see above. See the lower level functions for more details. | | Returns: | | | Return type: | The tuple \((L,T)\) | #### Notes What follows is a list of available methods. Depending on the method additional argument are required and different algorithms are available. The algorithm\_kwargs are additional keyword arguments passed to the selected algorithm (see the parameters section). Unless stated otherwise, only the gpa and gpa\_der\_free algorithm are available. Below, * \(L\) is a \(p\times k\) matrix; * \(N\) is \(k\times k\) matrix with zeros on the diagonal and ones elsewhere; * \(M\) is \(p\times p\) matrix with zeros on the diagonal and ones elsewhere; * \(C\) is a \(p\times p\) matrix with elements equal to \(1/p\); * \((X,Y)=\operatorname{Tr}(X^\*Y)\) is the Frobenius norm; * \(\circ\) is the element-wise product or Hadamard product. `oblimin : orthogonal or oblique rotation that minimizes` \[\phi(L) = \frac{1}{4}(L\circ L,(I-\gamma C)(L\circ L)N).\] For orthogonal rotations: * \(\gamma=0\) corresponds to quartimax, * \(\gamma=\frac{1}{2}\) corresponds to biquartimax, * \(\gamma=1\) corresponds to varimax, * \(\gamma=\frac{1}{p}\) corresponds to equamax. For oblique rotations rotations: * \(\gamma=0\) corresponds to quartimin, * \(\gamma=\frac{1}{2}\) corresponds to biquartimin. method\_args: `gamma : float` oblimin family parameter `rotation_method : string` should be one of {orthogonal, oblique} orthomax : orthogonal rotation that minimizes \[\phi(L) = -\frac{1}{4}(L\circ L,(I-\gamma C)(L\circ L)),\] where \(0\leq\gamma\leq1\). The orthomax family is equivalent to the oblimin family (when restricted to orthogonal rotations). Furthermore, * \(\gamma=0\) corresponds to quartimax, * \(\gamma=\frac{1}{2}\) corresponds to biquartimax, * \(\gamma=1\) corresponds to varimax, * \(\gamma=\frac{1}{p}\) corresponds to equamax. method\_args: `gamma : float (between 0 and 1)` orthomax family parameter CF : Crawford-Ferguson family for orthogonal and oblique rotation which minimizes: \[\phi(L) =\frac{1-\kappa}{4} (L\circ L,(L\circ L)N) -\frac{1}{4}(L\circ L,M(L\circ L)),\] where \(0\leq\kappa\leq1\). For orthogonal rotations the oblimin (and orthomax) family of rotations is equivalent to the Crawford-Ferguson family. To be more precise: * \(\kappa=0\) corresponds to quartimax, * \(\kappa=\frac{1}{p}\) corresponds to varimax, * \(\kappa=\frac{k-1}{p+k-2}\) corresponds to parsimax, * \(\kappa=1\) corresponds to factor parsimony. method\_args: `kappa : float (between 0 and 1)` Crawford-Ferguson family parameter `rotation_method : string` should be one of {orthogonal, oblique} `quartimax : orthogonal rotation method` minimizes the orthomax objective with \(\gamma=0\) `biquartimax : orthogonal rotation method` minimizes the orthomax objective with \(\gamma=\frac{1}{2}\) `varimax : orthogonal rotation method` minimizes the orthomax objective with \(\gamma=1\) `equamax : orthogonal rotation method` minimizes the orthomax objective with \(\gamma=\frac{1}{p}\) `parsimax : orthogonal rotation method` minimizes the Crawford-Ferguson family objective with \(\kappa=\frac{k-1}{p+k-2}\) `parsimony : orthogonal rotation method` minimizes the Crawford-Ferguson family objective with \(\kappa=1\) `quartimin : oblique rotation method that minimizes` minimizes the oblimin objective with \(\gamma=0\) `quartimin : oblique rotation method that minimizes` minimizes the oblimin objective with \(\gamma=\frac{1}{2}\) target : orthogonal or oblique rotation that rotates towards a target matrix : math:`H` by minimizing the objective \[\phi(L) =\frac{1}{2}\|L-H\|^2.\] method\_args: `H : numpy matrix` target matrix `rotation_method : string` should be one of {orthogonal, oblique} For orthogonal rotations the algorithm can be set to analytic in which case the following keyword arguments are available: `full_rank : boolean (default False)` if set to true full rank is assumed partial\_target : orthogonal (default) or oblique rotation that partially rotates towards a target matrix \(H\) by minimizing the objective: \[\phi(L) =\frac{1}{2}\|W\circ(L-H)\|^2.\] method\_args: `H : numpy matrix` target matrix `W : numpy matrix (default matrix with equal weight one for all entries)` matrix with weights, entries can either be one or zero #### Examples ``` >>> A = np.random.randn(8,2) >>> L, T = rotate_factors(A,'varimax') >>> np.allclose(L,A.dot(T)) >>> L, T = rotate_factors(A,'orthomax',0.5) >>> np.allclose(L,A.dot(T)) >>> L, T = rotate_factors(A,'quartimin',0.5) >>> np.allclose(L,A.dot(np.linalg.inv(T.T))) ``` statsmodels statsmodels.tsa.vector_ar.dynamic.DynamicVAR.T statsmodels.tsa.vector\_ar.dynamic.DynamicVAR.T =============================================== `DynamicVAR.T()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/dynamic.html#DynamicVAR.T) Number of time periods in results statsmodels statsmodels.tsa.statespace.kalman_filter.KalmanFilter statsmodels.tsa.statespace.kalman\_filter.KalmanFilter ====================================================== `class statsmodels.tsa.statespace.kalman_filter.KalmanFilter(k_endog, k_states, k_posdef=None, loglikelihood_burn=0, tolerance=1e-19, results_class=None, kalman_filter_classes=None, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/kalman_filter.html#KalmanFilter) State space representation of a time series process, with Kalman filter | Parameters: | * **k\_endog** (*array\_like* *or* *integer*) – The observed time-series process \(y\) if array like or the number of variables in the process if an integer. * **k\_states** (*int*) – The dimension of the unobserved state process. * **k\_posdef** (*int**,* *optional*) – The dimension of a guaranteed positive definite covariance matrix describing the shocks in the measurement equation. Must be less than or equal to `k_states`. Default is `k_states`. * **loglikelihood\_burn** (*int**,* *optional*) – The number of initial periods during which the loglikelihood is not recorded. Default is 0. * **tolerance** (*float**,* *optional*) – The tolerance at which the Kalman filter determines convergence to steady-state. Default is 1e-19. * **results\_class** (*class**,* *optional*) – Default results class to use to save filtering output. Default is `FilterResults`. If specified, class must extend from `FilterResults`. * **\*\*kwargs** – Keyword arguments may be used to provide values for the filter, inversion, and stability methods. See `set_filter_method`, `set_inversion_method`, and `set_stability_method`. Keyword arguments may be used to provide default values for state space matrices. See `Representation` for more details. | #### Notes There are several types of options available for controlling the Kalman filter operation. All options are internally held as bitmasks, but can be manipulated by setting class attributes, which act like boolean flags. For more information, see the `set_*` class method documentation. The options are: filter\_method The filtering method controls aspects of which Kalman filtering approach will be used. inversion\_method The Kalman filter may contain one matrix inversion: that of the forecast error covariance matrix. The inversion method controls how and if that inverse is performed. stability\_method The Kalman filter is a recursive algorithm that may in some cases suffer issues with numerical stability. The stability method controls what, if any, measures are taken to promote stability. conserve\_memory By default, the Kalman filter computes a number of intermediate matrices at each iteration. The memory conservation options control which of those matrices are stored. filter\_timing By default, the Kalman filter follows Durbin and Koopman, 2012, in initializing the filter with predicted values. Kim and Nelson, 1999, instead initialize the filter with filtered values, which is essentially just a different timing convention. The `filter_method` and `inversion_method` options intentionally allow the possibility that multiple methods will be indicated. In the case that multiple methods are selected, the underlying Kalman filter will attempt to select the optional method given the input data. For example, it may be that INVERT\_UNIVARIATE and SOLVE\_CHOLESKY are indicated (this is in fact the default case). In this case, if the endogenous vector is 1-dimensional (`k_endog` = 1), then INVERT\_UNIVARIATE is used and inversion reduces to simple division, and if it has a larger dimension, the Cholesky decomposition along with linear solving (rather than explicit matrix inversion) is used. If only SOLVE\_CHOLESKY had been set, then the Cholesky decomposition method would *always* be used, even in the case of 1-dimensional data. See also [`FilterResults`](statsmodels.tsa.statespace.kalman_filter.filterresults#statsmodels.tsa.statespace.kalman_filter.FilterResults "statsmodels.tsa.statespace.kalman_filter.FilterResults"), [`statsmodels.tsa.statespace.representation.Representation`](statsmodels.tsa.statespace.representation.representation#statsmodels.tsa.statespace.representation.Representation "statsmodels.tsa.statespace.representation.Representation") #### Methods | | | | --- | --- | | [`bind`](statsmodels.tsa.statespace.kalman_filter.kalmanfilter.bind#statsmodels.tsa.statespace.kalman_filter.KalmanFilter.bind "statsmodels.tsa.statespace.kalman_filter.KalmanFilter.bind")(endog) | Bind data to the statespace representation | | [`filter`](statsmodels.tsa.statespace.kalman_filter.kalmanfilter.filter#statsmodels.tsa.statespace.kalman_filter.KalmanFilter.filter "statsmodels.tsa.statespace.kalman_filter.KalmanFilter.filter")([filter\_method, inversion\_method, …]) | Apply the Kalman filter to the statespace model. | | [`impulse_responses`](statsmodels.tsa.statespace.kalman_filter.kalmanfilter.impulse_responses#statsmodels.tsa.statespace.kalman_filter.KalmanFilter.impulse_responses "statsmodels.tsa.statespace.kalman_filter.KalmanFilter.impulse_responses")([steps, impulse, …]) | Impulse response function | | [`initialize_approximate_diffuse`](statsmodels.tsa.statespace.kalman_filter.kalmanfilter.initialize_approximate_diffuse#statsmodels.tsa.statespace.kalman_filter.KalmanFilter.initialize_approximate_diffuse "statsmodels.tsa.statespace.kalman_filter.KalmanFilter.initialize_approximate_diffuse")([variance]) | Initialize the statespace model with approximate diffuse values. | | [`initialize_known`](statsmodels.tsa.statespace.kalman_filter.kalmanfilter.initialize_known#statsmodels.tsa.statespace.kalman_filter.KalmanFilter.initialize_known "statsmodels.tsa.statespace.kalman_filter.KalmanFilter.initialize_known")(initial\_state, …) | Initialize the statespace model with known distribution for initial state. | | [`initialize_stationary`](statsmodels.tsa.statespace.kalman_filter.kalmanfilter.initialize_stationary#statsmodels.tsa.statespace.kalman_filter.KalmanFilter.initialize_stationary "statsmodels.tsa.statespace.kalman_filter.KalmanFilter.initialize_stationary")() | Initialize the statespace model as stationary. | | [`loglike`](statsmodels.tsa.statespace.kalman_filter.kalmanfilter.loglike#statsmodels.tsa.statespace.kalman_filter.KalmanFilter.loglike "statsmodels.tsa.statespace.kalman_filter.KalmanFilter.loglike")(\*\*kwargs) | Calculate the loglikelihood associated with the statespace model. | | [`loglikeobs`](statsmodels.tsa.statespace.kalman_filter.kalmanfilter.loglikeobs#statsmodels.tsa.statespace.kalman_filter.KalmanFilter.loglikeobs "statsmodels.tsa.statespace.kalman_filter.KalmanFilter.loglikeobs")(\*\*kwargs) | Calculate the loglikelihood for each observation associated with the statespace model. | | [`set_conserve_memory`](statsmodels.tsa.statespace.kalman_filter.kalmanfilter.set_conserve_memory#statsmodels.tsa.statespace.kalman_filter.KalmanFilter.set_conserve_memory "statsmodels.tsa.statespace.kalman_filter.KalmanFilter.set_conserve_memory")([conserve\_memory]) | Set the memory conservation method | | [`set_filter_method`](statsmodels.tsa.statespace.kalman_filter.kalmanfilter.set_filter_method#statsmodels.tsa.statespace.kalman_filter.KalmanFilter.set_filter_method "statsmodels.tsa.statespace.kalman_filter.KalmanFilter.set_filter_method")([filter\_method]) | Set the filtering method | | [`set_filter_timing`](statsmodels.tsa.statespace.kalman_filter.kalmanfilter.set_filter_timing#statsmodels.tsa.statespace.kalman_filter.KalmanFilter.set_filter_timing "statsmodels.tsa.statespace.kalman_filter.KalmanFilter.set_filter_timing")([alternate\_timing]) | Set the filter timing convention | | [`set_inversion_method`](statsmodels.tsa.statespace.kalman_filter.kalmanfilter.set_inversion_method#statsmodels.tsa.statespace.kalman_filter.KalmanFilter.set_inversion_method "statsmodels.tsa.statespace.kalman_filter.KalmanFilter.set_inversion_method")([inversion\_method]) | Set the inversion method | | [`set_stability_method`](statsmodels.tsa.statespace.kalman_filter.kalmanfilter.set_stability_method#statsmodels.tsa.statespace.kalman_filter.KalmanFilter.set_stability_method "statsmodels.tsa.statespace.kalman_filter.KalmanFilter.set_stability_method")([stability\_method]) | Set the numerical stability method | | [`simulate`](statsmodels.tsa.statespace.kalman_filter.kalmanfilter.simulate#statsmodels.tsa.statespace.kalman_filter.KalmanFilter.simulate "statsmodels.tsa.statespace.kalman_filter.KalmanFilter.simulate")(nsimulations[, measurement\_shocks, …]) | Simulate a new time series following the state space model | #### Attributes | | | | --- | --- | | `conserve_memory` | (int) Memory conservation bitmask. | | `design` | | | `dtype` | (dtype) Datatype of currently active representation matrices | | `endog` | | | `filter_augmented` | (bool) Flag for augmented Kalman filtering. | | `filter_collapsed` | (bool) Flag for Kalman filtering with collapsed observation vector. | | `filter_conventional` | (bool) Flag for conventional Kalman filtering. | | `filter_exact_initial` | (bool) Flag for exact initial Kalman filtering. | | `filter_extended` | (bool) Flag for extended Kalman filtering. | | `filter_method` | (int) Filtering method bitmask. | | `filter_methods` | | | `filter_square_root` | (bool) Flag for square-root Kalman filtering. | | `filter_timing` | (int) Filter timing. | | `filter_univariate` | (bool) Flag for univariate filtering of multivariate observation vector. | | `filter_unscented` | (bool) Flag for unscented Kalman filtering. | | `inversion_method` | (int) Inversion method bitmask. | | `inversion_methods` | | | `invert_cholesky` | (bool) Flag for Cholesky inversion method. | | `invert_lu` | (bool) Flag for LU inversion method. | | `invert_univariate` | (bool) Flag for univariate inversion method (recommended). | | `memory_conserve` | (bool) Flag to conserve the maximum amount of memory. | | `memory_no_filtered` | (bool) Flag to prevent storing filtered state and covariance matrices. | | `memory_no_forecast` | (bool) Flag to prevent storing forecasts. | | `memory_no_gain` | (bool) Flag to prevent storing the Kalman gain matrices. | | `memory_no_likelihood` | (bool) Flag to prevent storing likelihood values for each observation. | | `memory_no_predicted` | (bool) Flag to prevent storing predicted state and covariance matrices. | | `memory_no_smoothing` | (bool) Flag to prevent storing likelihood values for each observation. | | `memory_no_std_forecast` | (bool) Flag to prevent storing standardized forecast errors. | | `memory_options` | | | `memory_store_all` | (bool) Flag for storing all intermediate results in memory (default). | | `obs` | *(array) Observation vector* – \(y~(k\\_endog \times nobs)\) | | `obs_cov` | | | `obs_intercept` | | | `prefix` | (str) BLAS prefix of currently active representation matrices | | `selection` | | | `solve_cholesky` | (bool) Flag for Cholesky and linear solver inversion method (recommended). | | `solve_lu` | (bool) Flag for LU and linear solver inversion method. | | `stability_force_symmetry` | (bool) Flag for enforcing covariance matrix symmetry | | `stability_method` | (int) Stability method bitmask. | | `stability_methods` | | | `state_cov` | | | `state_intercept` | | | `time_invariant` | (bool) Whether or not currently active representation matrices are time-invariant | | `timing_init_filtered` | (bool) Flag for the alternate timing convention (Kim and Nelson, 2012). | | `timing_init_predicted` | (bool) Flag for the default timing convention (Durbin and Koopman, 2012). | | `timing_options` | | | `transition` | | statsmodels statsmodels.discrete.discrete_model.CountModel.hessian statsmodels.discrete.discrete\_model.CountModel.hessian ======================================================= `CountModel.hessian(params)` The Hessian matrix of the model statsmodels statsmodels.stats.weightstats._zstat_generic statsmodels.stats.weightstats.\_zstat\_generic ============================================== `statsmodels.stats.weightstats._zstat_generic(value1, value2, std_diff, alternative, diff=0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/weightstats.html#_zstat_generic) generic (normal) z-test to save typing can be used as ztest based on summary statistics statsmodels statsmodels.duration.hazard_regression.PHReg.loglike statsmodels.duration.hazard\_regression.PHReg.loglike ===================================================== `PHReg.loglike(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/duration/hazard_regression.html#PHReg.loglike) Returns the log partial likelihood function evaluated at `params`. statsmodels statsmodels.genmod.bayes_mixed_glm.PoissonBayesMixedGLM.logposterior statsmodels.genmod.bayes\_mixed\_glm.PoissonBayesMixedGLM.logposterior ====================================================================== `PoissonBayesMixedGLM.logposterior(params)` The overall log-density: log p(y, fe, vc, vcp). This differs by an additive constant from the log posterior log p(fe, vc, vcp | y). statsmodels statsmodels.discrete.discrete_model.GeneralizedPoissonResults.pvalues statsmodels.discrete.discrete\_model.GeneralizedPoissonResults.pvalues ====================================================================== `GeneralizedPoissonResults.pvalues()`
programming_docs
statsmodels statsmodels.stats.contingency_tables.SquareTable.cumulative_oddsratios statsmodels.stats.contingency\_tables.SquareTable.cumulative\_oddsratios ======================================================================== `SquareTable.cumulative_oddsratios()` statsmodels statsmodels.multivariate.factor.Factor.from_formula statsmodels.multivariate.factor.Factor.from\_formula ==================================================== `classmethod Factor.from_formula(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** (*extra arguments*) – These are passed to the model * **kwargs** (*extra keyword arguments*) – These are passed to the model with one exception. The `eval_env` keyword is passed to patsy. It can be either a [`patsy.EvalEnvironment`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.EvalEnvironment "(in patsy v0.5.0+dev)") 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** | | Return type: | 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 statsmodels.tsa.vector_ar.vecm.VECM.from_formula statsmodels.tsa.vector\_ar.vecm.VECM.from\_formula ================================================== `classmethod VECM.from_formula(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** (*extra arguments*) – These are passed to the model * **kwargs** (*extra keyword arguments*) – These are passed to the model with one exception. The `eval_env` keyword is passed to patsy. It can be either a [`patsy.EvalEnvironment`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.EvalEnvironment "(in patsy v0.5.0+dev)") 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** | | Return type: | 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 statsmodels.sandbox.regression.gmm.GMMResults.q statsmodels.sandbox.regression.gmm.GMMResults.q =============================================== `GMMResults.q()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#GMMResults.q) statsmodels statsmodels.miscmodels.count.PoissonZiGMLE.initialize statsmodels.miscmodels.count.PoissonZiGMLE.initialize ===================================================== `PoissonZiGMLE.initialize()` Initialize (possibly re-initialize) a Model instance. For instance, the design matrix of a linear model may change and some things must be recomputed. statsmodels statsmodels.tsa.statespace.mlemodel.MLEResults.aic statsmodels.tsa.statespace.mlemodel.MLEResults.aic ================================================== `MLEResults.aic()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEResults.aic) (float) Akaike Information Criterion statsmodels statsmodels.robust.robust_linear_model.RLM.hessian statsmodels.robust.robust\_linear\_model.RLM.hessian ==================================================== `RLM.hessian(params)` The Hessian matrix of the model statsmodels statsmodels.discrete.discrete_model.GeneralizedPoisson.loglikeobs statsmodels.discrete.discrete\_model.GeneralizedPoisson.loglikeobs ================================================================== `GeneralizedPoisson.loglikeobs(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#GeneralizedPoisson.loglikeobs) Loglikelihood for observations of Generalized Poisson model | Parameters: | **params** (*array-like*) – The parameters of the model. | | Returns: | **loglike** – The log likelihood for each observation of the model evaluated at `params`. See Notes | | Return type: | ndarray | #### Notes \[\ln L=\sum\_{i=1}^{n}\left[\mu\_{i}+(y\_{i}-1)\*ln(\mu\_{i}+ \alpha\*\mu\_{i}^{p-1}\*y\_{i})-y\_{i}\*ln(1+\alpha\*\mu\_{i}^{p-1})- ln(y\_{i}!)-\frac{\mu\_{i}+\alpha\*\mu\_{i}^{p-1}\*y\_{i}}{1+\alpha\* \mu\_{i}^{p-1}}\right]\] for observations \(i=1,...,n\) statsmodels statsmodels.discrete.discrete_model.NegativeBinomial.predict statsmodels.discrete.discrete\_model.NegativeBinomial.predict ============================================================= `NegativeBinomial.predict(params, exog=None, exposure=None, offset=None, linear=False)` Predict response variable of a count model given exogenous variables. #### Notes If exposure is specified, then it will be logged by the method. The user does not need to log it first. statsmodels statsmodels.stats.sandwich_covariance.cov_nw_groupsum statsmodels.stats.sandwich\_covariance.cov\_nw\_groupsum ======================================================== `statsmodels.stats.sandwich_covariance.cov_nw_groupsum(results, nlags, time, weights_func=<function weights_bartlett>, use_correction=0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/sandwich_covariance.html#cov_nw_groupsum) Driscoll and Kraay Panel robust covariance matrix Robust covariance matrix for panel data of Driscoll and Kraay. Assumes we have a panel of time series where the time index is available. The time index is assumed to represent equal spaced periods. At least one observation per period is required. | Parameters: | * **results** (*result instance*) – result of a regression, uses results.model.exog and results.resid TODO: this should use wexog instead * **nlags** (*int* *or* *None*) – Highest lag to include in kernel window. Currently, no default because the optimal length will depend on the number of observations per cross-sectional unit. * **time** (*ndarray of int*) – this should contain the coding for the time period of each observation. time periods should be integers in range(maxT) where maxT is obs of i * **weights\_func** (*callable*) – weights\_func is called with nlags as argument to get the kernel weights. default are Bartlett weights * **use\_correction** (*'cluster'* *or* *'hac'* *or* *False*) – If False, then no small sample correction is used. If ‘hac’ (default), then the same correction as in single time series, cov\_hac is used. If ‘cluster’, then the same correction as in cov\_cluster is used. | | Returns: | **cov** – HAC robust covariance matrix for parameter estimates | | Return type: | ndarray, (k\_vars, k\_vars) | #### Notes Tested against STATA xtscc package, which uses no small sample correction This first averages relevant variables for each time period over all individuals/groups, and then applies the same kernel weighted averaging over time as in HAC. Warning: In the example with a short panel (few time periods and many individuals) with mainly across individual variation this estimator did not produce reasonable results. Options might change when other kernels besides Bartlett and uniform are available. #### References Daniel Hoechle, xtscc paper Driscoll and Kraay statsmodels statsmodels.discrete.discrete_model.MultinomialModel.information statsmodels.discrete.discrete\_model.MultinomialModel.information ================================================================= `MultinomialModel.information(params)` Fisher information matrix of model Returns -Hessian of loglike evaluated at params. statsmodels statsmodels.stats.proportion.binom_tost statsmodels.stats.proportion.binom\_tost ======================================== `statsmodels.stats.proportion.binom_tost(count, nobs, low, upp)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/proportion.html#binom_tost) exact TOST test for one proportion using binomial distribution | Parameters: | * **count** (*integer* *or* *array\_like*) – the number of successes in nobs trials. * **nobs** (*integer*) – the number of trials or observations. * **upp** (*low**,*) – lower and upper limit of equivalence region | | Returns: | * **pvalue** (*float*) – p-value of equivalence test * **pval\_low, pval\_upp** (*floats*) – p-values of lower and upper one-sided tests | statsmodels statsmodels.tsa.statespace.structural.UnobservedComponents.opg_information_matrix statsmodels.tsa.statespace.structural.UnobservedComponents.opg\_information\_matrix =================================================================================== `UnobservedComponents.opg_information_matrix(params, transformed=True, approx_complex_step=None, **kwargs)` Outer product of gradients information matrix | Parameters: | * **params** (*array\_like**,* *optional*) – Array of parameters at which to evaluate the loglikelihood function. * **\*\*kwargs** – Additional arguments to the `loglikeobs` method. | #### References Berndt, Ernst R., Bronwyn Hall, Robert Hall, and Jerry Hausman. 1974. Estimation and Inference in Nonlinear Structural Models. NBER Chapters. National Bureau of Economic Research, Inc. statsmodels statsmodels.discrete.discrete_model.Probit.fit_regularized statsmodels.discrete.discrete\_model.Probit.fit\_regularized ============================================================ `Probit.fit_regularized(start_params=None, method='l1', maxiter='defined_by_method', full_output=1, disp=1, callback=None, alpha=0, trim_mode='auto', auto_trim_tol=0.01, size_trim_tol=0.0001, qc_tol=0.03, **kwargs)` Fit the model using a regularized maximum likelihood. The regularization method AND the solver used is determined by the argument method. | Parameters: | * **start\_params** (*array-like**,* *optional*) – Initial guess of the solution for the loglikelihood maximization. The default is an array of zeros. * **method** (*'l1'* *or* *'l1\_cvxopt\_cp'*) – See notes for details. * **maxiter** (*Integer* *or* *'defined\_by\_method'*) – Maximum number of iterations to perform. If ‘defined\_by\_method’, then use method defaults (see notes). * **full\_output** (*bool*) – Set to True to have all available output in the Results object’s mle\_retvals attribute. The output is dependent on the solver. See LikelihoodModelResults notes section for more information. * **disp** (*bool*) – Set to True to print convergence messages. * **fargs** (*tuple*) – Extra arguments passed to the likelihood function, i.e., loglike(x,\*args) * **callback** (*callable callback**(**xk**)*) – Called after each iteration, as callback(xk), where xk is the current parameter vector. * **retall** (*bool*) – Set to True to return list of solutions at each iteration. Available in Results object’s mle\_retvals attribute. * **alpha** (*non-negative scalar* *or* *numpy array* *(**same size as parameters**)*) – The weight multiplying the l1 penalty term * **trim\_mode** (*'auto**,* *'size'**, or* *'off'*) – If not ‘off’, trim (set to zero) parameters that would have been zero if the solver reached the theoretical minimum. If ‘auto’, trim params using the Theory above. If ‘size’, trim params if they have very small absolute value * **size\_trim\_tol** (*float* *or* *'auto'* *(**default = 'auto'**)*) – For use when trim\_mode == ‘size’ * **auto\_trim\_tol** (*float*) – For sue when trim\_mode == ‘auto’. Use * **qc\_tol** (*float*) – Print warning and don’t allow auto trim when (ii) (above) is violated by this much. * **qc\_verbose** (*Boolean*) – If true, print out a full QC report upon failure | #### Notes Extra parameters are not penalized if alpha is given as a scalar. An example is the shape parameter in NegativeBinomial `nb1` and `nb2`. Optional arguments for the solvers (available in Results.mle\_settings): ``` 'l1' acc : float (default 1e-6) Requested accuracy as used by slsqp 'l1_cvxopt_cp' abstol : float absolute accuracy (default: 1e-7). reltol : float relative accuracy (default: 1e-6). feastol : float tolerance for feasibility conditions (default: 1e-7). refinement : int number of iterative refinement steps when solving KKT equations (default: 1). ``` Optimization methodology With \(L\) the negative log likelihood, we solve the convex but non-smooth problem \[\min\_\beta L(\beta) + \sum\_k\alpha\_k |\beta\_k|\] via the transformation to the smooth, convex, constrained problem in twice as many variables (adding the “added variables” \(u\_k\)) \[\min\_{\beta,u} L(\beta) + \sum\_k\alpha\_k u\_k,\] subject to \[-u\_k \leq \beta\_k \leq u\_k.\] With \(\partial\_k L\) the derivative of \(L\) in the \(k^{th}\) parameter direction, theory dictates that, at the minimum, exactly one of two conditions holds: 1. \(|\partial\_k L| = \alpha\_k\) and \(\beta\_k \neq 0\) 2. \(|\partial\_k L| \leq \alpha\_k\) and \(\beta\_k = 0\) statsmodels statsmodels.discrete.discrete_model.CountModel.cdf statsmodels.discrete.discrete\_model.CountModel.cdf =================================================== `CountModel.cdf(X)` The cumulative distribution function of the model. statsmodels statsmodels.genmod.families.links.inverse_power.deriv statsmodels.genmod.families.links.inverse\_power.deriv ====================================================== `inverse_power.deriv(p)` Derivative of the power transform | Parameters: | **p** (*array-like*) – Mean parameters | | Returns: | **g’(p)** – Derivative of power transform of `p` | | Return type: | array | #### Notes g’(`p`) = `power` \* `p`**(`power` - 1) statsmodels statsmodels.tsa.statespace.varmax.VARMAX.set_stability_method statsmodels.tsa.statespace.varmax.VARMAX.set\_stability\_method =============================================================== `VARMAX.set_stability_method(stability_method=None, **kwargs)` Set the numerical stability method The Kalman filter is a recursive algorithm that may in some cases suffer issues with numerical stability. The stability method controls what, if any, measures are taken to promote stability. | Parameters: | * **stability\_method** (*integer**,* *optional*) – Bitmask value to set the stability method to. See notes for details. * **\*\*kwargs** – Keyword arguments may be used to influence the stability method by setting individual boolean flags. See notes for details. | #### Notes This method is rarely used. See the corresponding function in the `KalmanFilter` class for details. statsmodels statsmodels.regression.linear_model.OLSResults.mse_total statsmodels.regression.linear\_model.OLSResults.mse\_total ========================================================== `OLSResults.mse_total()` statsmodels statsmodels.emplike.descriptive.DescStatUV.test_skew statsmodels.emplike.descriptive.DescStatUV.test\_skew ===================================================== `DescStatUV.test_skew(skew0, return_weights=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/emplike/descriptive.html#DescStatUV.test_skew) Returns -2 x log-likelihood and p-value for the hypothesized skewness. | Parameters: | * **skew0** (*float*) – Skewness value to be tested * **return\_weights** (*bool*) – If True, function also returns the weights that maximize the likelihood ratio. Default is False. | | Returns: | **test\_results** – The log-likelihood ratio and p\_value of skew0 | | Return type: | tuple | statsmodels statsmodels.tsa.statespace.mlemodel.MLEModel.initialize_approximate_diffuse statsmodels.tsa.statespace.mlemodel.MLEModel.initialize\_approximate\_diffuse ============================================================================= `MLEModel.initialize_approximate_diffuse(variance=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEModel.initialize_approximate_diffuse) statsmodels statsmodels.discrete.count_model.GenericZeroInflated statsmodels.discrete.count\_model.GenericZeroInflated ===================================================== `class statsmodels.discrete.count_model.GenericZeroInflated(endog, exog, exog_infl=None, offset=None, inflation='logit', exposure=None, missing='none', **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/count_model.html#GenericZeroInflated) Generiz Zero Inflated model for count data | Parameters: | * **endog** (*array-like*) – 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 `statsmodels.tools.add_constant`. * **exog\_infl** (*array\_like* *or* *None*) – Explanatory variables for the binary inflation model, i.e. for mixing probability model. If None, then a constant is used. * **offset** (*array\_like*) – Offset is added to the linear prediction with coefficient equal to 1. * **exposure** (*array\_like*) – Log(exposure) is added to the linear prediction with coefficient equal to 1. * **inflation** (*string**,* *'logit'* *or* *'probit'*) – The model for the zero inflation, either Logit (default) or Probit * **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.’ | `endog` *array* – A reference to the endogenous response variable `exog` *array* – A reference to the exogenous design. `exog_infl` *array* – A reference to the zero-inflated exogenous design. #### Methods | | | | --- | --- | | [`cdf`](statsmodels.discrete.count_model.genericzeroinflated.cdf#statsmodels.discrete.count_model.GenericZeroInflated.cdf "statsmodels.discrete.count_model.GenericZeroInflated.cdf")(X) | The cumulative distribution function of the model. | | [`cov_params_func_l1`](statsmodels.discrete.count_model.genericzeroinflated.cov_params_func_l1#statsmodels.discrete.count_model.GenericZeroInflated.cov_params_func_l1 "statsmodels.discrete.count_model.GenericZeroInflated.cov_params_func_l1")(likelihood\_model, xopt, …) | Computes cov\_params on a reduced parameter space corresponding to the nonzero parameters resulting from the l1 regularized fit. | | [`fit`](statsmodels.discrete.count_model.genericzeroinflated.fit#statsmodels.discrete.count_model.GenericZeroInflated.fit "statsmodels.discrete.count_model.GenericZeroInflated.fit")([start\_params, method, maxiter, …]) | Fit the model using maximum likelihood. | | [`fit_regularized`](statsmodels.discrete.count_model.genericzeroinflated.fit_regularized#statsmodels.discrete.count_model.GenericZeroInflated.fit_regularized "statsmodels.discrete.count_model.GenericZeroInflated.fit_regularized")([start\_params, method, …]) | Fit the model using a regularized maximum likelihood. | | [`from_formula`](statsmodels.discrete.count_model.genericzeroinflated.from_formula#statsmodels.discrete.count_model.GenericZeroInflated.from_formula "statsmodels.discrete.count_model.GenericZeroInflated.from_formula")(formula, data[, subset, drop\_cols]) | Create a Model from a formula and dataframe. | | [`hessian`](statsmodels.discrete.count_model.genericzeroinflated.hessian#statsmodels.discrete.count_model.GenericZeroInflated.hessian "statsmodels.discrete.count_model.GenericZeroInflated.hessian")(params) | Generic Zero Inflated model Hessian matrix of the loglikelihood | | [`information`](statsmodels.discrete.count_model.genericzeroinflated.information#statsmodels.discrete.count_model.GenericZeroInflated.information "statsmodels.discrete.count_model.GenericZeroInflated.information")(params) | Fisher information matrix of model | | [`initialize`](statsmodels.discrete.count_model.genericzeroinflated.initialize#statsmodels.discrete.count_model.GenericZeroInflated.initialize "statsmodels.discrete.count_model.GenericZeroInflated.initialize")() | Initialize is called by statsmodels.model.LikelihoodModel.\_\_init\_\_ and should contain any preprocessing that needs to be done for a model. | | [`loglike`](statsmodels.discrete.count_model.genericzeroinflated.loglike#statsmodels.discrete.count_model.GenericZeroInflated.loglike "statsmodels.discrete.count_model.GenericZeroInflated.loglike")(params) | Loglikelihood of Generic Zero Inflated model | | [`loglikeobs`](statsmodels.discrete.count_model.genericzeroinflated.loglikeobs#statsmodels.discrete.count_model.GenericZeroInflated.loglikeobs "statsmodels.discrete.count_model.GenericZeroInflated.loglikeobs")(params) | Loglikelihood for observations of Generic Zero Inflated model | | [`pdf`](statsmodels.discrete.count_model.genericzeroinflated.pdf#statsmodels.discrete.count_model.GenericZeroInflated.pdf "statsmodels.discrete.count_model.GenericZeroInflated.pdf")(X) | The probability density (mass) function of the model. | | [`predict`](statsmodels.discrete.count_model.genericzeroinflated.predict#statsmodels.discrete.count_model.GenericZeroInflated.predict "statsmodels.discrete.count_model.GenericZeroInflated.predict")(params[, exog, exog\_infl, exposure, …]) | Predict response variable of a count model given exogenous variables. | | [`score`](statsmodels.discrete.count_model.genericzeroinflated.score#statsmodels.discrete.count_model.GenericZeroInflated.score "statsmodels.discrete.count_model.GenericZeroInflated.score")(params) | Score vector of model. | | [`score_obs`](statsmodels.discrete.count_model.genericzeroinflated.score_obs#statsmodels.discrete.count_model.GenericZeroInflated.score_obs "statsmodels.discrete.count_model.GenericZeroInflated.score_obs")(params) | Generic Zero Inflated model score (gradient) vector of the log-likelihood | #### Attributes | | | | --- | --- | | `endog_names` | Names of endogenous variables | | `exog_names` | Names of exogenous variables |
programming_docs
statsmodels statsmodels.tsa.statespace.structural.UnobservedComponentsResults.bse statsmodels.tsa.statespace.structural.UnobservedComponentsResults.bse ===================================================================== `UnobservedComponentsResults.bse()` statsmodels statsmodels.tsa.vector_ar.vecm.VECMResults.pvalues_alpha statsmodels.tsa.vector\_ar.vecm.VECMResults.pvalues\_alpha ========================================================== `VECMResults.pvalues_alpha()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/vecm.html#VECMResults.pvalues_alpha) statsmodels statsmodels.stats.moment_helpers.mnc2cum statsmodels.stats.moment\_helpers.mnc2cum ========================================= `statsmodels.stats.moment_helpers.mnc2cum(mnc)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/moment_helpers.html#mnc2cum) convert non-central moments to cumulants recursive formula produces as many cumulants as moments <http://en.wikipedia.org/wiki/Cumulant#Cumulants_and_moments> statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.mse_resid statsmodels.sandbox.regression.gmm.IVRegressionResults.mse\_resid ================================================================= `IVRegressionResults.mse_resid()` statsmodels statsmodels.discrete.count_model.ZeroInflatedPoissonResults.pvalues statsmodels.discrete.count\_model.ZeroInflatedPoissonResults.pvalues ==================================================================== `ZeroInflatedPoissonResults.pvalues()` statsmodels statsmodels.discrete.discrete_model.MNLogit.predict statsmodels.discrete.discrete\_model.MNLogit.predict ==================================================== `MNLogit.predict(params, exog=None, linear=False)` Predict response variable of a model given exogenous variables. | Parameters: | * **params** (*array-like*) – 2d array of fitted parameters of the model. Should be in the order returned from the model. * **exog** (*array-like*) – 1d or 2d array of exogenous values. If not supplied, the whole exog attribute of the model is used. If a 1d array is given it assumed to be 1 row of exogenous variables. If you only have one regressor and would like to do prediction, you must provide a 2d array with shape[1] == 1. * **linear** (*bool**,* *optional*) – If True, returns the linear predictor dot(exog,params). Else, returns the value of the cdf at the linear predictor. | #### Notes Column 0 is the base case, the rest conform to the rows of params shifted up one for the base case. statsmodels statsmodels.nonparametric.kernel_regression.KernelReg.fit statsmodels.nonparametric.kernel\_regression.KernelReg.fit ========================================================== `KernelReg.fit(data_predict=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/nonparametric/kernel_regression.html#KernelReg.fit) Returns the mean and marginal effects at the `data_predict` points. | Parameters: | **data\_predict** (*array\_like**,* *optional*) – Points at which to return the mean and marginal effects. If not given, `data_predict == exog`. | | Returns: | * **mean** (*ndarray*) – The regression result for the mean (i.e. the actual curve). * **mfx** (*ndarray*) – The marginal effects, i.e. the partial derivatives of the mean. | statsmodels statsmodels.genmod.generalized_estimating_equations.GEEResults.centered_resid statsmodels.genmod.generalized\_estimating\_equations.GEEResults.centered\_resid ================================================================================ `GEEResults.centered_resid()` Returns the residuals centered within each group. statsmodels statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.loglike statsmodels.tsa.regime\_switching.markov\_regression.MarkovRegression.loglike ============================================================================= `MarkovRegression.loglike(params, transformed=True)` Loglikelihood evaluation | Parameters: | * **params** (*array\_like*) – Array of parameters at which to evaluate the loglikelihood function. * **transformed** (*boolean**,* *optional*) – Whether or not `params` is already transformed. Default is True. | statsmodels statsmodels.stats.weightstats.CompareMeans.tconfint_diff statsmodels.stats.weightstats.CompareMeans.tconfint\_diff ========================================================= `CompareMeans.tconfint_diff(alpha=0.05, alternative='two-sided', usevar='pooled')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/weightstats.html#CompareMeans.tconfint_diff) confidence interval for the difference in means | Parameters: | * **alpha** (*float*) – significance level for the confidence interval, coverage is `1-alpha` * **alternative** (*string*) – This specifies the alternative hypothesis for the test that corresponds to the confidence interval. The alternative hypothesis, H1, has to be one of the following : ’two-sided’: H1: difference in means not equal to value (default) ‘larger’ : H1: difference in means larger than value ‘smaller’ : H1: difference in means smaller than value * **usevar** (*string**,* *'pooled'* *or* *'unequal'*) – If `pooled`, then the standard deviation of the samples is assumed to be the same. If `unequal`, then Welsh ttest with Satterthwait degrees of freedom is used | | Returns: | **lower, upper** – lower and upper limits of the confidence interval | | Return type: | floats | #### Notes The result is independent of the user specified ddof. statsmodels statsmodels.discrete.discrete_model.ProbitResults.llf statsmodels.discrete.discrete\_model.ProbitResults.llf ====================================================== `ProbitResults.llf()` statsmodels statsmodels.genmod.cov_struct.Independence.covariance_matrix_solve statsmodels.genmod.cov\_struct.Independence.covariance\_matrix\_solve ===================================================================== `Independence.covariance_matrix_solve(expval, index, stdev, rhs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/cov_struct.html#Independence.covariance_matrix_solve) Solves matrix equations of the form `covmat * soln = rhs` and returns the values of `soln`, where `covmat` is the covariance matrix represented by this class. | Parameters: | * **expval** (*array-like*) – The expected value of endog for each observed value in the group. * **index** (*integer*) – The group index. * **stdev** (*array-like*) – The standard deviation of endog for each observation in the group. * **rhs** (*list/tuple of array-like*) – A set of right-hand sides; each defines a matrix equation to be solved. | | Returns: | **soln** – The solutions to the matrix equations. | | Return type: | list/tuple of array-like | #### Notes Returns None if the solver fails. Some dependence structures do not use `expval` and/or `index` to determine the correlation matrix. Some families (e.g. binomial) do not use the `stdev` parameter when forming the covariance matrix. If the covariance matrix is singular or not SPD, it is projected to the nearest such matrix. These projection events are recorded in the fit\_history member of the GEE model. Systems of linear equations with the covariance matrix as the left hand side (LHS) are solved for different right hand sides (RHS); the LHS is only factorized once to save time. This is a default implementation, it can be reimplemented in subclasses to optimize the linear algebra according to the struture of the covariance matrix. statsmodels statsmodels.duration.hazard_regression.PHRegResults.conf_int statsmodels.duration.hazard\_regression.PHRegResults.conf\_int ============================================================== `PHRegResults.conf_int(alpha=0.05, cols=None, method='default')` Returns the confidence interval of the fitted parameters. | Parameters: | * **alpha** (*float**,* *optional*) – The significance level for the confidence interval. ie., The default `alpha` = .05 returns a 95% confidence interval. * **cols** (*array-like**,* *optional*) – `cols` specifies which confidence intervals to return * **method** (*string*) – Not Implemented Yet Method to estimate the confidence\_interval. “Default” : uses self.bse which is based on inverse Hessian for MLE “hjjh” : “jac” : “boot-bse” “boot\_quant” “profile” | | Returns: | **conf\_int** – Each row contains [lower, upper] limits of the confidence interval for the corresponding parameter. The first column contains all lower, the second column contains all upper limits. | | Return type: | array | #### Examples ``` >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> results.conf_int() array([[-5496529.48322745, -1467987.78596704], [ -177.02903529, 207.15277984], [ -0.1115811 , 0.03994274], [ -3.12506664, -0.91539297], [ -1.5179487 , -0.54850503], [ -0.56251721, 0.460309 ], [ 798.7875153 , 2859.51541392]]) ``` ``` >>> results.conf_int(cols=(2,3)) array([[-0.1115811 , 0.03994274], [-3.12506664, -0.91539297]]) ``` #### Notes The confidence interval is based on the standard normal distribution. Models wish to use a different distribution should overwrite this method. statsmodels statsmodels.tsa.statespace.kalman_filter.PredictionResults.update_filter statsmodels.tsa.statespace.kalman\_filter.PredictionResults.update\_filter ========================================================================== `PredictionResults.update_filter(kalman_filter)` Update the filter results | Parameters: | **kalman\_filter** ([statespace.kalman\_filter.KalmanFilter](statsmodels.tsa.statespace.kalman_filter.kalmanfilter#statsmodels.tsa.statespace.kalman_filter.KalmanFilter "statsmodels.tsa.statespace.kalman_filter.KalmanFilter")) – The model object from which to take the updated values. | #### Notes This method is rarely required except for internal usage. statsmodels statsmodels.regression.recursive_ls.RecursiveLS.score statsmodels.regression.recursive\_ls.RecursiveLS.score ====================================================== `RecursiveLS.score(params, *args, **kwargs)` Compute the score function at params. | Parameters: | * **params** (*array\_like*) – Array of parameters at which to evaluate the score. * **args** – Additional positional arguments to the `loglike` method. * **kwargs** – Additional keyword arguments to the `loglike` method. | | Returns: | **score** – Score, evaluated at `params`. | | Return type: | array | #### Notes This is a numerical approximation, calculated using first-order complex step differentiation on the `loglike` method. Both \*args and \*\*kwargs are necessary because the optimizer from `fit` must call this function and only supports passing arguments via \*args (for example `scipy.optimize.fmin_l_bfgs`). statsmodels statsmodels.tsa.statespace.varmax.VARMAXResults.t_test_pairwise statsmodels.tsa.statespace.varmax.VARMAXResults.t\_test\_pairwise ================================================================= `VARMAXResults.t_test_pairwise(term_name, method='hs', alpha=0.05, factor_labels=None)` perform pairwise t\_test with multiple testing corrected p-values This uses the formula design\_info encoding contrast matrix and should work for all encodings of a main effect. | Parameters: | * **result** (*result instance*) – The results of an estimated model with a categorical main effect. * **term\_name** (*str*) – name of the term for which pairwise comparisons are computed. Term names for categorical effects are created by patsy and correspond to the main part of the exog names. * **method** (*str* *or* *list of strings*) – multiple testing p-value correction, default is ‘hs’, see stats.multipletesting * **alpha** (*float*) – significance level for multiple testing reject decision. * **factor\_labels** (*None**,* *list of str*) – Labels for the factor levels used for pairwise labels. If not provided, then the labels from the formula design\_info are used. | | Returns: | **results** – The results are stored as attributes, the main attributes are the following two. Other attributes are added for debugging purposes or as background information.* result\_frame : pandas DataFrame with t\_test results and multiple testing corrected p-values. * contrasts : matrix of constraints of the null hypothesis in the t\_test. | | Return type: | instance of a simple Results class | #### Notes Status: experimental. Currently only checked for treatment coding with and without specified reference level. Currently there are no multiple testing corrected confidence intervals available. #### Examples ``` >>> res = ols("np.log(Days+1) ~ C(Weight) + C(Duration)", data).fit() >>> pw = res.t_test_pairwise("C(Weight)") >>> pw.result_frame coef std err t P>|t| Conf. Int. Low 2-1 0.632315 0.230003 2.749157 8.028083e-03 0.171563 3-1 1.302555 0.230003 5.663201 5.331513e-07 0.841803 3-2 0.670240 0.230003 2.914044 5.119126e-03 0.209488 Conf. Int. Upp. pvalue-hs reject-hs 2-1 1.093067 0.010212 True 3-1 1.763307 0.000002 True 3-2 1.130992 0.010212 True ``` statsmodels statsmodels.tsa.vector_ar.hypothesis_test_results.CausalityTestResults.summary statsmodels.tsa.vector\_ar.hypothesis\_test\_results.CausalityTestResults.summary ================================================================================= `CausalityTestResults.summary()` statsmodels statsmodels.regression.linear_model.OLSResults.f_test statsmodels.regression.linear\_model.OLSResults.f\_test ======================================================= `OLSResults.f_test(r_matrix, cov_p=None, scale=1.0, invcov=None)` Compute the F-test for a joint linear hypothesis. This is a special case of `wald_test` that always uses the F distribution. | Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) – + array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length k row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – Default is 1.0 for no scaling. * **invcov** (*array-like**,* *optional*) – A q x q array to specify an inverse covariance matrix based on a restrictions matrix. | | Returns: | **res** – The results for the test are attributes of this results instance. | | Return type: | ContrastResults instance | #### Examples ``` >>> import numpy as np >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> A = np.identity(len(results.params)) >>> A = A[1:,:] ``` This tests that each coefficient is jointly statistically significantly different from zero. ``` >>> print(results.f_test(A)) <F test: F=array([[ 330.28533923]]), p=4.984030528700946e-10, df_denom=9, df_num=6> ``` Compare this to ``` >>> results.fvalue 330.2853392346658 >>> results.f_pvalue 4.98403096572e-10 ``` ``` >>> B = np.array(([0,0,1,-1,0,0,0],[0,0,0,0,0,1,-1])) ``` This tests that the coefficient on the 2nd and 3rd regressors are equal and jointly that the coefficient on the 5th and 6th regressors are equal. ``` >>> print(results.f_test(B)) <F test: F=array([[ 9.74046187]]), p=0.005605288531708235, df_denom=9, df_num=2> ``` Alternatively, you can specify the hypothesis tests using a string ``` >>> from statsmodels.datasets import longley >>> from statsmodels.formula.api import ols >>> dta = longley.load_pandas().data >>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' >>> results = ols(formula, dta).fit() >>> hypotheses = '(GNPDEFL = GNP), (UNEMP = 2), (YEAR/1829 = 1)' >>> f_test = results.f_test(hypotheses) >>> print(f_test) <F test: F=array([[ 144.17976065]]), p=6.322026217355609e-08, df_denom=9, df_num=3> ``` See also [`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`wald_test`](statsmodels.regression.linear_model.olsresults.wald_test#statsmodels.regression.linear_model.OLSResults.wald_test "statsmodels.regression.linear_model.OLSResults.wald_test"), [`t_test`](statsmodels.regression.linear_model.olsresults.t_test#statsmodels.regression.linear_model.OLSResults.t_test "statsmodels.regression.linear_model.OLSResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") #### Notes The matrix `r_matrix` is assumed to be non-singular. More precisely, r\_matrix (pX pX.T) r\_matrix.T is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full. statsmodels statsmodels.regression.recursive_ls.RecursiveLS.loglike statsmodels.regression.recursive\_ls.RecursiveLS.loglike ======================================================== `RecursiveLS.loglike(params, *args, **kwargs)` Loglikelihood evaluation | Parameters: | * **params** (*array\_like*) – Array of parameters at which to evaluate the loglikelihood function. * **transformed** (*boolean**,* *optional*) – Whether or not `params` is already transformed. Default is True. * **kwargs** – Additional keyword arguments to pass to the Kalman filter. See `KalmanFilter.filter` for more details. | #### Notes [[1]](#id2) recommend maximizing the average likelihood to avoid scale issues; this is done automatically by the base Model fit method. #### References | | | | --- | --- | | [[1]](#id1) | Koopman, Siem Jan, Neil Shephard, and Jurgen A. Doornik. 1999. Statistical Algorithms for Models in State Space Using SsfPack 2.2. Econometrics Journal 2 (1): 107-60. doi:10.1111/1368-423X.00023. | See also [`update`](statsmodels.regression.recursive_ls.recursivels.update#statsmodels.regression.recursive_ls.RecursiveLS.update "statsmodels.regression.recursive_ls.RecursiveLS.update") modifies the internal state of the state space model to reflect new params statsmodels statsmodels.tsa.stattools.grangercausalitytests statsmodels.tsa.stattools.grangercausalitytests =============================================== `statsmodels.tsa.stattools.grangercausalitytests(x, maxlag, addconst=True, verbose=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/stattools.html#grangercausalitytests) four tests for granger non causality of 2 timeseries all four tests give similar results `params_ftest` and `ssr_ftest` are equivalent based on F test which is identical to lmtest:grangertest in R | Parameters: | * **x** (*array**,* *2d*) – data for test whether the time series in the second column Granger causes the time series in the first column * **maxlag** (*integer*) – the Granger causality test results are calculated for all lags up to maxlag * **verbose** (*bool*) – print results if true | | Returns: | **results** – all test results, dictionary keys are the number of lags. For each lag the values are a tuple, with the first element a dictionary with teststatistic, pvalues, degrees of freedom, the second element are the OLS estimation results for the restricted model, the unrestricted model and the restriction (contrast) matrix for the parameter f\_test. | | Return type: | dictionary | #### Notes TODO: convert to class and attach results properly The Null hypothesis for grangercausalitytests is that the time series in the second column, x2, does NOT Granger cause the time series in the first column, x1. Grange causality means that past values of x2 have a statistically significant effect on the current value of x1, taking past values of x1 into account as regressors. We reject the null hypothesis that x2 does not Granger cause x1 if the pvalues are below a desired size of the test. The null hypothesis for all four test is that the coefficients corresponding to past values of the second time series are zero. ‘params\_ftest’, ‘ssr\_ftest’ are based on F distribution ‘ssr\_chi2test’, ‘lrtest’ are based on chi-square distribution #### References <http://en.wikipedia.org/wiki/Granger_causality> Greene: Econometric Analysis
programming_docs
statsmodels statsmodels.regression.mixed_linear_model.MixedLMResults.random_effects statsmodels.regression.mixed\_linear\_model.MixedLMResults.random\_effects ========================================================================== `MixedLMResults.random_effects()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/mixed_linear_model.html#MixedLMResults.random_effects) The conditional means of random effects given the data. | Returns: | **random\_effects** – A dictionary mapping the distinct `group` values to the conditional means of the random effects for the group given the data. | | Return type: | [dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)") | statsmodels statsmodels.iolib.table.SimpleTable.as_text statsmodels.iolib.table.SimpleTable.as\_text ============================================ `SimpleTable.as_text(**fmt_dict)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/iolib/table.html#SimpleTable.as_text) Return string, the table as text. statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.aic statsmodels.sandbox.regression.gmm.IVRegressionResults.aic ========================================================== `IVRegressionResults.aic()` statsmodels statsmodels.robust.robust_linear_model.RLMResults.wald_test_terms statsmodels.robust.robust\_linear\_model.RLMResults.wald\_test\_terms ===================================================================== `RLMResults.wald_test_terms(skip_single=False, extra_constraints=None, combine_terms=None)` Compute a sequence of Wald tests for terms over multiple columns This computes joined Wald tests for the hypothesis that all coefficients corresponding to a `term` are zero. `Terms` are defined by the underlying formula or by string matching. | Parameters: | * **skip\_single** (*boolean*) – If true, then terms that consist only of a single column and, therefore, refers only to a single parameter is skipped. If false, then all terms are included. * **extra\_constraints** (*ndarray*) – not tested yet * **combine\_terms** (*None* *or* *list of strings*) – Each string in this list is matched to the name of the terms or the name of the exogenous variables. All columns whose name includes that string are combined in one joint test. | | Returns: | **test\_result** – The result instance contains `table` which is a pandas DataFrame with the test results: test statistic, degrees of freedom and pvalues. | | Return type: | result instance | #### Examples ``` >>> res_ols = ols("np.log(Days+1) ~ C(Duration, Sum)*C(Weight, Sum)", data).fit() >>> res_ols.wald_test_terms() <class 'statsmodels.stats.contrast.WaldTestResults'> F P>F df constraint df denom Intercept 279.754525 2.37985521351e-22 1 51 C(Duration, Sum) 5.367071 0.0245738436636 1 51 C(Weight, Sum) 12.432445 3.99943118767e-05 2 51 C(Duration, Sum):C(Weight, Sum) 0.176002 0.83912310946 2 51 ``` ``` >>> res_poi = Poisson.from_formula("Days ~ C(Weight) * C(Duration)", data).fit(cov_type='HC0') >>> wt = res_poi.wald_test_terms(skip_single=False, combine_terms=['Duration', 'Weight']) >>> print(wt) chi2 P>chi2 df constraint Intercept 15.695625 7.43960374424e-05 1 C(Weight) 16.132616 0.000313940174705 2 C(Duration) 1.009147 0.315107378931 1 C(Weight):C(Duration) 0.216694 0.897315972824 2 Duration 11.187849 0.010752286833 3 Weight 30.263368 4.32586407145e-06 4 ``` statsmodels statsmodels.stats.weightstats._zconfint_generic statsmodels.stats.weightstats.\_zconfint\_generic ================================================= `statsmodels.stats.weightstats._zconfint_generic(mean, std_mean, alpha, alternative)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/weightstats.html#_zconfint_generic) generic normal-confint to save typing statsmodels statsmodels.genmod.generalized_estimating_equations.GEEResults.resid_working statsmodels.genmod.generalized\_estimating\_equations.GEEResults.resid\_working =============================================================================== `GEEResults.resid_working()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_estimating_equations.html#GEEResults.resid_working) statsmodels statsmodels.regression.linear_model.GLSAR.score statsmodels.regression.linear\_model.GLSAR.score ================================================ `GLSAR.score(params)` Score vector of model. The gradient of logL with respect to each parameter. statsmodels statsmodels.genmod.families.family.Gaussian.resid_dev statsmodels.genmod.families.family.Gaussian.resid\_dev ====================================================== `Gaussian.resid_dev(endog, mu, var_weights=1.0, scale=1.0)` The deviance residuals | Parameters: | * **endog** (*array-like*) – The endogenous response variable * **mu** (*array-like*) – The inverse of the link function at the linear predicted values. * **var\_weights** (*array-like*) – 1d array of variance (analytic) weights. The default is 1. * **scale** (*float**,* *optional*) – An optional scale argument. The default is 1. | | Returns: | **resid\_dev** – Deviance residuals as defined below. | | Return type: | float | #### Notes The deviance residuals are defined by the contribution D\_i of observation i to the deviance as \[resid\\_dev\_i = sign(y\_i-\mu\_i) \sqrt{D\_i}\] D\_i is calculated from the \_resid\_dev method in each family. Distribution-specific documentation of the calculation is available there. statsmodels statsmodels.tsa.statespace.sarimax.SARIMAXResults.arroots statsmodels.tsa.statespace.sarimax.SARIMAXResults.arroots ========================================================= `SARIMAXResults.arroots()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/sarimax.html#SARIMAXResults.arroots) (array) Roots of the reduced form autoregressive lag polynomial statsmodels statsmodels.tsa.statespace.mlemodel.MLEModel.set_smoother_output statsmodels.tsa.statespace.mlemodel.MLEModel.set\_smoother\_output ================================================================== `MLEModel.set_smoother_output(smoother_output=None, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEModel.set_smoother_output) Set the smoother output The smoother can produce several types of results. The smoother output variable controls which are calculated and returned. | Parameters: | * **smoother\_output** (*integer**,* *optional*) – Bitmask value to set the smoother output to. See notes for details. * **\*\*kwargs** – Keyword arguments may be used to influence the smoother output by setting individual boolean flags. | #### Notes This method is rarely used. See the corresponding function in the `KalmanSmoother` class for details. statsmodels statsmodels.tsa.vector_ar.vecm.VECM.loglike statsmodels.tsa.vector\_ar.vecm.VECM.loglike ============================================ `VECM.loglike(params)` Log-likelihood of model. statsmodels statsmodels.duration.hazard_regression.PHRegResults.t_test_pairwise statsmodels.duration.hazard\_regression.PHRegResults.t\_test\_pairwise ====================================================================== `PHRegResults.t_test_pairwise(term_name, method='hs', alpha=0.05, factor_labels=None)` perform pairwise t\_test with multiple testing corrected p-values This uses the formula design\_info encoding contrast matrix and should work for all encodings of a main effect. | Parameters: | * **result** (*result instance*) – The results of an estimated model with a categorical main effect. * **term\_name** (*str*) – name of the term for which pairwise comparisons are computed. Term names for categorical effects are created by patsy and correspond to the main part of the exog names. * **method** (*str* *or* *list of strings*) – multiple testing p-value correction, default is ‘hs’, see stats.multipletesting * **alpha** (*float*) – significance level for multiple testing reject decision. * **factor\_labels** (*None**,* *list of str*) – Labels for the factor levels used for pairwise labels. If not provided, then the labels from the formula design\_info are used. | | Returns: | **results** – The results are stored as attributes, the main attributes are the following two. Other attributes are added for debugging purposes or as background information.* result\_frame : pandas DataFrame with t\_test results and multiple testing corrected p-values. * contrasts : matrix of constraints of the null hypothesis in the t\_test. | | Return type: | instance of a simple Results class | #### Notes Status: experimental. Currently only checked for treatment coding with and without specified reference level. Currently there are no multiple testing corrected confidence intervals available. #### Examples ``` >>> res = ols("np.log(Days+1) ~ C(Weight) + C(Duration)", data).fit() >>> pw = res.t_test_pairwise("C(Weight)") >>> pw.result_frame coef std err t P>|t| Conf. Int. Low 2-1 0.632315 0.230003 2.749157 8.028083e-03 0.171563 3-1 1.302555 0.230003 5.663201 5.331513e-07 0.841803 3-2 0.670240 0.230003 2.914044 5.119126e-03 0.209488 Conf. Int. Upp. pvalue-hs reject-hs 2-1 1.093067 0.010212 True 3-1 1.763307 0.000002 True 3-2 1.130992 0.010212 True ``` statsmodels statsmodels.tsa.statespace.structural.UnobservedComponentsResults.plot_diagnostics statsmodels.tsa.statespace.structural.UnobservedComponentsResults.plot\_diagnostics =================================================================================== `UnobservedComponentsResults.plot_diagnostics(variable=0, lags=10, fig=None, figsize=None)` Diagnostic plots for standardized residuals of one endogenous variable | Parameters: | * **variable** (*integer**,* *optional*) – Index of the endogenous variable for which the diagnostic plots should be created. Default is 0. * **lags** (*integer**,* *optional*) – Number of lags to include in the correlogram. Default is 10. * **fig** (*Matplotlib Figure instance**,* *optional*) – If given, subplots are created in this figure instead of in a new figure. Note that the 2x2 grid will be created in the provided figure using `fig.add_subplot()`. * **figsize** (*tuple**,* *optional*) – If a figure is created, this argument allows specifying a size. The tuple is (width, height). | #### Notes Produces a 2x2 plot grid with the following plots (ordered clockwise from top left): 1. Standardized residuals over time 2. Histogram plus estimated density of standardized residulas, along with a Normal(0,1) density plotted for reference. 3. Normal Q-Q plot, with Normal reference line. 4. Correlogram See also [`statsmodels.graphics.gofplots.qqplot`](statsmodels.graphics.gofplots.qqplot#statsmodels.graphics.gofplots.qqplot "statsmodels.graphics.gofplots.qqplot"), [`statsmodels.graphics.tsaplots.plot_acf`](statsmodels.graphics.tsaplots.plot_acf#statsmodels.graphics.tsaplots.plot_acf "statsmodels.graphics.tsaplots.plot_acf") statsmodels statsmodels.tsa.arima_model.ARIMAResults.bse statsmodels.tsa.arima\_model.ARIMAResults.bse ============================================= `ARIMAResults.bse()` statsmodels statsmodels.tsa.holtwinters.ExponentialSmoothing.fit statsmodels.tsa.holtwinters.ExponentialSmoothing.fit ==================================================== `ExponentialSmoothing.fit(smoothing_level=None, smoothing_slope=None, smoothing_seasonal=None, damping_slope=None, optimized=True, use_boxcox=False, remove_bias=False, use_basinhopping=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/holtwinters.html#ExponentialSmoothing.fit) fit Holt Winter’s Exponential Smoothing | Parameters: | * **smoothing\_level** (*float**,* *optional*) – The alpha value of the simple exponential smoothing, if the value is set then this value will be used as the value. * **smoothing\_slope** (*float**,* *optional*) – The beta value of the holts trend method, if the value is set then this value will be used as the value. * **smoothing\_seasonal** (*float**,* *optional*) – The gamma value of the holt winters seasonal method, if the value is set then this value will be used as the value. * **damping\_slope** (*float**,* *optional*) – The phi value of the damped method, if the value is set then this value will be used as the value. * **optimized** (*bool**,* *optional*) – Should the values that have not been set above be optimized automatically? * **use\_boxcox** (*{True**,* *False**,* *'log'**,* *float}**,* *optional*) – Should the boxcox tranform be applied to the data first? If ‘log’ then apply the log. If float then use lambda equal to float. * **remove\_bias** (*bool**,* *optional*) – Should the bias be removed from the forecast values and fitted values before being returned? Does this by enforcing average residuals equal to zero. * **use\_basinhopping** (*bool**,* *optional*) – Should the opptimser try harder using basinhopping to find optimal values? | | Returns: | **results** – See statsmodels.tsa.holtwinters.HoltWintersResults | | Return type: | HoltWintersResults class | #### Notes This is a full implementation of the holt winters exponential smoothing as per [1]. This includes all the unstable methods as well as the stable methods. The implementation of the library covers the functionality of the R library as much as possible whilst still being pythonic. #### References [1] Hyndman, Rob J., and George Athanasopoulos. Forecasting: principles and practice. OTexts, 2014. statsmodels statsmodels.discrete.discrete_model.GeneralizedPoissonResults.set_null_options statsmodels.discrete.discrete\_model.GeneralizedPoissonResults.set\_null\_options ================================================================================= `GeneralizedPoissonResults.set_null_options(llnull=None, attach_results=True, **kwds)` set fit options for Null (constant-only) model This resets the cache for related attributes which is potentially fragile. This only sets the option, the null model is estimated when llnull is accessed, if llnull is not yet in cache. | Parameters: | * **llnull** (*None* *or* *float*) – If llnull is not None, then the value will be directly assigned to the cached attribute “llnull”. * **attach\_results** (*bool*) – Sets an internal flag whether the results instance of the null model should be attached. By default without calling this method, thenull model results are not attached and only the loglikelihood value llnull is stored. * **kwds** (*keyword arguments*) – `kwds` are directly used as fit keyword arguments for the null model, overriding any provided defaults. | | Returns: | | | Return type: | no returns, modifies attributes of this instance | statsmodels statsmodels.discrete.discrete_model.ProbitResults.pred_table statsmodels.discrete.discrete\_model.ProbitResults.pred\_table ============================================================== `ProbitResults.pred_table(threshold=0.5)` Prediction table | Parameters: | **threshold** (*scalar*) – Number between 0 and 1. Threshold above which a prediction is considered 1 and below which a prediction is considered 0. | #### Notes pred\_table[i,j] refers to the number of times “i” was observed and the model predicted “j”. Correct predictions are along the diagonal. statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.initialize statsmodels.sandbox.regression.gmm.IVRegressionResults.initialize ================================================================= `IVRegressionResults.initialize(model, params, **kwd)` statsmodels statsmodels.discrete.count_model.ZeroInflatedPoissonResults.resid statsmodels.discrete.count\_model.ZeroInflatedPoissonResults.resid ================================================================== `ZeroInflatedPoissonResults.resid()` Residuals #### Notes The residuals for Count models are defined as \[y - p\] where \(p = \exp(X\beta)\). Any exposure and offset variables are also handled. statsmodels statsmodels.stats.contingency_tables.Table2x2.fittedvalues statsmodels.stats.contingency\_tables.Table2x2.fittedvalues =========================================================== `Table2x2.fittedvalues()` statsmodels statsmodels.miscmodels.count.PoissonOffsetGMLE statsmodels.miscmodels.count.PoissonOffsetGMLE ============================================== `class statsmodels.miscmodels.count.PoissonOffsetGMLE(endog, exog=None, offset=None, missing='none', **kwds)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/miscmodels/count.html#PoissonOffsetGMLE) Maximum Likelihood Estimation of Poisson Model This is an example for generic MLE which has the same statistical model as discretemod.Poisson but adds offset Except for defining the negative log-likelihood method, all methods and results are generic. Gradients and Hessian and all resulting statistics are based on numerical differentiation. #### Methods | | | | --- | --- | | [`expandparams`](statsmodels.miscmodels.count.poissonoffsetgmle.expandparams#statsmodels.miscmodels.count.PoissonOffsetGMLE.expandparams "statsmodels.miscmodels.count.PoissonOffsetGMLE.expandparams")(params) | expand to full parameter array when some parameters are fixed | | [`fit`](statsmodels.miscmodels.count.poissonoffsetgmle.fit#statsmodels.miscmodels.count.PoissonOffsetGMLE.fit "statsmodels.miscmodels.count.PoissonOffsetGMLE.fit")([start\_params, method, maxiter, …]) | Fit the model using maximum likelihood. | | [`from_formula`](statsmodels.miscmodels.count.poissonoffsetgmle.from_formula#statsmodels.miscmodels.count.PoissonOffsetGMLE.from_formula "statsmodels.miscmodels.count.PoissonOffsetGMLE.from_formula")(formula, data[, subset, drop\_cols]) | Create a Model from a formula and dataframe. | | [`hessian`](statsmodels.miscmodels.count.poissonoffsetgmle.hessian#statsmodels.miscmodels.count.PoissonOffsetGMLE.hessian "statsmodels.miscmodels.count.PoissonOffsetGMLE.hessian")(params) | Hessian of log-likelihood evaluated at params | | [`hessian_factor`](statsmodels.miscmodels.count.poissonoffsetgmle.hessian_factor#statsmodels.miscmodels.count.PoissonOffsetGMLE.hessian_factor "statsmodels.miscmodels.count.PoissonOffsetGMLE.hessian_factor")(params[, scale, observed]) | Weights for calculating Hessian | | [`information`](statsmodels.miscmodels.count.poissonoffsetgmle.information#statsmodels.miscmodels.count.PoissonOffsetGMLE.information "statsmodels.miscmodels.count.PoissonOffsetGMLE.information")(params) | Fisher information matrix of model | | [`initialize`](statsmodels.miscmodels.count.poissonoffsetgmle.initialize#statsmodels.miscmodels.count.PoissonOffsetGMLE.initialize "statsmodels.miscmodels.count.PoissonOffsetGMLE.initialize")() | Initialize (possibly re-initialize) a Model instance. | | [`loglike`](statsmodels.miscmodels.count.poissonoffsetgmle.loglike#statsmodels.miscmodels.count.PoissonOffsetGMLE.loglike "statsmodels.miscmodels.count.PoissonOffsetGMLE.loglike")(params) | Log-likelihood of model. | | [`loglikeobs`](statsmodels.miscmodels.count.poissonoffsetgmle.loglikeobs#statsmodels.miscmodels.count.PoissonOffsetGMLE.loglikeobs "statsmodels.miscmodels.count.PoissonOffsetGMLE.loglikeobs")(params) | | | [`nloglike`](statsmodels.miscmodels.count.poissonoffsetgmle.nloglike#statsmodels.miscmodels.count.PoissonOffsetGMLE.nloglike "statsmodels.miscmodels.count.PoissonOffsetGMLE.nloglike")(params) | | | [`nloglikeobs`](statsmodels.miscmodels.count.poissonoffsetgmle.nloglikeobs#statsmodels.miscmodels.count.PoissonOffsetGMLE.nloglikeobs "statsmodels.miscmodels.count.PoissonOffsetGMLE.nloglikeobs")(params) | Loglikelihood of Poisson model | | [`predict`](statsmodels.miscmodels.count.poissonoffsetgmle.predict#statsmodels.miscmodels.count.PoissonOffsetGMLE.predict "statsmodels.miscmodels.count.PoissonOffsetGMLE.predict")(params[, exog]) | After a model has been fit predict returns the fitted values. | | [`reduceparams`](statsmodels.miscmodels.count.poissonoffsetgmle.reduceparams#statsmodels.miscmodels.count.PoissonOffsetGMLE.reduceparams "statsmodels.miscmodels.count.PoissonOffsetGMLE.reduceparams")(params) | | | [`score`](statsmodels.miscmodels.count.poissonoffsetgmle.score#statsmodels.miscmodels.count.PoissonOffsetGMLE.score "statsmodels.miscmodels.count.PoissonOffsetGMLE.score")(params) | Gradient of log-likelihood evaluated at params | | [`score_obs`](statsmodels.miscmodels.count.poissonoffsetgmle.score_obs#statsmodels.miscmodels.count.PoissonOffsetGMLE.score_obs "statsmodels.miscmodels.count.PoissonOffsetGMLE.score_obs")(params, \*\*kwds) | Jacobian/Gradient of log-likelihood evaluated at params for each observation. | #### Attributes | | | | --- | --- | | `endog_names` | Names of endogenous variables | | `exog_names` | Names of exogenous variables |
programming_docs
statsmodels statsmodels.multivariate.pca.PCA statsmodels.multivariate.pca.PCA ================================ `class statsmodels.multivariate.pca.PCA(data, ncomp=None, standardize=True, demean=True, normalize=True, gls=False, weights=None, method='svd', missing=None, tol=5e-08, max_iter=1000, tol_em=5e-08, max_em_iter=100)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/multivariate/pca.html#PCA) Principal Component Analysis | Parameters: | * **data** (*array-like*) – Variables in columns, observations in rows * **ncomp** (*int**,* *optional*) – Number of components to return. If None, returns the as many as the smaller of the number of rows or columns in data * **standardize** (*bool**,* *optional*) – Flag indicating to use standardized data with mean 0 and unit variance. standardized being True implies demean. Using standardized data is equivalent to computing principal components from the correlation matrix of data * **demean** (*bool**,* *optional*) – Flag indicating whether to demean data before computing principal components. demean is ignored if standardize is True. Demeaning data but not standardizing is equivalent to computing principal components from the covariance matrix of data * **normalize** (*bool* *,* *optional*) – Indicates whether th normalize the factors to have unit inner product. If False, the loadings will have unit inner product. * **weights** (*array**,* *optional*) – Series weights to use after transforming data according to standardize or demean when computing the principal components. * **gls** (*bool**,* *optional*) – Flag indicating to implement a two-step GLS estimator where in the first step principal components are used to estimate residuals, and then the inverse residual variance is used as a set of weights to estimate the final principal components. Setting gls to True requires ncomp to be less then the min of the number of rows or columns * **method** (*str**,* *optional*) – Sets the linear algebra routine used to compute eigenvectors ‘svd’ uses a singular value decomposition (default). ‘eig’ uses an eigenvalue decomposition of a quadratic form ‘nipals’ uses the NIPALS algorithm and can be faster than SVD when ncomp is small and nvars is large. See notes about additional changes when using NIPALS * **tol** (*float**,* *optional*) – Tolerance to use when checking for convergence when using NIPALS * **max\_iter** (*int**,* *optional*) – Maximum iterations when using NIPALS * **missing** (*string*) – Method for missing data. Choices are ‘drop-row’ - drop rows with missing values ‘drop-col’ - drop columns with missing values ‘drop-min’ - drop either rows or columns, choosing by data retention ‘fill-em’ - use EM algorithm to fill missing value. ncomp should be set to the number of factors required * **tol\_em** (*float*) – Tolerance to use when checking for convergence of the EM algorithm * **max\_em\_iter** (*int*) – Maximum iterations for the EM algorithm | `factors` *array or DataFrame* – nobs by ncomp array of of principal components (scores) `scores` *array or DataFrame* – nobs by ncomp array of of principal components - identical to factors `loadings` *array or DataFrame* – ncomp by nvar array of principal component loadings for constructing the factors `coeff` *array or DataFrame* – nvar by ncomp array of principal component loadings for constructing the projections `projection` *array or DataFrame* – nobs by var array containing the projection of the data onto the ncomp estimated factors `rsquare` *array or Series* – ncomp array where the element in the ith position is the R-square of including the fist i principal components. Note: values are calculated on the transformed data, not the original data `ic` *array or DataFrame* – ncomp by 3 array containing the Bai and Ng (2003) Information criteria. Each column is a different criteria, and each row represents the number of included factors. `eigenvals` *array or Series* – nvar array of eigenvalues `eigenvecs` *array or DataFrame* – nvar by nvar array of eigenvectors `weights` *array* – nvar array of weights used to compute the principal components, normalized to unit length `transformed_data` *array* – Standardized, demeaned and weighted data used to compute principal components and related quantities `cols` *array* – Array of indices indicating columns used in the PCA `rows` *array* – Array of indices indicating rows used in the PCA #### Examples Basic PCA using the correlation matrix of the data ``` >>> import numpy as np >>> from statsmodels.multivariate.pca import PCA >>> x = np.random.randn(100)[:, None] >>> x = x + np.random.randn(100, 100) >>> pc = PCA(x) ``` Note that the principal components are computed using a SVD and so the correlation matrix is never constructed, unless method=’eig’. PCA using the covariance matrix of the data ``` >>> pc = PCA(x, standardize=False) ``` Limiting the number of factors returned to 1 computed using NIPALS ``` >>> pc = PCA(x, ncomp=1, method='nipals') >>> pc.factors.shape (100, 1) ``` #### Notes The default options perform principal component analysis on the demeanded, unit variance version of data. Setting standardize to False will instead onle demean, and setting both standardized and demean to False will not alter the data. Once the data have been transformed, the following relationships hold when the number of components (ncomp) is the same as tne minimum of the number of observation or the number of variables. where X is the `data`, F is the array of principal components (`factors` or `scores`), and V is the array of eigenvectors (`loadings`) and V’ is the array of factor coefficients (`coeff`). When weights are provided, the principal components are computed from the modified data where \(\Omega\) is a diagonal matrix composed of the weights. For example, when using the GLS version of PCA, the elements of \(\Omega\) will be the inverse of the variances of the residuals from where the number of factors is less than the rank of X | | | | --- | --- | | [\*] | J. Bai and S. Ng, “Determining the number of factors in approximate factor models,” Econometrica, vol. 70, number 1, pp. 191-221, 2002 | #### Methods | | | | --- | --- | | [`plot_rsquare`](statsmodels.multivariate.pca.pca.plot_rsquare#statsmodels.multivariate.pca.PCA.plot_rsquare "statsmodels.multivariate.pca.PCA.plot_rsquare")([ncomp, ax]) | Box plots of the individual series R-square against the number of PCs | | [`plot_scree`](statsmodels.multivariate.pca.pca.plot_scree#statsmodels.multivariate.pca.PCA.plot_scree "statsmodels.multivariate.pca.PCA.plot_scree")([ncomp, log\_scale, cumulative, ax]) | Plot of the ordered eigenvalues | | [`project`](statsmodels.multivariate.pca.pca.project#statsmodels.multivariate.pca.PCA.project "statsmodels.multivariate.pca.PCA.project")([ncomp, transform, unweight]) | Project series onto a specific number of factors | statsmodels statsmodels.genmod.bayes_mixed_glm.PoissonBayesMixedGLM.fit statsmodels.genmod.bayes\_mixed\_glm.PoissonBayesMixedGLM.fit ============================================================= `PoissonBayesMixedGLM.fit()` Fit a model to data. statsmodels statsmodels.genmod.families.family.InverseGaussian.fitted statsmodels.genmod.families.family.InverseGaussian.fitted ========================================================= `InverseGaussian.fitted(lin_pred)` Fitted values based on linear predictors lin\_pred. | Parameters: | **lin\_pred** (*array*) – Values of the linear predictor of the model. \(X \cdot \beta\) in a classical linear model. | | Returns: | **mu** – The mean response variables given by the inverse of the link function. | | Return type: | array | statsmodels statsmodels.sandbox.distributions.transformed.LogTransf_gen.var statsmodels.sandbox.distributions.transformed.LogTransf\_gen.var ================================================================ `LogTransf_gen.var(*args, **kwds)` Variance of the distribution. | Parameters: | * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **var** – the variance of the distribution | | Return type: | float | statsmodels statsmodels.regression.mixed_linear_model.MixedLMResults.save statsmodels.regression.mixed\_linear\_model.MixedLMResults.save =============================================================== `MixedLMResults.save(fname, remove_data=False)` save a pickle of this instance | Parameters: | * **fname** (*string* *or* *filehandle*) – fname can be a string to a file path or filename, or a filehandle. * **remove\_data** (*bool*) – If False (default), then the instance is pickled without changes. If True, then all arrays with length nobs are set to None before pickling. See the remove\_data method. In some cases not all arrays will be set to None. | #### Notes If remove\_data is true and the model result does not implement a remove\_data method then this will raise an exception. statsmodels statsmodels.iolib.table.SimpleTable.get_colwidths statsmodels.iolib.table.SimpleTable.get\_colwidths ================================================== `SimpleTable.get_colwidths(output_format, **fmt_dict)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/iolib/table.html#SimpleTable.get_colwidths) Return list, the widths of each column. statsmodels statsmodels.tsa.holtwinters.HoltWintersResults statsmodels.tsa.holtwinters.HoltWintersResults ============================================== `class statsmodels.tsa.holtwinters.HoltWintersResults(model, params, **kwds)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/holtwinters.html#HoltWintersResults) Holt Winter’s Exponential Smoothing Results | Parameters: | * **model** (*ExponentialSmoothing instance*) – The fitted model instance * **params** (*dictionary*) – All the parameters for the Exponential Smoothing model. | `specification` *dictionary* – Dictionary including all attributes from the VARMAX model instance. `params` *dictionary* – All the parameters for the Exponential Smoothing model. `fittedfcast` *array* – An array of both the fitted values and forecast values. `fittedvalues` *array* – An array of the fitted values. Fitted by the Exponential Smoothing model. `fcast` *array* – An array of the forecast values forecast by the Exponential Smoothing model. `sse` *float* – The sum of squared errors `level` *array* – An array of the levels values that make up the fitted values. `slope` *array* – An array of the slope values that make up the fitted values. `season` *array* – An array of the seaonal values that make up the fitted values. `aic` *float* – The Akaike information criterion. `bic` *float* – The Bayesian information criterion. `aicc` *float* – AIC with a correction for finite sample sizes. `resid` *array* – An array of the residuals of the fittedvalues and actual values. `k` *int* – the k parameter used to remove the bias in AIC, BIC etc. #### Methods | | | | --- | --- | | [`forecast`](statsmodels.tsa.holtwinters.holtwintersresults.forecast#statsmodels.tsa.holtwinters.HoltWintersResults.forecast "statsmodels.tsa.holtwinters.HoltWintersResults.forecast")([steps]) | Out-of-sample forecasts | | [`initialize`](statsmodels.tsa.holtwinters.holtwintersresults.initialize#statsmodels.tsa.holtwinters.HoltWintersResults.initialize "statsmodels.tsa.holtwinters.HoltWintersResults.initialize")(model, params, \*\*kwd) | | | [`predict`](statsmodels.tsa.holtwinters.holtwintersresults.predict#statsmodels.tsa.holtwinters.HoltWintersResults.predict "statsmodels.tsa.holtwinters.HoltWintersResults.predict")([start, end]) | In-sample prediction and out-of-sample forecasting | | [`summary`](statsmodels.tsa.holtwinters.holtwintersresults.summary#statsmodels.tsa.holtwinters.HoltWintersResults.summary "statsmodels.tsa.holtwinters.HoltWintersResults.summary")() | | statsmodels statsmodels.sandbox.regression.gmm.GMM.gmmobjective statsmodels.sandbox.regression.gmm.GMM.gmmobjective =================================================== `GMM.gmmobjective(params, weights)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#GMM.gmmobjective) objective function for GMM minimization | Parameters: | * **params** (*array*) – parameter values at which objective is evaluated * **weights** (*array*) – weighting matrix | | Returns: | **jval** – value of objective function | | Return type: | float | statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.tvalues statsmodels.sandbox.regression.gmm.IVRegressionResults.tvalues ============================================================== `IVRegressionResults.tvalues()` Return the t-statistic for a given parameter estimate. statsmodels statsmodels.tsa.filters.bk_filter.bkfilter statsmodels.tsa.filters.bk\_filter.bkfilter =========================================== `statsmodels.tsa.filters.bk_filter.bkfilter(X, low=6, high=32, K=12)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/filters/bk_filter.html#bkfilter) Baxter-King bandpass filter | Parameters: | * **X** (*array-like*) – A 1 or 2d ndarray. If 2d, variables are assumed to be in columns. * **low** (*float*) – Minimum period for oscillations, ie., Baxter and King suggest that the Burns-Mitchell U.S. business cycle has 6 for quarterly data and 1.5 for annual data. * **high** (*float*) – Maximum period for oscillations BK suggest that the U.S. business cycle has 32 for quarterly data and 8 for annual data. * **K** (*int*) – Lead-lag length of the filter. Baxter and King propose a truncation length of 12 for quarterly data and 3 for annual data. | | Returns: | * **Y** (*array*) – Cyclical component of X * *References* * *———- ::* * **Baxter, M. and R. G. King. “Measuring Business Cycles** (*Approximate*) – Band-Pass Filters for Economic Time Series.” *Review of Economics and Statistics*, 1999, 81(4), 575-593. | #### Notes Returns a centered weighted moving average of the original series. Where the weights a[j] are computed ``` a[j] = b[j] + theta, for j = 0, +/-1, +/-2, ... +/- K b[0] = (omega_2 - omega_1)/pi b[j] = 1/(pi*j)(sin(omega_2*j)-sin(omega_1*j), for j = +/-1, +/-2,... ``` and theta is a normalizing constant ``` theta = -sum(b)/(2K+1) ``` #### Examples ``` >>> import statsmodels.api as sm >>> import pandas as pd >>> dta = sm.datasets.macrodata.load_pandas().data >>> index = pd.DatetimeIndex(start='1959Q1', end='2009Q4', freq='Q') >>> dta.set_index(index, inplace=True) ``` ``` >>> cycles = sm.tsa.filters.bkfilter(dta[['realinv']], 6, 24, 12) ``` ``` >>> import matplotlib.pyplot as plt >>> fig, ax = plt.subplots() >>> cycles.plot(ax=ax, style=['r--', 'b-']) >>> plt.show() ``` ([Source code](../plots/bkf_plot.py), [png](../plots/bkf_plot.png), [hires.png](../plots/bkf_plot.hires.png), [pdf](../plots/bkf_plot.pdf)) See also [`statsmodels.tsa.filters.cf_filter.cffilter`](statsmodels.tsa.filters.cf_filter.cffilter#statsmodels.tsa.filters.cf_filter.cffilter "statsmodels.tsa.filters.cf_filter.cffilter"), [`statsmodels.tsa.filters.hp_filter.hpfilter`](statsmodels.tsa.filters.hp_filter.hpfilter#statsmodels.tsa.filters.hp_filter.hpfilter "statsmodels.tsa.filters.hp_filter.hpfilter"), [`statsmodels.tsa.seasonal.seasonal_decompose`](statsmodels.tsa.seasonal.seasonal_decompose#statsmodels.tsa.seasonal.seasonal_decompose "statsmodels.tsa.seasonal.seasonal_decompose") statsmodels statsmodels.genmod.generalized_linear_model.GLMResults.llf statsmodels.genmod.generalized\_linear\_model.GLMResults.llf ============================================================ `GLMResults.llf()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_linear_model.html#GLMResults.llf) statsmodels statsmodels.stats.outliers_influence.OLSInfluence.resid_std statsmodels.stats.outliers\_influence.OLSInfluence.resid\_std ============================================================= `OLSInfluence.resid_std()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/outliers_influence.html#OLSInfluence.resid_std) (cached attribute) estimate of standard deviation of the residuals See also [`resid_var`](statsmodels.stats.outliers_influence.olsinfluence.resid_var#statsmodels.stats.outliers_influence.OLSInfluence.resid_var "statsmodels.stats.outliers_influence.OLSInfluence.resid_var") statsmodels statsmodels.tsa.statespace.structural.UnobservedComponents.loglike statsmodels.tsa.statespace.structural.UnobservedComponents.loglike ================================================================== `UnobservedComponents.loglike(params, *args, **kwargs)` Loglikelihood evaluation | Parameters: | * **params** (*array\_like*) – Array of parameters at which to evaluate the loglikelihood function. * **transformed** (*boolean**,* *optional*) – Whether or not `params` is already transformed. Default is True. * **kwargs** – Additional keyword arguments to pass to the Kalman filter. See `KalmanFilter.filter` for more details. | #### Notes [[1]](#id2) recommend maximizing the average likelihood to avoid scale issues; this is done automatically by the base Model fit method. #### References | | | | --- | --- | | [[1]](#id1) | Koopman, Siem Jan, Neil Shephard, and Jurgen A. Doornik. 1999. Statistical Algorithms for Models in State Space Using SsfPack 2.2. Econometrics Journal 2 (1): 107-60. doi:10.1111/1368-423X.00023. | See also [`update`](statsmodels.tsa.statespace.structural.unobservedcomponents.update#statsmodels.tsa.statespace.structural.UnobservedComponents.update "statsmodels.tsa.statespace.structural.UnobservedComponents.update") modifies the internal state of the state space model to reflect new params statsmodels statsmodels.sandbox.regression.try_ols_anova.form2design statsmodels.sandbox.regression.try\_ols\_anova.form2design ========================================================== `statsmodels.sandbox.regression.try_ols_anova.form2design(ss, data)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/try_ols_anova.html#form2design) convert string formula to data dictionary `ss : string` * I : add constant * varname : for simple varnames data is used as is * F:varname : create dummy variables for factor varname * P:varname1\*varname2 : create product dummy variables for varnames * G:varname1\*varname2 : create product between factor and continuous variable `data : dict or structured array` data set, access of variables by name as in dictionaries | Returns: | * **vars** (*dictionary*) – dictionary of variables with converted dummy variables * **names** (*list*) – list of names, product (P:) and grouped continuous variables (G:) have name by joining individual names sorted according to input | #### Examples ``` >>> xx, n = form2design('I a F:b P:c*d G:c*f', testdata) >>> xx.keys() ['a', 'b', 'const', 'cf', 'cd'] >>> n ['const', 'a', 'b', 'cd', 'cf'] ``` #### Notes with sorted dict, separate name list wouldn’t be necessary statsmodels statsmodels.multivariate.multivariate_ols.MultivariateTestResults.summary statsmodels.multivariate.multivariate\_ols.MultivariateTestResults.summary ========================================================================== `MultivariateTestResults.summary(show_contrast_L=False, show_transform_M=False, show_constant_C=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/multivariate/multivariate_ols.html#MultivariateTestResults.summary) | Parameters: | * **contrast\_L** (*True* *or* *False*) – Whether to show contrast\_L matrix * **transform\_M** (*True* *or* *False*) – Whether to show transform\_M matrix |
programming_docs
statsmodels statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults statsmodels.discrete.count\_model.ZeroInflatedGeneralizedPoissonResults ======================================================================= `class statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults(model, mlefit, cov_type='nonrobust', cov_kwds=None, use_t=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/count_model.html#ZeroInflatedGeneralizedPoissonResults) A results class for Zero Inflated Generalized Poisson | Parameters: | * **model** (*A DiscreteModel instance*) – * **params** (*array-like*) – The parameters of a fitted model. * **hessian** (*array-like*) – The hessian of the fitted model. * **scale** (*float*) – A scale parameter for the covariance matrix. | | Returns: | * *\*Attributes\** * **aic** (*float*) – Akaike information criterion. `-2*(llf - p)` where `p` is the number of regressors including the intercept. * **bic** (*float*) – Bayesian information criterion. `-2*llf + ln(nobs)*p` where `p` is the number of regressors including the intercept. * **bse** (*array*) – The standard errors of the coefficients. * **df\_resid** (*float*) – See model definition. * **df\_model** (*float*) – See model definition. * **fitted\_values** (*array*) – Linear predictor XB. * **llf** (*float*) – Value of the loglikelihood * **llnull** (*float*) – Value of the constant-only loglikelihood * **llr** (*float*) – Likelihood ratio chi-squared statistic; `-2*(llnull - llf)` * **llr\_pvalue** (*float*) – The chi-squared probability of getting a log-likelihood ratio statistic greater than llr. llr has a chi-squared distribution with degrees of freedom `df_model`. * **prsquared** (*float*) – McFadden’s pseudo-R-squared. `1 - (llf / llnull)` | #### Methods | | | | --- | --- | | [`aic`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoissonresults.aic#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.aic "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.aic")() | | | [`bic`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoissonresults.bic#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.bic "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.bic")() | | | [`bse`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoissonresults.bse#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.bse "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.bse")() | | | [`conf_int`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoissonresults.conf_int#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.conf_int "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.conf_int")([alpha, cols, method]) | Returns the confidence interval of the fitted parameters. | | [`cov_params`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoissonresults.cov_params#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.cov_params "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.cov_params")([r\_matrix, column, scale, cov\_p, …]) | Returns the variance/covariance matrix. | | [`f_test`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoissonresults.f_test#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.f_test "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.f_test")(r\_matrix[, cov\_p, scale, invcov]) | Compute the F-test for a joint linear hypothesis. | | [`fittedvalues`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoissonresults.fittedvalues#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.fittedvalues "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.fittedvalues")() | | | [`get_margeff`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoissonresults.get_margeff#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.get_margeff "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.get_margeff")([at, method, atexog, dummy, count]) | Get marginal effects of the fitted model. | | [`initialize`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoissonresults.initialize#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.initialize "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.initialize")(model, params, \*\*kwd) | | | [`llf`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoissonresults.llf#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.llf "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.llf")() | | | [`llnull`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoissonresults.llnull#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.llnull "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.llnull")() | | | [`llr`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoissonresults.llr#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.llr "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.llr")() | | | [`llr_pvalue`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoissonresults.llr_pvalue#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.llr_pvalue "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.llr_pvalue")() | | | [`load`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoissonresults.load#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.load "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.load")(fname) | load a pickle, (class method) | | [`normalized_cov_params`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoissonresults.normalized_cov_params#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.normalized_cov_params "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.normalized_cov_params")() | | | [`predict`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoissonresults.predict#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.predict "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.predict")([exog, transform]) | Call self.model.predict with self.params as the first argument. | | [`prsquared`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoissonresults.prsquared#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.prsquared "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.prsquared")() | | | [`pvalues`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoissonresults.pvalues#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.pvalues "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.pvalues")() | | | [`remove_data`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoissonresults.remove_data#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.remove_data "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.remove_data")() | remove data arrays, all nobs arrays from result and model | | [`resid`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoissonresults.resid#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.resid "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.resid")() | Residuals | | [`save`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoissonresults.save#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.save "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.save")(fname[, remove\_data]) | save a pickle of this instance | | [`set_null_options`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoissonresults.set_null_options#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.set_null_options "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.set_null_options")([llnull, attach\_results]) | set fit options for Null (constant-only) model | | [`summary`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoissonresults.summary#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.summary "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.summary")([yname, xname, title, alpha, yname\_list]) | Summarize the Regression Results | | [`summary2`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoissonresults.summary2#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.summary2 "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.summary2")([yname, xname, title, alpha, …]) | Experimental function to summarize regression results | | [`t_test`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoissonresults.t_test#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.t_test "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.t_test")(r\_matrix[, cov\_p, scale, use\_t]) | Compute a t-test for a each linear hypothesis of the form Rb = q | | [`t_test_pairwise`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoissonresults.t_test_pairwise#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.t_test_pairwise "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.t_test_pairwise")(term\_name[, method, alpha, …]) | perform pairwise t\_test with multiple testing corrected p-values | | [`tvalues`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoissonresults.tvalues#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.tvalues "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.tvalues")() | Return the t-statistic for a given parameter estimate. | | [`wald_test`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoissonresults.wald_test#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.wald_test "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.wald_test")(r\_matrix[, cov\_p, scale, invcov, …]) | Compute a Wald-test for a joint linear hypothesis. | | [`wald_test_terms`](statsmodels.discrete.count_model.zeroinflatedgeneralizedpoissonresults.wald_test_terms#statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.wald_test_terms "statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.wald_test_terms")([skip\_single, …]) | Compute a sequence of Wald tests for terms over multiple columns | #### Attributes | | | | --- | --- | | `use_t` | | statsmodels statsmodels.sandbox.regression.gmm.LinearIVGMM.score statsmodels.sandbox.regression.gmm.LinearIVGMM.score ==================================================== `LinearIVGMM.score(params, weights, **kwds)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#LinearIVGMM.score) statsmodels statsmodels.genmod.families.family.Binomial.starting_mu statsmodels.genmod.families.family.Binomial.starting\_mu ======================================================== `Binomial.starting_mu(y)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/family.html#Binomial.starting_mu) The starting values for the IRLS algorithm for the Binomial family. A good choice for the binomial family is \(\mu\_0 = (Y\_i + 0.5)/2\) statsmodels statsmodels.stats.proportion.power_binom_tost statsmodels.stats.proportion.power\_binom\_tost =============================================== `statsmodels.stats.proportion.power_binom_tost(low, upp, nobs, p_alt=None, alpha=0.05)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/proportion.html#power_binom_tost) statsmodels statsmodels.tsa.statespace.sarimax.SARIMAXResults.seasonalarparams statsmodels.tsa.statespace.sarimax.SARIMAXResults.seasonalarparams ================================================================== `SARIMAXResults.seasonalarparams()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/sarimax.html#SARIMAXResults.seasonalarparams) (array) Seasonal autoregressive parameters actually estimated in the model. Does not include nonseasonal autoregressive parameters (see `arparams`) or parameters whose values are constrained to be zero. statsmodels statsmodels.sandbox.distributions.extras.SkewNorm_gen.logpdf statsmodels.sandbox.distributions.extras.SkewNorm\_gen.logpdf ============================================================= `SkewNorm_gen.logpdf(x, *args, **kwds)` Log of the probability density function at x of the given RV. This uses a more numerically accurate calculation if available. | Parameters: | * **x** (*array\_like*) – quantiles * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **logpdf** – Log of the probability density function evaluated at x | | Return type: | array\_like | statsmodels statsmodels.tsa.statespace.structural.UnobservedComponentsResults.bic statsmodels.tsa.statespace.structural.UnobservedComponentsResults.bic ===================================================================== `UnobservedComponentsResults.bic()` (float) Bayes Information Criterion statsmodels statsmodels.distributions.empirical_distribution.monotone_fn_inverter statsmodels.distributions.empirical\_distribution.monotone\_fn\_inverter ======================================================================== `statsmodels.distributions.empirical_distribution.monotone_fn_inverter(fn, x, vectorized=True, **keywords)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/distributions/empirical_distribution.html#monotone_fn_inverter) Given a monotone function fn (no checking is done to verify monotonicity) and a set of x values, return an linearly interpolated approximation to its inverse from its values on x. statsmodels statsmodels.tsa.statespace.structural.UnobservedComponents.initialize_state statsmodels.tsa.statespace.structural.UnobservedComponents.initialize\_state ============================================================================ `UnobservedComponents.initialize_state()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/structural.html#UnobservedComponents.initialize_state) statsmodels statsmodels.tsa.statespace.mlemodel.MLEResults.cov_params_robust_oim statsmodels.tsa.statespace.mlemodel.MLEResults.cov\_params\_robust\_oim ======================================================================= `MLEResults.cov_params_robust_oim()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEResults.cov_params_robust_oim) (array) The QMLE variance / covariance matrix. Computed using the method from Harvey (1989) as the evaluated hessian. statsmodels statsmodels.tsa.statespace.mlemodel.MLEModel.score_obs statsmodels.tsa.statespace.mlemodel.MLEModel.score\_obs ======================================================= `MLEModel.score_obs(params, method='approx', transformed=True, approx_complex_step=None, approx_centered=False, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEModel.score_obs) Compute the score per observation, evaluated at params | Parameters: | * **params** (*array\_like*) – Array of parameters at which to evaluate the score. * **kwargs** – Additional arguments to the `loglike` method. | | Returns: | **score** – Score per observation, evaluated at `params`. | | Return type: | array | #### Notes This is a numerical approximation, calculated using first-order complex step differentiation on the `loglikeobs` method. statsmodels statsmodels.miscmodels.count.PoissonZiGMLE.hessian statsmodels.miscmodels.count.PoissonZiGMLE.hessian ================================================== `PoissonZiGMLE.hessian(params)` Hessian of log-likelihood evaluated at params statsmodels statsmodels.regression.linear_model.OLSResults.compare_lr_test statsmodels.regression.linear\_model.OLSResults.compare\_lr\_test ================================================================= `OLSResults.compare_lr_test(restricted, large_sample=False)` Likelihood ratio test to test whether restricted model is correct | Parameters: | * **restricted** (*Result instance*) – The restricted model is assumed to be nested in the current model. The result instance of the restricted model is required to have two attributes, residual sum of squares, `ssr`, residual degrees of freedom, `df_resid`. * **large\_sample** (*bool*) – Flag indicating whether to use a heteroskedasticity robust version of the LR test, which is a modified LM test. | | Returns: | * **lr\_stat** (*float*) – likelihood ratio, chisquare distributed with df\_diff degrees of freedom * **p\_value** (*float*) – p-value of the test statistic * **df\_diff** (*int*) – degrees of freedom of the restriction, i.e. difference in df between models | #### Notes The exact likelihood ratio is valid for homoskedastic data, and is defined as \[D=-2\log\left(\frac{\mathcal{L}\_{null}} {\mathcal{L}\_{alternative}}\right)\] where \(\mathcal{L}\) is the likelihood of the model. With \(D\) distributed as chisquare with df equal to difference in number of parameters or equivalently difference in residual degrees of freedom. The large sample version of the likelihood ratio is defined as \[D=n s^{\prime}S^{-1}s\] where \(s=n^{-1}\sum\_{i=1}^{n} s\_{i}\) \[s\_{i} = x\_{i,alternative} \epsilon\_{i,null}\] is the average score of the model evaluated using the residuals from null model and the regressors from the alternative model and \(S\) is the covariance of the scores, \(s\_{i}\). The covariance of the scores is estimated using the same estimator as in the alternative model. This test compares the loglikelihood of the two models. This may not be a valid test, if there is unspecified heteroscedasticity or correlation. This method will issue a warning if this is detected but still return the results without taking unspecified heteroscedasticity or correlation into account. This test compares the loglikelihood of the two models. This may not be a valid test, if there is unspecified heteroscedasticity or correlation. This method will issue a warning if this is detected but still return the results without taking unspecified heteroscedasticity or correlation into account. is the average score of the model evaluated using the residuals from null model and the regressors from the alternative model and \(S\) is the covariance of the scores, \(s\_{i}\). The covariance of the scores is estimated using the same estimator as in the alternative model. TODO: put into separate function, needs tests statsmodels statsmodels.robust.norms.LeastSquares.psi_deriv statsmodels.robust.norms.LeastSquares.psi\_deriv ================================================ `LeastSquares.psi_deriv(z)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/norms.html#LeastSquares.psi_deriv) The derivative of the least squares psi function. | Returns: | **psi\_deriv** – ones(z.shape) | | Return type: | array | #### Notes Used to estimate the robust covariance matrix. statsmodels statsmodels.sandbox.stats.multicomp.rankdata statsmodels.sandbox.stats.multicomp.rankdata ============================================ `statsmodels.sandbox.stats.multicomp.rankdata(x)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/multicomp.html#rankdata) rankdata, equivalent to scipy.stats.rankdata just a different implementation, I have not yet compared speed
programming_docs
statsmodels statsmodels.tsa.varma_process.VarmaPoly.hstack statsmodels.tsa.varma\_process.VarmaPoly.hstack =============================================== `VarmaPoly.hstack(a=None, name='ar')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/varma_process.html#VarmaPoly.hstack) stack lagpolynomial horizontally in 2d array statsmodels statsmodels.genmod.generalized_estimating_equations.GEEResults.initialize statsmodels.genmod.generalized\_estimating\_equations.GEEResults.initialize =========================================================================== `GEEResults.initialize(model, params, **kwd)` statsmodels statsmodels.sandbox.tsa.movstat.movorder statsmodels.sandbox.tsa.movstat.movorder ======================================== `statsmodels.sandbox.tsa.movstat.movorder(x, order='med', windsize=3, lag='lagged')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/tsa/movstat.html#movorder) moving order statistics | Parameters: | * **x** (*array*) – time series data * **order** (*float* *or* *'med'**,* *'min'**,* *'max'*) – which order statistic to calculate * **windsize** (*int*) – window size * **lag** (*'lagged'**,* *'centered'**, or* *'leading'*) – location of window relative to current position | | Returns: | | | Return type: | filtered array | statsmodels statsmodels.regression.linear_model.OLSResults.mse_model statsmodels.regression.linear\_model.OLSResults.mse\_model ========================================================== `OLSResults.mse_model()` statsmodels statsmodels.sandbox.distributions.transformed.LogTransf_gen.pdf statsmodels.sandbox.distributions.transformed.LogTransf\_gen.pdf ================================================================ `LogTransf_gen.pdf(x, *args, **kwds)` Probability density function at x of the given RV. | Parameters: | * **x** (*array\_like*) – quantiles * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **pdf** – Probability density function evaluated at x | | Return type: | ndarray | statsmodels statsmodels.tsa.arima_process.arma2ma statsmodels.tsa.arima\_process.arma2ma ====================================== `statsmodels.tsa.arima_process.arma2ma(ar, ma, lags=100, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_process.html#arma2ma) Get the MA representation of an ARMA process | Parameters: | * **ar** (*array\_like**,* *1d*) – auto regressive lag polynomial * **ma** (*array\_like**,* *1d*) – moving average lag polynomial * **lags** (*int*) – number of coefficients to calculate | | Returns: | **ar** – coefficients of AR lag polynomial with nobs elements | | Return type: | array, 1d | #### Notes Equivalent to `arma_impulse_response(ma, ar, leads=100)` #### Examples statsmodels statsmodels.genmod.generalized_estimating_equations.GEE.update_cached_means statsmodels.genmod.generalized\_estimating\_equations.GEE.update\_cached\_means =============================================================================== `GEE.update_cached_means(mean_params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_estimating_equations.html#GEE.update_cached_means) cached\_means should always contain the most recent calculation of the group-wise mean vectors. This function should be called every time the regression parameters are changed, to keep the cached means up to date. statsmodels statsmodels.discrete.discrete_model.NegativeBinomialResults.lnalpha_std_err statsmodels.discrete.discrete\_model.NegativeBinomialResults.lnalpha\_std\_err ============================================================================== `NegativeBinomialResults.lnalpha_std_err()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#NegativeBinomialResults.lnalpha_std_err) statsmodels statsmodels.tsa.statespace.varmax.VARMAX.simulation_smoother statsmodels.tsa.statespace.varmax.VARMAX.simulation\_smoother ============================================================= `VARMAX.simulation_smoother(simulation_output=None, **kwargs)` Retrieve a simulation smoother for the state space model. | Parameters: | * **simulation\_output** (*int**,* *optional*) – Determines which simulation smoother output is calculated. Default is all (including state and disturbances). * **\*\*kwargs** – Additional keyword arguments, used to set the simulation output. See `set_simulation_output` for more details. | | Returns: | | | Return type: | SimulationSmoothResults | statsmodels statsmodels.regression.quantile_regression.QuantRegResults.cov_HC1 statsmodels.regression.quantile\_regression.QuantRegResults.cov\_HC1 ==================================================================== `QuantRegResults.cov_HC1()` See statsmodels.RegressionResults statsmodels statsmodels.tsa.statespace.mlemodel.MLEResults.test_normality statsmodels.tsa.statespace.mlemodel.MLEResults.test\_normality ============================================================== `MLEResults.test_normality(method)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEResults.test_normality) Test for normality of standardized residuals. Null hypothesis is normality. | Parameters: | **method** (*string {'jarquebera'}* *or* *None*) – The statistical test for normality. Must be ‘jarquebera’ for Jarque-Bera normality test. If None, an attempt is made to select an appropriate test. | #### Notes If the first `d` loglikelihood values were burned (i.e. in the specified model, `loglikelihood_burn=d`), then this test is calculated ignoring the first `d` residuals. In the case of missing data, the maintained hypothesis is that the data are missing completely at random. This test is then run on the standardized residuals excluding those corresponding to missing observations. See also [`statsmodels.stats.stattools.jarque_bera`](statsmodels.stats.stattools.jarque_bera#statsmodels.stats.stattools.jarque_bera "statsmodels.stats.stattools.jarque_bera") statsmodels statsmodels.tsa.statespace.sarimax.SARIMAXResults.load statsmodels.tsa.statespace.sarimax.SARIMAXResults.load ====================================================== `classmethod SARIMAXResults.load(fname)` load a pickle, (class method) | Parameters: | **fname** (*string* *or* *filehandle*) – fname can be a string to a file path or filename, or a filehandle. | | Returns: | | | Return type: | unpickled instance | statsmodels statsmodels.genmod.bayes_mixed_glm.BinomialBayesMixedGLM.vb_elbo_grad_base statsmodels.genmod.bayes\_mixed\_glm.BinomialBayesMixedGLM.vb\_elbo\_grad\_base =============================================================================== `BinomialBayesMixedGLM.vb_elbo_grad_base(h, tm, tv, fep_mean, vcp_mean, vc_mean, fep_sd, vcp_sd, vc_sd)` Return the gradient of the ELBO function. See vb\_elbo\_base for parameters. statsmodels statsmodels.iolib.foreign.savetxt statsmodels.iolib.foreign.savetxt ================================= `statsmodels.iolib.foreign.savetxt(fname, X, names=None, fmt='%.18e', delimiter=' ')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/iolib/foreign.html#savetxt) Save an array to a text file. This is just a copy of numpy.savetxt patched to support structured arrays or a header of names. Does not include py3 support now in savetxt. | Parameters: | * **fname** (*filename* *or* *file handle*) – If the filename ends in `.gz`, the file is automatically saved in compressed gzip format. `loadtxt` understands gzipped files transparently. * **X** (*array\_like*) – Data to be saved to a text file. * **names** (*list**,* *optional*) – If given names will be the column header in the text file. If None and X is a structured or recarray then the names are taken from X.dtype.names. * **fmt** (*str* *or* *sequence of strs*) – A single format (%10.5f), a sequence of formats, or a multi-format string, e.g. ‘Iteration %d – %10.5f’, in which case `delimiter` is ignored. * **delimiter** (*str*) – Character separating columns. | See also `save` Save an array to a binary file in NumPy `.npy` format `savez` Save several arrays into a `.npz` compressed archive #### Notes Further explanation of the `fmt` parameter (`%[flag]width[.precision]specifier`): flags: `-` : left justify `+` : Forces to preceed result with + or -. `0` : Left pad the number with zeros instead of space (see width). width: Minimum number of characters to be printed. The value is not truncated if it has more characters. precision: * For integer specifiers (eg. `d,i,o,x`), the minimum number of digits. * For `e, E` and `f` specifiers, the number of digits to print after the decimal point. * For `g` and `G`, the maximum number of significant digits. * For `s`, the maximum number of characters. specifiers: `c` : character `d` or `i` : signed decimal integer `e` or `E` : scientific notation with `e` or `E`. `f` : decimal floating point `g,G` : use the shorter of `e,E` or `f` `o` : signed octal `s` : string of characters `u` : unsigned decimal integer `x,X` : unsigned hexadecimal integer This explanation of `fmt` is not complete, for an exhaustive specification see [[1]](#id2). #### References | | | | --- | --- | | [[1]](#id1) | [Format Specification Mini-Language](http://docs.python.org/library/string.html#format-specification-mini-language), Python Documentation. | #### Examples ``` >>> savetxt('test.out', x, delimiter=',') # x is an array >>> savetxt('test.out', (x,y,z)) # x,y,z equal sized 1D arrays >>> savetxt('test.out', x, fmt='%1.4e') # use exponential notation ``` statsmodels statsmodels.regression.mixed_linear_model.MixedLM.loglike statsmodels.regression.mixed\_linear\_model.MixedLM.loglike =========================================================== `MixedLM.loglike(params, profile_fe=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/mixed_linear_model.html#MixedLM.loglike) Evaluate the (profile) log-likelihood of the linear mixed effects model. | Parameters: | * **params** (*MixedLMParams**, or* *array-like.*) – The parameter value. If array-like, must be a packed parameter vector containing only the covariance parameters. * **profile\_fe** (*boolean*) – If True, replace the provided value of `fe_params` with the GLS estimates. | | Returns: | | | Return type: | The log-likelihood value at `params`. | #### Notes The scale parameter `scale` is always profiled out of the log-likelihood. In addition, if `profile_fe` is true the fixed effects parameters are also profiled out. statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.get_prediction statsmodels.sandbox.regression.gmm.IVRegressionResults.get\_prediction ====================================================================== `IVRegressionResults.get_prediction(exog=None, transform=True, weights=None, row_labels=None, **kwds)` compute prediction results | Parameters: | * **exog** (*array-like**,* *optional*) – The values for which you want to predict. * **transform** (*bool**,* *optional*) – If the model was fit via a formula, do you want to pass exog through the formula. Default is True. E.g., if you fit a model y ~ log(x1) + log(x2), and transform is True, then you can pass a data structure that contains x1 and x2 in their original form. Otherwise, you’d need to log the data first. * **weights** (*array\_like**,* *optional*) – Weights interpreted as in WLS, used for the variance of the predicted residual. * **kwargs** (*args**,*) – Some models can take additional arguments or keywords, see the predict method of the model for the details. | | Returns: | **prediction\_results** – The prediction results instance contains prediction and prediction variance and can on demand calculate confidence intervals and summary tables for the prediction of the mean and of new observations. | | Return type: | [linear\_model.PredictionResults](statsmodels.regression.linear_model.predictionresults#statsmodels.regression.linear_model.PredictionResults "statsmodels.regression.linear_model.PredictionResults") | statsmodels statsmodels.tsa.statespace.mlemodel.MLEResults.initialize statsmodels.tsa.statespace.mlemodel.MLEResults.initialize ========================================================= `MLEResults.initialize(model, params, **kwd)` statsmodels statsmodels.discrete.discrete_model.LogitResults.pred_table statsmodels.discrete.discrete\_model.LogitResults.pred\_table ============================================================= `LogitResults.pred_table(threshold=0.5)` Prediction table | Parameters: | **threshold** (*scalar*) – Number between 0 and 1. Threshold above which a prediction is considered 1 and below which a prediction is considered 0. | #### Notes pred\_table[i,j] refers to the number of times “i” was observed and the model predicted “j”. Correct predictions are along the diagonal. statsmodels statsmodels.tsa.ar_model.AR.select_order statsmodels.tsa.ar\_model.AR.select\_order ========================================== `AR.select_order(maxlag, ic, trend='c', method='mle')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/ar_model.html#AR.select_order) Select the lag order according to the information criterion. | Parameters: | * **maxlag** (*int*) – The highest lag length tried. See `AR.fit`. * **ic** (*str {'aic'**,**'bic'**,**'hqic'**,**'t-stat'}*) – Criterion used for selecting the optimal lag length. See `AR.fit`. * **trend** (*str {'c'**,**'nc'}*) – Whether to include a constant or not. ‘c’ - include constant. ‘nc’ - no constant. | | Returns: | **bestlag** – Best lag according to IC. | | Return type: | int | statsmodels statsmodels.discrete.count_model.ZeroInflatedPoissonResults.cov_params statsmodels.discrete.count\_model.ZeroInflatedPoissonResults.cov\_params ======================================================================== `ZeroInflatedPoissonResults.cov_params(r_matrix=None, column=None, scale=None, cov_p=None, other=None)` Returns the variance/covariance matrix. The variance/covariance matrix can be of a linear contrast of the estimates of params or all params multiplied by scale which will usually be an estimate of sigma^2. Scale is assumed to be a scalar. | Parameters: | * **r\_matrix** (*array-like*) – Can be 1d, or 2d. Can be used alone or with other. * **column** (*array-like**,* *optional*) – Must be used on its own. Can be 0d or 1d see below. * **scale** (*float**,* *optional*) – Can be specified or not. Default is None, which means that the scale argument is taken from the model. * **other** (*array-like**,* *optional*) – Can be used when r\_matrix is specified. | | Returns: | **cov** – covariance matrix of the parameter estimates or of linear combination of parameter estimates. See Notes. | | Return type: | ndarray | #### Notes (The below are assumed to be in matrix notation.) If no argument is specified returns the covariance matrix of a model `(scale)*(X.T X)^(-1)` If contrast is specified it pre and post-multiplies as follows `(scale) * r_matrix (X.T X)^(-1) r_matrix.T` If contrast and other are specified returns `(scale) * r_matrix (X.T X)^(-1) other.T` If column is specified returns `(scale) * (X.T X)^(-1)[column,column]` if column is 0d OR `(scale) * (X.T X)^(-1)[column][:,column]` if column is 1d statsmodels statsmodels.discrete.discrete_model.ProbitResults.llnull statsmodels.discrete.discrete\_model.ProbitResults.llnull ========================================================= `ProbitResults.llnull()` statsmodels statsmodels.tsa.vector_ar.vecm.VECMResults.fittedvalues statsmodels.tsa.vector\_ar.vecm.VECMResults.fittedvalues ======================================================== `VECMResults.fittedvalues()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/vecm.html#VECMResults.fittedvalues) Return the in-sample values of endog calculated by the model. | Returns: | **fitted** – The predicted in-sample values of the models’ endogenous variables. | | Return type: | array (nobs x neqs) | statsmodels statsmodels.multivariate.factor.FactorResults statsmodels.multivariate.factor.FactorResults ============================================= `class statsmodels.multivariate.factor.FactorResults(factor)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/multivariate/factor.html#FactorResults) Factor results class For result summary, scree/loading plots and factor rotations | Parameters: | **factor** ([Factor](statsmodels.multivariate.factor.factor#statsmodels.multivariate.factor.Factor "statsmodels.multivariate.factor.Factor")) – Fitted Factor class | `uniqueness` *ndarray* – The uniqueness (variance of uncorrelated errors unique to each variable) `communality` *ndarray* – 1 - uniqueness `loadings` *ndarray* – Each column is the loading vector for one factor `loadings_no_rot` *ndarray* – Unrotated loadings, not available under maximum likelihood analyis. `eigenvalues` *ndarray* – The eigenvalues for a factor analysis obtained using principal components; not available under ML estimation. `n_comp` *int* – Number of components (factors) `nbs` *int* – Number of observations `fa_method` *string* – The method used to obtain the decomposition, either ‘pa’ for ‘principal axes’ or ‘ml’ for maximum likelihood. `df` *int* – Degrees of freedom of the factor model. #### Notes Under ML estimation, the default rotation (used for `loadings`) is condition IC3 of Bai and Li (2012). Under this rotation, the factor scores are iid and standardized. If `G` is the canonical loadings and `U` is the vector of uniquenesses, then the covariance matrix implied by the factor analysis is `GG’ + diag(U)`. Status: experimental, Some refactoring will be necessary when new features are added. #### Methods | | | | --- | --- | | [`factor_score_params`](statsmodels.multivariate.factor.factorresults.factor_score_params#statsmodels.multivariate.factor.FactorResults.factor_score_params "statsmodels.multivariate.factor.FactorResults.factor_score_params")([method]) | compute factor scoring coefficient matrix | | [`factor_scoring`](statsmodels.multivariate.factor.factorresults.factor_scoring#statsmodels.multivariate.factor.FactorResults.factor_scoring "statsmodels.multivariate.factor.FactorResults.factor_scoring")([endog, method, transform]) | factor scoring: compute factors for endog | | [`fitted_cov`](statsmodels.multivariate.factor.factorresults.fitted_cov#statsmodels.multivariate.factor.FactorResults.fitted_cov "statsmodels.multivariate.factor.FactorResults.fitted_cov")() | Returns the fitted covariance matrix. | | [`get_loadings_frame`](statsmodels.multivariate.factor.factorresults.get_loadings_frame#statsmodels.multivariate.factor.FactorResults.get_loadings_frame "statsmodels.multivariate.factor.FactorResults.get_loadings_frame")([style, sort\_, …]) | get loadings matrix as DataFrame or pandas Styler | | [`load_stderr`](statsmodels.multivariate.factor.factorresults.load_stderr#statsmodels.multivariate.factor.FactorResults.load_stderr "statsmodels.multivariate.factor.FactorResults.load_stderr")() | The standard errors of the loadings. | | [`plot_loadings`](statsmodels.multivariate.factor.factorresults.plot_loadings#statsmodels.multivariate.factor.FactorResults.plot_loadings "statsmodels.multivariate.factor.FactorResults.plot_loadings")([loading\_pairs, plot\_prerotated]) | Plot factor loadings in 2-d plots | | [`plot_scree`](statsmodels.multivariate.factor.factorresults.plot_scree#statsmodels.multivariate.factor.FactorResults.plot_scree "statsmodels.multivariate.factor.FactorResults.plot_scree")([ncomp]) | Plot of the ordered eigenvalues and variance explained for the loadings | | [`rotate`](statsmodels.multivariate.factor.factorresults.rotate#statsmodels.multivariate.factor.FactorResults.rotate "statsmodels.multivariate.factor.FactorResults.rotate")(method) | Apply rotation, inplace modification of this Results instance | | [`summary`](statsmodels.multivariate.factor.factorresults.summary#statsmodels.multivariate.factor.FactorResults.summary "statsmodels.multivariate.factor.FactorResults.summary")() | | | [`uniq_stderr`](statsmodels.multivariate.factor.factorresults.uniq_stderr#statsmodels.multivariate.factor.FactorResults.uniq_stderr "statsmodels.multivariate.factor.FactorResults.uniq_stderr")([kurt]) | The standard errors of the uniquenesses. |
programming_docs
statsmodels statsmodels.imputation.mice.MICEData.get_split_data statsmodels.imputation.mice.MICEData.get\_split\_data ===================================================== `MICEData.get_split_data(vname)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/imputation/mice.html#MICEData.get_split_data) Return endog and exog for imputation of a given variable. | Parameters: | **vname** (*string*) – The variable for which the split data is returned. | | Returns: | * **endog\_obs** (*DataFrame*) – Observed values of the variable to be imputed. * **exog\_obs** (*DataFrame*) – Current values of the predictors where the variable to be imputed is observed. * **exog\_miss** (*DataFrame*) – Current values of the predictors where the variable to be Imputed is missing. * **init\_kwds** (*dict-like*) – The init keyword arguments for `vname`, processed through Patsy as required. * **fit\_kwds** (*dict-like*) – The fit keyword arguments for `vname`, processed through Patsy as required. | statsmodels statsmodels.tsa.statespace.structural.UnobservedComponents.observed_information_matrix statsmodels.tsa.statespace.structural.UnobservedComponents.observed\_information\_matrix ======================================================================================== `UnobservedComponents.observed_information_matrix(params, transformed=True, approx_complex_step=None, approx_centered=False, **kwargs)` Observed information matrix | Parameters: | * **params** (*array\_like**,* *optional*) – Array of parameters at which to evaluate the loglikelihood function. * **\*\*kwargs** – Additional keyword arguments to pass to the Kalman filter. See `KalmanFilter.filter` for more details. | #### Notes This method is from Harvey (1989), which shows that the information matrix only depends on terms from the gradient. This implementation is partially analytic and partially numeric approximation, therefore, because it uses the analytic formula for the information matrix, with numerically computed elements of the gradient. #### References Harvey, Andrew C. 1990. Forecasting, Structural Time Series Models and the Kalman Filter. Cambridge University Press. statsmodels statsmodels.tsa.arima_model.ARIMAResults.bic statsmodels.tsa.arima\_model.ARIMAResults.bic ============================================= `ARIMAResults.bic()` statsmodels statsmodels.regression.linear_model.OLSResults.outlier_test statsmodels.regression.linear\_model.OLSResults.outlier\_test ============================================================= `OLSResults.outlier_test(method='bonf', alpha=0.05, labels=None, order=False, cutoff=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#OLSResults.outlier_test) Test observations for outliers according to method | Parameters: | * **method** (*str*) – + `bonferroni` : one-step correction + `sidak` : one-step correction + `holm-sidak` : + `holm` : + `simes-hochberg` : + `hommel` : + `fdr_bh` : Benjamini/Hochberg + `fdr_by` : Benjamini/YekutieliSee `statsmodels.stats.multitest.multipletests` for details. * **alpha** (*float*) – familywise error rate * **labels** (*None* *or* *array\_like*) – If `labels` is not None, then it will be used as index to the returned pandas DataFrame. See also Returns below * **order** (*bool*) – Whether or not to order the results by the absolute value of the studentized residuals. If labels are provided they will also be sorted. * **cutoff** (*None* *or* *float in* *[**0**,* *1**]*) – If cutoff is not None, then the return only includes observations with multiple testing corrected p-values strictly below the cutoff. The returned array or dataframe can be empty if t | | Returns: | **table** – Returns either an ndarray or a DataFrame if labels is not None. Will attempt to get labels from model\_results if available. The columns are the Studentized residuals, the unadjusted p-value, and the corrected p-value according to method. | | Return type: | ndarray or DataFrame | #### Notes The unadjusted p-value is stats.t.sf(abs(resid), df) where df = df\_resid - 1. statsmodels statsmodels.sandbox.regression.gmm.LinearIVGMM.predict statsmodels.sandbox.regression.gmm.LinearIVGMM.predict ====================================================== `LinearIVGMM.predict(params, exog=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#LinearIVGMM.predict) After a model has been fit predict returns the fitted values. This is a placeholder intended to be overwritten by individual models. statsmodels statsmodels.tsa.vector_ar.var_model.VARResults.long_run_effects statsmodels.tsa.vector\_ar.var\_model.VARResults.long\_run\_effects =================================================================== `VARResults.long_run_effects()` Compute long-run effect of unit impulse \[\Psi\_\infty = \sum\_{i=0}^\infty \Phi\_i\] statsmodels statsmodels.tsa.statespace.structural.UnobservedComponents.prepare_data statsmodels.tsa.statespace.structural.UnobservedComponents.prepare\_data ======================================================================== `UnobservedComponents.prepare_data()` Prepare data for use in the state space representation statsmodels statsmodels.tsa.statespace.varmax.VARMAX statsmodels.tsa.statespace.varmax.VARMAX ======================================== `class statsmodels.tsa.statespace.varmax.VARMAX(endog, exog=None, order=(1, 0), trend='c', error_cov_type='unstructured', measurement_error=False, enforce_stationarity=True, enforce_invertibility=True, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/varmax.html#VARMAX) Vector Autoregressive Moving Average with eXogenous regressors model | Parameters: | * **endog** (*array\_like*) – The observed time-series process \(y\), , shaped nobs x k\_endog. * **exog** (*array\_like**,* *optional*) – Array of exogenous regressors, shaped nobs x k. * **order** (*iterable*) – The (p,q) order of the model for the number of AR and MA parameters to use. * **trend** (*{'nc'**,* *'c'}**,* *optional*) – Parameter controlling the deterministic trend polynomial. Can be specified as a string where ‘c’ indicates a constant intercept and ‘nc’ indicates no intercept term. * **error\_cov\_type** (*{'diagonal'**,* *'unstructured'}**,* *optional*) – The structure of the covariance matrix of the error term, where “unstructured” puts no restrictions on the matrix and “diagonal” requires it to be a diagonal matrix (uncorrelated errors). Default is “unstructured”. * **measurement\_error** (*boolean**,* *optional*) – Whether or not to assume the endogenous observations `endog` were measured with error. Default is False. * **enforce\_stationarity** (*boolean**,* *optional*) – Whether or not to transform the AR parameters to enforce stationarity in the autoregressive component of the model. Default is True. * **enforce\_invertibility** (*boolean**,* *optional*) – Whether or not to transform the MA parameters to enforce invertibility in the moving average component of the model. Default is True. * **kwargs** – Keyword arguments may be used to provide default values for state space matrices or for Kalman filtering options. See `Representation`, and `KalmanFilter` for more details. | `order` *iterable* – The (p,q) order of the model for the number of AR and MA parameters to use. `trend` *{‘nc’, ‘c’}, optional* – Parameter controlling the deterministic trend polynomial. Can be specified as a string where ‘c’ indicates a constant intercept and ‘nc’ indicates no intercept term. `error_cov_type` *{‘diagonal’, ‘unstructured’}, optional* – The structure of the covariance matrix of the error term, where “unstructured” puts no restrictions on the matrix and “diagonal” requires it to be a diagonal matrix (uncorrelated errors). Default is “unstructured”. `measurement_error` *boolean, optional* – Whether or not to assume the endogenous observations `endog` were measured with error. Default is False. `enforce_stationarity` *boolean, optional* – Whether or not to transform the AR parameters to enforce stationarity in the autoregressive component of the model. Default is True. `enforce_invertibility` *boolean, optional* – Whether or not to transform the MA parameters to enforce invertibility in the moving average component of the model. Default is True. #### Notes Generically, the VARMAX model is specified (see for example chapter 18 of [[1]](#id3)): \[y\_t = \nu + A\_1 y\_{t-1} + \dots + A\_p y\_{t-p} + B x\_t + \epsilon\_t + M\_1 \epsilon\_{t-1} + \dots M\_q \epsilon\_{t-q}\] where \(\epsilon\_t \sim N(0, \Omega)\), and where \(y\_t\) is a `k_endog x 1` vector. Additionally, this model allows considering the case where the variables are measured with error. Note that in the full VARMA(p,q) case there is a fundamental identification problem in that the coefficient matrices \(\{A\_i, M\_j\}\) are not generally unique, meaning that for a given time series process there may be multiple sets of matrices that equivalently represent it. See Chapter 12 of [[1]](#id3) for more informationl. Although this class can be used to estimate VARMA(p,q) models, a warning is issued to remind users that no steps have been taken to ensure identification in this case. #### References | | | | --- | --- | | [1] | *([1](#id1), [2](#id2))* Lütkepohl, Helmut. 2007. New Introduction to Multiple Time Series Analysis. Berlin: Springer. | #### Methods | | | | --- | --- | | [`filter`](statsmodels.tsa.statespace.varmax.varmax.filter#statsmodels.tsa.statespace.varmax.VARMAX.filter "statsmodels.tsa.statespace.varmax.VARMAX.filter")(params[, transformed, complex\_step, …]) | Kalman filtering | | [`fit`](statsmodels.tsa.statespace.varmax.varmax.fit#statsmodels.tsa.statespace.varmax.VARMAX.fit "statsmodels.tsa.statespace.varmax.VARMAX.fit")([start\_params, transformed, cov\_type, …]) | Fits the model by maximum likelihood via Kalman filter. | | [`from_formula`](statsmodels.tsa.statespace.varmax.varmax.from_formula#statsmodels.tsa.statespace.varmax.VARMAX.from_formula "statsmodels.tsa.statespace.varmax.VARMAX.from_formula")(formula, data[, subset]) | Not implemented for state space models | | [`hessian`](statsmodels.tsa.statespace.varmax.varmax.hessian#statsmodels.tsa.statespace.varmax.VARMAX.hessian "statsmodels.tsa.statespace.varmax.VARMAX.hessian")(params, \*args, \*\*kwargs) | Hessian matrix of the likelihood function, evaluated at the given parameters | | [`impulse_responses`](statsmodels.tsa.statespace.varmax.varmax.impulse_responses#statsmodels.tsa.statespace.varmax.VARMAX.impulse_responses "statsmodels.tsa.statespace.varmax.VARMAX.impulse_responses")(params[, steps, impulse, …]) | Impulse response function | | [`information`](statsmodels.tsa.statespace.varmax.varmax.information#statsmodels.tsa.statespace.varmax.VARMAX.information "statsmodels.tsa.statespace.varmax.VARMAX.information")(params) | Fisher information matrix of model | | [`initialize`](statsmodels.tsa.statespace.varmax.varmax.initialize#statsmodels.tsa.statespace.varmax.VARMAX.initialize "statsmodels.tsa.statespace.varmax.VARMAX.initialize")() | Initialize (possibly re-initialize) a Model instance. | | [`initialize_approximate_diffuse`](statsmodels.tsa.statespace.varmax.varmax.initialize_approximate_diffuse#statsmodels.tsa.statespace.varmax.VARMAX.initialize_approximate_diffuse "statsmodels.tsa.statespace.varmax.VARMAX.initialize_approximate_diffuse")([variance]) | | | [`initialize_known`](statsmodels.tsa.statespace.varmax.varmax.initialize_known#statsmodels.tsa.statespace.varmax.VARMAX.initialize_known "statsmodels.tsa.statespace.varmax.VARMAX.initialize_known")(initial\_state, …) | | | [`initialize_statespace`](statsmodels.tsa.statespace.varmax.varmax.initialize_statespace#statsmodels.tsa.statespace.varmax.VARMAX.initialize_statespace "statsmodels.tsa.statespace.varmax.VARMAX.initialize_statespace")(\*\*kwargs) | Initialize the state space representation | | [`initialize_stationary`](statsmodels.tsa.statespace.varmax.varmax.initialize_stationary#statsmodels.tsa.statespace.varmax.VARMAX.initialize_stationary "statsmodels.tsa.statespace.varmax.VARMAX.initialize_stationary")() | | | [`loglike`](statsmodels.tsa.statespace.varmax.varmax.loglike#statsmodels.tsa.statespace.varmax.VARMAX.loglike "statsmodels.tsa.statespace.varmax.VARMAX.loglike")(params, \*args, \*\*kwargs) | Loglikelihood evaluation | | [`loglikeobs`](statsmodels.tsa.statespace.varmax.varmax.loglikeobs#statsmodels.tsa.statespace.varmax.VARMAX.loglikeobs "statsmodels.tsa.statespace.varmax.VARMAX.loglikeobs")(params[, transformed, complex\_step]) | Loglikelihood evaluation | | [`observed_information_matrix`](statsmodels.tsa.statespace.varmax.varmax.observed_information_matrix#statsmodels.tsa.statespace.varmax.VARMAX.observed_information_matrix "statsmodels.tsa.statespace.varmax.VARMAX.observed_information_matrix")(params[, …]) | Observed information matrix | | [`opg_information_matrix`](statsmodels.tsa.statespace.varmax.varmax.opg_information_matrix#statsmodels.tsa.statespace.varmax.VARMAX.opg_information_matrix "statsmodels.tsa.statespace.varmax.VARMAX.opg_information_matrix")(params[, …]) | Outer product of gradients information matrix | | [`predict`](statsmodels.tsa.statespace.varmax.varmax.predict#statsmodels.tsa.statespace.varmax.VARMAX.predict "statsmodels.tsa.statespace.varmax.VARMAX.predict")(params[, exog]) | After a model has been fit predict returns the fitted values. | | [`prepare_data`](statsmodels.tsa.statespace.varmax.varmax.prepare_data#statsmodels.tsa.statespace.varmax.VARMAX.prepare_data "statsmodels.tsa.statespace.varmax.VARMAX.prepare_data")() | Prepare data for use in the state space representation | | [`score`](statsmodels.tsa.statespace.varmax.varmax.score#statsmodels.tsa.statespace.varmax.VARMAX.score "statsmodels.tsa.statespace.varmax.VARMAX.score")(params, \*args, \*\*kwargs) | Compute the score function at params. | | [`score_obs`](statsmodels.tsa.statespace.varmax.varmax.score_obs#statsmodels.tsa.statespace.varmax.VARMAX.score_obs "statsmodels.tsa.statespace.varmax.VARMAX.score_obs")(params[, method, transformed, …]) | Compute the score per observation, evaluated at params | | [`set_conserve_memory`](statsmodels.tsa.statespace.varmax.varmax.set_conserve_memory#statsmodels.tsa.statespace.varmax.VARMAX.set_conserve_memory "statsmodels.tsa.statespace.varmax.VARMAX.set_conserve_memory")([conserve\_memory]) | Set the memory conservation method | | [`set_filter_method`](statsmodels.tsa.statespace.varmax.varmax.set_filter_method#statsmodels.tsa.statespace.varmax.VARMAX.set_filter_method "statsmodels.tsa.statespace.varmax.VARMAX.set_filter_method")([filter\_method]) | Set the filtering method | | [`set_inversion_method`](statsmodels.tsa.statespace.varmax.varmax.set_inversion_method#statsmodels.tsa.statespace.varmax.VARMAX.set_inversion_method "statsmodels.tsa.statespace.varmax.VARMAX.set_inversion_method")([inversion\_method]) | Set the inversion method | | [`set_smoother_output`](statsmodels.tsa.statespace.varmax.varmax.set_smoother_output#statsmodels.tsa.statespace.varmax.VARMAX.set_smoother_output "statsmodels.tsa.statespace.varmax.VARMAX.set_smoother_output")([smoother\_output]) | Set the smoother output | | [`set_stability_method`](statsmodels.tsa.statespace.varmax.varmax.set_stability_method#statsmodels.tsa.statespace.varmax.VARMAX.set_stability_method "statsmodels.tsa.statespace.varmax.VARMAX.set_stability_method")([stability\_method]) | Set the numerical stability method | | [`simulate`](statsmodels.tsa.statespace.varmax.varmax.simulate#statsmodels.tsa.statespace.varmax.VARMAX.simulate "statsmodels.tsa.statespace.varmax.VARMAX.simulate")(params, nsimulations[, …]) | Simulate a new time series following the state space model | | [`simulation_smoother`](statsmodels.tsa.statespace.varmax.varmax.simulation_smoother#statsmodels.tsa.statespace.varmax.VARMAX.simulation_smoother "statsmodels.tsa.statespace.varmax.VARMAX.simulation_smoother")([simulation\_output]) | Retrieve a simulation smoother for the state space model. | | [`smooth`](statsmodels.tsa.statespace.varmax.varmax.smooth#statsmodels.tsa.statespace.varmax.VARMAX.smooth "statsmodels.tsa.statespace.varmax.VARMAX.smooth")(params[, transformed, complex\_step, …]) | Kalman smoothing | | [`transform_jacobian`](statsmodels.tsa.statespace.varmax.varmax.transform_jacobian#statsmodels.tsa.statespace.varmax.VARMAX.transform_jacobian "statsmodels.tsa.statespace.varmax.VARMAX.transform_jacobian")(unconstrained[, …]) | Jacobian matrix for the parameter transformation function | | [`transform_params`](statsmodels.tsa.statespace.varmax.varmax.transform_params#statsmodels.tsa.statespace.varmax.VARMAX.transform_params "statsmodels.tsa.statespace.varmax.VARMAX.transform_params")(unconstrained) | Transform unconstrained parameters used by the optimizer to constrained parameters used in likelihood evaluation | | [`untransform_params`](statsmodels.tsa.statespace.varmax.varmax.untransform_params#statsmodels.tsa.statespace.varmax.VARMAX.untransform_params "statsmodels.tsa.statespace.varmax.VARMAX.untransform_params")(constrained) | Transform constrained parameters used in likelihood evaluation to unconstrained parameters used by the optimizer. | | [`update`](statsmodels.tsa.statespace.varmax.varmax.update#statsmodels.tsa.statespace.varmax.VARMAX.update "statsmodels.tsa.statespace.varmax.VARMAX.update")(params, \*\*kwargs) | Update the parameters of the model | #### Attributes | | | | --- | --- | | `endog_names` | Names of endogenous variables | | `exog_names` | | | `initial_variance` | | | `initialization` | | | `loglikelihood_burn` | | | `param_names` | (list of str) List of human readable parameter names (for parameters actually included in the model). | | `start_params` | (array) Starting parameters for maximum likelihood estimation. | | `tolerance` | | statsmodels statsmodels.imputation.mice.MICEData.set_imputer statsmodels.imputation.mice.MICEData.set\_imputer ================================================= `MICEData.set_imputer(endog_name, formula=None, model_class=None, init_kwds=None, fit_kwds=None, predict_kwds=None, k_pmm=20, perturbation_method=None, regularized=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/imputation/mice.html#MICEData.set_imputer) Specify the imputation process for a single variable. | Parameters: | * **endog\_name** (*string*) – Name of the variable to be imputed. * **formula** (*string*) – Conditional formula for imputation. Defaults to a formula with main effects for all other variables in dataset. The formula should only include an expression for the mean structure, e.g. use ‘x1 + x2’ not ‘x4 ~ x1 + x2’. * **model\_class** (*statsmodels model*) – Conditional model for imputation. Defaults to OLS. See below for more information. * **init\_kwds** (*dit-like*) – Keyword arguments passed to the model init method. * **fit\_kwds** (*dict-like*) – Keyword arguments passed to the model fit method. * **predict\_kwds** (*dict-like*) – Keyword arguments passed to the model predict method. * **k\_pmm** (*int*) – Determines number of neighboring observations from which to randomly sample when using predictive mean matching. * **perturbation\_method** (*string*) – Either ‘gaussian’ or ‘bootstrap’. Determines the method for perturbing parameters in the imputation model. If None, uses the default specified at class initialization. * **regularized** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")) – If regularized[name]=True, `fit_regularized` rather than `fit` is called when fitting imputation models for this variable. When regularized[name]=True for any variable, pertrurbation\_method must be set to boot. | #### Notes The model class must meet the following conditions: * A model must have a ‘fit’ method that returns an object. * The object returned from `fit` must have a `params` attribute that is an array-like object. * The object returned from `fit` must have a cov\_params method that returns a square array-like object. * The model must have a `predict` method.
programming_docs
statsmodels statsmodels.stats.gof.powerdiscrepancy statsmodels.stats.gof.powerdiscrepancy ====================================== `statsmodels.stats.gof.powerdiscrepancy(observed, expected, lambd=0.0, axis=0, ddof=0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/gof.html#powerdiscrepancy) Calculates power discrepancy, a class of goodness-of-fit tests as a measure of discrepancy between observed and expected data. This contains several goodness-of-fit tests as special cases, see the describtion of lambd, the exponent of the power discrepancy. The pvalue is based on the asymptotic chi-square distribution of the test statistic. freeman\_tukey: D(x| heta) = sum\_j (sqrt{x\_j} - sqrt{e\_j})^2 | Parameters: | * **o** (*Iterable*) – Observed values * **e** (*Iterable*) – Expected values * **lambd** (*float* *or* *string*) – + float : exponent `a` for power discrepancy + ’loglikeratio’: a = 0 + ’freeman\_tukey’: a = -0.5 + ’pearson’: a = 1 (standard chisquare test statistic) + ’modified\_loglikeratio’: a = -1 + ’cressie\_read’: a = 2/3 + ’neyman’ : a = -2 (Neyman-modified chisquare, reference from a book?) * **axis** (*int*) – axis for observations of one series * **ddof** (*int*) – degrees of freedom correction, | | Returns: | * **D\_obs** (*Discrepancy of observed values*) * **pvalue** (*pvalue*) | #### References Cressie, Noel and Timothy R. C. Read, Multinomial Goodness-of-Fit Tests, Journal of the Royal Statistical Society. Series B (Methodological), Vol. 46, No. 3 (1984), pp. 440-464 Campbell B. Read: Freeman-Tukey chi-squared goodness-of-fit statistics, Statistics & Probability Letters 18 (1993) 271-278 Nobuhiro Taneichi, Yuri Sekiya, Akio Suzukawa, Asymptotic Approximations for the Distributions of the Multinomial Goodness-of-Fit Statistics under Local Alternatives, Journal of Multivariate Analysis 81, 335?359 (2002) Steele, M. 1,2, C. Hurst 3 and J. Chaseling, Simulated Power of Discrete Goodness-of-Fit Tests for Likert Type Data #### Examples ``` >>> observed = np.array([ 2., 4., 2., 1., 1.]) >>> expected = np.array([ 0.2, 0.2, 0.2, 0.2, 0.2]) ``` for checking correct dimension with multiple series ``` >>> powerdiscrepancy(np.column_stack((observed,observed)).T, 10*expected, lambd='freeman_tukey',axis=1) (array([[ 2.745166, 2.745166]]), array([[ 0.6013346, 0.6013346]])) >>> powerdiscrepancy(np.column_stack((observed,observed)).T, 10*expected,axis=1) (array([[ 2.77258872, 2.77258872]]), array([[ 0.59657359, 0.59657359]])) >>> powerdiscrepancy(np.column_stack((observed,observed)).T, 10*expected, lambd=0,axis=1) (array([[ 2.77258872, 2.77258872]]), array([[ 0.59657359, 0.59657359]])) >>> powerdiscrepancy(np.column_stack((observed,observed)).T, 10*expected, lambd=1,axis=1) (array([[ 3., 3.]]), array([[ 0.5578254, 0.5578254]])) >>> powerdiscrepancy(np.column_stack((observed,observed)).T, 10*expected, lambd=2/3.0,axis=1) (array([[ 2.89714546, 2.89714546]]), array([[ 0.57518277, 0.57518277]])) >>> powerdiscrepancy(np.column_stack((observed,observed)).T, expected, lambd=2/3.0,axis=1) (array([[ 2.89714546, 2.89714546]]), array([[ 0.57518277, 0.57518277]])) >>> powerdiscrepancy(np.column_stack((observed,observed)), expected, lambd=2/3.0, axis=0) (array([[ 2.89714546, 2.89714546]]), array([[ 0.57518277, 0.57518277]])) ``` each random variable can have different total count/sum ``` >>> powerdiscrepancy(np.column_stack((observed,2*observed)), expected, lambd=2/3.0, axis=0) (array([[ 2.89714546, 5.79429093]]), array([[ 0.57518277, 0.21504648]])) >>> powerdiscrepancy(np.column_stack((observed,2*observed)), expected, lambd=2/3.0, axis=0) (array([[ 2.89714546, 5.79429093]]), array([[ 0.57518277, 0.21504648]])) >>> powerdiscrepancy(np.column_stack((2*observed,2*observed)), expected, lambd=2/3.0, axis=0) (array([[ 5.79429093, 5.79429093]]), array([[ 0.21504648, 0.21504648]])) >>> powerdiscrepancy(np.column_stack((2*observed,2*observed)), 20*expected, lambd=2/3.0, axis=0) (array([[ 5.79429093, 5.79429093]]), array([[ 0.21504648, 0.21504648]])) >>> powerdiscrepancy(np.column_stack((observed,2*observed)), np.column_stack((10*expected,20*expected)), lambd=2/3.0, axis=0) (array([[ 2.89714546, 5.79429093]]), array([[ 0.57518277, 0.21504648]])) >>> powerdiscrepancy(np.column_stack((observed,2*observed)), np.column_stack((10*expected,20*expected)), lambd=-1, axis=0) (array([[ 2.77258872, 5.54517744]]), array([[ 0.59657359, 0.2357868 ]])) ``` statsmodels statsmodels.sandbox.distributions.transformed.LogTransf_gen.stats statsmodels.sandbox.distributions.transformed.LogTransf\_gen.stats ================================================================== `LogTransf_gen.stats(*args, **kwds)` Some statistics of the given RV. | Parameters: | * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional* *(**continuous RVs only**)*) – scale parameter (default=1) * **moments** (*str**,* *optional*) – composed of letters [‘mvsk’] defining which moments to compute: ‘m’ = mean, ‘v’ = variance, ‘s’ = (Fisher’s) skew, ‘k’ = (Fisher’s) kurtosis. (default is ‘mv’) | | Returns: | **stats** – of requested moments. | | Return type: | sequence | statsmodels statsmodels.duration.hazard_regression.PHReg.get_distribution statsmodels.duration.hazard\_regression.PHReg.get\_distribution =============================================================== `PHReg.get_distribution(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/duration/hazard_regression.html#PHReg.get_distribution) Returns a scipy distribution object corresponding to the distribution of uncensored endog (duration) values for each case. | Parameters: | **params** (*array-like*) – The proportional hazards model parameters. | | Returns: | | | Return type: | A list of objects of type scipy.stats.distributions.rv\_discrete | #### Notes The distributions are obtained from a simple discrete estimate of the survivor function that puts all mass on the observed failure times within a stratum. statsmodels statsmodels.tsa.arima_model.ARIMAResults.hqic statsmodels.tsa.arima\_model.ARIMAResults.hqic ============================================== `ARIMAResults.hqic()` statsmodels statsmodels.tsa.vector_ar.irf.IRAnalysis.G statsmodels.tsa.vector\_ar.irf.IRAnalysis.G =========================================== `IRAnalysis.G()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/irf.html#IRAnalysis.G) statsmodels statsmodels.tsa.vector_ar.var_model.VARResults.pvalues statsmodels.tsa.vector\_ar.var\_model.VARResults.pvalues ======================================================== `VARResults.pvalues()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/var_model.html#VARResults.pvalues) Two-sided p-values for model coefficients from Student t-distribution statsmodels statsmodels.regression.linear_model.GLS.information statsmodels.regression.linear\_model.GLS.information ==================================================== `GLS.information(params)` Fisher information matrix of model Returns -Hessian of loglike evaluated at params. statsmodels statsmodels.regression.quantile_regression.QuantRegResults.bic statsmodels.regression.quantile\_regression.QuantRegResults.bic =============================================================== `QuantRegResults.bic()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/quantile_regression.html#QuantRegResults.bic) statsmodels statsmodels.tsa.vector_ar.var_model.VARResults.plot_acorr statsmodels.tsa.vector\_ar.var\_model.VARResults.plot\_acorr ============================================================ `VARResults.plot_acorr(nlags=10, resid=True, linewidth=8)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/var_model.html#VARResults.plot_acorr) Plot autocorrelation of sample (endog) or residuals Sample (Y) or Residual autocorrelations are plotted together with the standard \(2 / \sqrt{T}\) bounds. | Parameters: | * **nlags** (*int*) – number of lags to display (excluding 0) * **resid** (*boolean*) – If True, then the autocorrelation of the residuals is plotted If False, then the autocorrelation of endog is plotted. * **linewidth** (*int*) – width of vertical bars | | Returns: | **fig** | | Return type: | matplotlib figure instance | statsmodels statsmodels.genmod.generalized_linear_model.GLMResults.resid_working statsmodels.genmod.generalized\_linear\_model.GLMResults.resid\_working ======================================================================= `GLMResults.resid_working()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_linear_model.html#GLMResults.resid_working) statsmodels statsmodels.tsa.vector_ar.vecm.VECMResults.test_normality statsmodels.tsa.vector\_ar.vecm.VECMResults.test\_normality =========================================================== `VECMResults.test_normality(signif=0.05)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/vecm.html#VECMResults.test_normality) Test assumption of normal-distributed errors using Jarque-Bera-style omnibus \(\chi^2\) test. | Parameters: | **signif** (*float*) – The test’s significance level. | | Returns: | **result** | | Return type: | [`statsmodels.tsa.vector_ar.hypothesis_test_results.NormalityTestResults`](statsmodels.tsa.vector_ar.hypothesis_test_results.normalitytestresults#statsmodels.tsa.vector_ar.hypothesis_test_results.NormalityTestResults "statsmodels.tsa.vector_ar.hypothesis_test_results.NormalityTestResults") | #### Notes H0 : data are generated by a Gaussian-distributed process statsmodels statsmodels.sandbox.regression.gmm.IVGMM.gradient_momcond statsmodels.sandbox.regression.gmm.IVGMM.gradient\_momcond ========================================================== `IVGMM.gradient_momcond(params, epsilon=0.0001, centered=True)` gradient of moment conditions | Parameters: | * **params** (*ndarray*) – parameter at which the moment conditions are evaluated * **epsilon** (*float*) – stepsize for finite difference calculation * **centered** (*bool*) – This refers to the finite difference calculation. If `centered` is true, then the centered finite difference calculation is used. Otherwise the one-sided forward differences are used. * **TODO** (*looks like not used yet*) – missing argument `weights` | statsmodels statsmodels.iolib.foreign.StataWriter statsmodels.iolib.foreign.StataWriter ===================================== `class statsmodels.iolib.foreign.StataWriter(fname, data, convert_dates=None, encoding='latin-1', byteorder=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/iolib/foreign.html#StataWriter) A class for writing Stata binary dta files from array-like objects | Parameters: | * **fname** (*file path* *or* *buffer*) – Where to save the dta file. * **data** (*array-like*) – Array-like input to save. Pandas objects are also accepted. * **convert\_dates** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")) – Dictionary mapping column of datetime types to the stata internal format that you want to use for the dates. Options are ‘tc’, ‘td’, ‘tm’, ‘tw’, ‘th’, ‘tq’, ‘ty’. Column can be either a number or a name. * **encoding** (*str*) – Default is latin-1. Note that Stata does not support unicode. * **byteorder** (*str*) – Can be “>”, “<”, “little”, or “big”. The default is None which uses `sys.byteorder` | | Returns: | **writer** – The StataWriter instance has a write\_file method, which will write the file to the given `fname`. | | Return type: | StataWriter instance | #### Examples ``` >>> writer = StataWriter('./data_file.dta', data) >>> writer.write_file() ``` Or with dates ``` >>> writer = StataWriter('./date_data_file.dta', date, {2 : 'tw'}) >>> writer.write_file() ``` #### Methods | | | | --- | --- | | [`write_file`](statsmodels.iolib.foreign.statawriter.write_file#statsmodels.iolib.foreign.StataWriter.write_file "statsmodels.iolib.foreign.StataWriter.write_file")() | | #### Attributes | | | | --- | --- | | `DTYPE_MAP` | | | `MISSING_VALUES` | | | `TYPE_MAP` | | statsmodels statsmodels.genmod.generalized_estimating_equations.GEEResults.params_sensitivity statsmodels.genmod.generalized\_estimating\_equations.GEEResults.params\_sensitivity ==================================================================================== `GEEResults.params_sensitivity(dep_params_first, dep_params_last, num_steps)` Refits the GEE model using a sequence of values for the dependence parameters. | Parameters: | * **dep\_params\_first** (*array-like*) – The first dep\_params in the sequence * **dep\_params\_last** (*array-like*) – The last dep\_params in the sequence * **num\_steps** (*int*) – The number of dep\_params in the sequence | | Returns: | **results** – The GEEResults objects resulting from the fits. | | Return type: | array-like | statsmodels statsmodels.multivariate.multivariate_ols._MultivariateOLSResults.summary statsmodels.multivariate.multivariate\_ols.\_MultivariateOLSResults.summary =========================================================================== `_MultivariateOLSResults.summary()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/multivariate/multivariate_ols.html#_MultivariateOLSResults.summary) statsmodels statsmodels.tsa.statespace.tools.validate_matrix_shape statsmodels.tsa.statespace.tools.validate\_matrix\_shape ======================================================== `statsmodels.tsa.statespace.tools.validate_matrix_shape(name, shape, nrows, ncols, nobs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/tools.html#validate_matrix_shape) Validate the shape of a possibly time-varying matrix, or raise an exception | Parameters: | * **name** (*str*) – The name of the matrix being validated (used in exception messages) * **shape** (*array\_like*) – The shape of the matrix to be validated. May be of size 2 or (if the matrix is time-varying) 3. * **nrows** (*int*) – The expected number of rows. * **ncols** (*int*) – The expected number of columns. * **nobs** (*int*) – The number of observations (used to validate the last dimension of a time-varying matrix) | | Raises: | [`ValueError`](https://docs.python.org/3.2/library/exceptions.html#ValueError "(in Python v3.2)") – If the matrix is not of the desired shape. | statsmodels statsmodels.regression.linear_model.WLS.fit_regularized statsmodels.regression.linear\_model.WLS.fit\_regularized ========================================================= `WLS.fit_regularized(method='elastic_net', alpha=0.0, L1_wt=1.0, start_params=None, profile_scale=False, refit=False, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#WLS.fit_regularized) Return a regularized fit to a linear regression model. | Parameters: | * **method** (*string*) – Only the ‘elastic\_net’ approach is currently implemented. * **alpha** (*scalar* *or* *array-like*) – The penalty weight. If a scalar, the same penalty weight applies to all variables in the model. If a vector, it must have the same length as `params`, and contains a penalty weight for each coefficient. * **L1\_wt** (*scalar*) – The fraction of the penalty given to the L1 penalty term. Must be between 0 and 1 (inclusive). If 0, the fit is a ridge fit, if 1 it is a lasso fit. * **start\_params** (*array-like*) – Starting values for `params`. * **profile\_scale** (*bool*) – If True the penalized fit is computed using the profile (concentrated) log-likelihood for the Gaussian model. Otherwise the fit uses the residual sum of squares. * **refit** (*bool*) – If True, the model is refit using only the variables that have non-zero coefficients in the regularized fit. The refitted model is not regularized. * **distributed** (*bool*) – If True, the model uses distributed methods for fitting, will raise an error if True and partitions is None. * **generator** (*function*) – generator used to partition the model, allows for handling of out of memory/parallel computing. * **partitions** (*scalar*) – The number of partitions desired for the distributed estimation. * **threshold** (*scalar* *or* *array-like*) – The threshold below which coefficients are zeroed out, only used for distributed estimation | | Returns: | | | Return type: | A RegularizedResults instance. | #### Notes The elastic net approach closely follows that implemented in the glmnet package in R. The penalty is a combination of L1 and L2 penalties. The function that is minimized is: \[0.5\*RSS/n + alpha\*((1-L1\\_wt)\*|params|\_2^2/2 + L1\\_wt\*|params|\_1)\] where RSS is the usual regression sum of squares, n is the sample size, and \(|\*|\_1\) and \(|\*|\_2\) are the L1 and L2 norms. For WLS and GLS, the RSS is calculated using the whitened endog and exog data. Post-estimation results are based on the same data used to select variables, hence may be subject to overfitting biases. The elastic\_net method uses the following keyword arguments: `maxiter : int` Maximum number of iterations `cnvrg_tol : float` Convergence threshold for line searches `zero_tol : float` Coefficients below this threshold are treated as zero. #### References Friedman, Hastie, Tibshirani (2008). Regularization paths for generalized linear models via coordinate descent. Journal of Statistical Software 33(1), 1-22 Feb 2010. statsmodels statsmodels.tsa.vector_ar.vecm.VECMResults.summary statsmodels.tsa.vector\_ar.vecm.VECMResults.summary =================================================== `VECMResults.summary(alpha=0.05)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/vecm.html#VECMResults.summary) Return a summary of the estimation results. | Parameters: | **alpha** (float 0 < `alpha` < 1, default 0.05) – Significance level of the shown confidence intervals. | | Returns: | **summary** – A summary containing information about estimated parameters. | | Return type: | [`statsmodels.iolib.summary.Summary`](statsmodels.iolib.summary.summary#statsmodels.iolib.summary.Summary "statsmodels.iolib.summary.Summary") | statsmodels statsmodels.tsa.vector_ar.var_model.VARResults.info_criteria statsmodels.tsa.vector\_ar.var\_model.VARResults.info\_criteria =============================================================== `VARResults.info_criteria()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/var_model.html#VARResults.info_criteria) information criteria for lagorder selection statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.resid_pearson statsmodels.sandbox.regression.gmm.IVRegressionResults.resid\_pearson ===================================================================== `IVRegressionResults.resid_pearson()` Residuals, normalized to have unit variance. | Returns: | | | Return type: | An array wresid standardized by the sqrt if scale | statsmodels statsmodels.discrete.discrete_model.GeneralizedPoisson.initialize statsmodels.discrete.discrete\_model.GeneralizedPoisson.initialize ================================================================== `GeneralizedPoisson.initialize()` Initialize is called by statsmodels.model.LikelihoodModel.\_\_init\_\_ and should contain any preprocessing that needs to be done for a model. statsmodels statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialResults.load statsmodels.discrete.count\_model.ZeroInflatedNegativeBinomialResults.load ========================================================================== `classmethod ZeroInflatedNegativeBinomialResults.load(fname)` load a pickle, (class method) | Parameters: | **fname** (*string* *or* *filehandle*) – fname can be a string to a file path or filename, or a filehandle. | | Returns: | | | Return type: | unpickled instance |
programming_docs
statsmodels statsmodels.genmod.cov_struct.Exchangeable.covariance_matrix statsmodels.genmod.cov\_struct.Exchangeable.covariance\_matrix ============================================================== `Exchangeable.covariance_matrix(expval, index)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/cov_struct.html#Exchangeable.covariance_matrix) Returns the working covariance or correlation matrix for a given cluster of data. | Parameters: | * **endog\_expval** (*array-like*) – The expected values of endog for the cluster for which the covariance or correlation matrix will be returned * **index** (*integer*) – The index of the cluster for which the covariane or correlation matrix will be returned | | Returns: | * **M** (*matrix*) – The covariance or correlation matrix of endog * **is\_cor** (*bool*) – True if M is a correlation matrix, False if M is a covariance matrix | statsmodels statsmodels.regression.linear_model.WLS.hessian statsmodels.regression.linear\_model.WLS.hessian ================================================ `WLS.hessian(params)` The Hessian matrix of the model statsmodels statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialResults.wald_test statsmodels.discrete.count\_model.ZeroInflatedNegativeBinomialResults.wald\_test ================================================================================ `ZeroInflatedNegativeBinomialResults.wald_test(r_matrix, cov_p=None, scale=1.0, invcov=None, use_f=None)` Compute a Wald-test for a joint linear hypothesis. | Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) – + array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length p row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – Default is 1.0 for no scaling. * **invcov** (*array-like**,* *optional*) – A q x q array to specify an inverse covariance matrix based on a restrictions matrix. * **use\_f** (*bool*) – If True, then the F-distribution is used. If False, then the asymptotic distribution, chisquare is used. If use\_f is None, then the F distribution is used if the model specifies that use\_t is True. The test statistic is proportionally adjusted for the distribution by the number of constraints in the hypothesis. | | Returns: | **res** – The results for the test are attributes of this results instance. | | Return type: | ContrastResults instance | See also [`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`f_test`](statsmodels.discrete.count_model.zeroinflatednegativebinomialresults.f_test#statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialResults.f_test "statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialResults.f_test"), [`t_test`](statsmodels.discrete.count_model.zeroinflatednegativebinomialresults.t_test#statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialResults.t_test "statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") #### Notes The matrix `r_matrix` is assumed to be non-singular. More precisely, r\_matrix (pX pX.T) r\_matrix.T is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full. statsmodels statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.set_filter_method statsmodels.tsa.statespace.kalman\_smoother.KalmanSmoother.set\_filter\_method ============================================================================== `KalmanSmoother.set_filter_method(filter_method=None, **kwargs)` Set the filtering method The filtering method controls aspects of which Kalman filtering approach will be used. | Parameters: | * **filter\_method** (*integer**,* *optional*) – Bitmask value to set the filter method to. See notes for details. * **\*\*kwargs** – Keyword arguments may be used to influence the filter method by setting individual boolean flags. See notes for details. | #### Notes The filtering method is defined by a collection of boolean flags, and is internally stored as a bitmask. The methods available are: FILTER\_CONVENTIONAL = 0x01 Conventional Kalman filter. FILTER\_UNIVARIATE = 0x10 Univariate approach to Kalman filtering. Overrides conventional method if both are specified. FILTER\_COLLAPSED = 0x20 Collapsed approach to Kalman filtering. Will be used *in addition* to conventional or univariate filtering. Note that only the first method is available if using a Scipy version older than 0.16. If the bitmask is set directly via the `filter_method` argument, then the full method must be provided. If keyword arguments are used to set individual boolean flags, then the lowercase of the method must be used as an argument name, and the value is the desired value of the boolean flag (True or False). Note that the filter method may also be specified by directly modifying the class attributes which are defined similarly to the keyword arguments. The default filtering method is FILTER\_CONVENTIONAL. #### Examples ``` >>> mod = sm.tsa.statespace.SARIMAX(range(10)) >>> mod.ssm.filter_method 1 >>> mod.ssm.filter_conventional True >>> mod.ssm.filter_univariate = True >>> mod.ssm.filter_method 17 >>> mod.ssm.set_filter_method(filter_univariate=False, ... filter_collapsed=True) >>> mod.ssm.filter_method 33 >>> mod.ssm.set_filter_method(filter_method=1) >>> mod.ssm.filter_conventional True >>> mod.ssm.filter_univariate False >>> mod.ssm.filter_collapsed False >>> mod.ssm.filter_univariate = True >>> mod.ssm.filter_method 17 ``` statsmodels statsmodels.sandbox.distributions.transformed.TransfTwo_gen.std statsmodels.sandbox.distributions.transformed.TransfTwo\_gen.std ================================================================ `TransfTwo_gen.std(*args, **kwds)` Standard deviation of the distribution. | Parameters: | * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **std** – standard deviation of the distribution | | Return type: | float | statsmodels statsmodels.tsa.statespace.mlemodel.MLEResults.cov_params_robust statsmodels.tsa.statespace.mlemodel.MLEResults.cov\_params\_robust ================================================================== `MLEResults.cov_params_robust()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEResults.cov_params_robust) (array) The QMLE variance / covariance matrix. Alias for `cov_params_robust_oim` statsmodels statsmodels.tsa.statespace.sarimax.SARIMAXResults.pvalues statsmodels.tsa.statespace.sarimax.SARIMAXResults.pvalues ========================================================= `SARIMAXResults.pvalues()` (array) The p-values associated with the z-statistics of the coefficients. Note that the coefficients are assumed to have a Normal distribution. statsmodels statsmodels.discrete.discrete_model.GeneralizedPoissonResults.conf_int statsmodels.discrete.discrete\_model.GeneralizedPoissonResults.conf\_int ======================================================================== `GeneralizedPoissonResults.conf_int(alpha=0.05, cols=None, method='default')` Returns the confidence interval of the fitted parameters. | Parameters: | * **alpha** (*float**,* *optional*) – The significance level for the confidence interval. ie., The default `alpha` = .05 returns a 95% confidence interval. * **cols** (*array-like**,* *optional*) – `cols` specifies which confidence intervals to return * **method** (*string*) – Not Implemented Yet Method to estimate the confidence\_interval. “Default” : uses self.bse which is based on inverse Hessian for MLE “hjjh” : “jac” : “boot-bse” “boot\_quant” “profile” | | Returns: | **conf\_int** – Each row contains [lower, upper] limits of the confidence interval for the corresponding parameter. The first column contains all lower, the second column contains all upper limits. | | Return type: | array | #### Examples ``` >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> results.conf_int() array([[-5496529.48322745, -1467987.78596704], [ -177.02903529, 207.15277984], [ -0.1115811 , 0.03994274], [ -3.12506664, -0.91539297], [ -1.5179487 , -0.54850503], [ -0.56251721, 0.460309 ], [ 798.7875153 , 2859.51541392]]) ``` ``` >>> results.conf_int(cols=(2,3)) array([[-0.1115811 , 0.03994274], [-3.12506664, -0.91539297]]) ``` #### Notes The confidence interval is based on the standard normal distribution. Models wish to use a different distribution should overwrite this method. statsmodels statsmodels.sandbox.sysreg.SUR.initialize statsmodels.sandbox.sysreg.SUR.initialize ========================================= `SUR.initialize()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/sysreg.html#SUR.initialize) statsmodels statsmodels.duration.hazard_regression.PHRegResults.baseline_cumulative_hazard statsmodels.duration.hazard\_regression.PHRegResults.baseline\_cumulative\_hazard ================================================================================= `PHRegResults.baseline_cumulative_hazard()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/duration/hazard_regression.html#PHRegResults.baseline_cumulative_hazard) A list (corresponding to the strata) containing the baseline cumulative hazard function evaluated at the event points. statsmodels statsmodels.iolib.foreign.StataWriter.write_file statsmodels.iolib.foreign.StataWriter.write\_file ================================================= `StataWriter.write_file()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/iolib/foreign.html#StataWriter.write_file) statsmodels statsmodels.tsa.statespace.structural.UnobservedComponentsResults.cov_params_oim statsmodels.tsa.statespace.structural.UnobservedComponentsResults.cov\_params\_oim ================================================================================== `UnobservedComponentsResults.cov_params_oim()` (array) The variance / covariance matrix. Computed using the method from Harvey (1989). statsmodels statsmodels.discrete.discrete_model.DiscreteResults.predict statsmodels.discrete.discrete\_model.DiscreteResults.predict ============================================================ `DiscreteResults.predict(exog=None, transform=True, *args, **kwargs)` Call self.model.predict with self.params as the first argument. | Parameters: | * **exog** (*array-like**,* *optional*) – The values for which you want to predict. see Notes below. * **transform** (*bool**,* *optional*) – If the model was fit via a formula, do you want to pass exog through the formula. Default is True. E.g., if you fit a model y ~ log(x1) + log(x2), and transform is True, then you can pass a data structure that contains x1 and x2 in their original form. Otherwise, you’d need to log the data first. * **kwargs** (*args**,*) – Some models can take additional arguments or keywords, see the predict method of the model for the details. | | Returns: | **prediction** – See self.model.predict | | Return type: | ndarray, [pandas.Series](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html#pandas.Series "(in pandas v0.22.0)") or [pandas.DataFrame](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html#pandas.DataFrame "(in pandas v0.22.0)") | #### Notes The types of exog that are supported depends on whether a formula was used in the specification of the model. If a formula was used, then exog is processed in the same way as the original data. This transformation needs to have key access to the same variable names, and can be a pandas DataFrame or a dict like object. If no formula was used, then the provided exog needs to have the same number of columns as the original exog in the model. No transformation of the data is performed except converting it to a numpy array. Row indices as in pandas data frames are supported, and added to the returned prediction. statsmodels statsmodels.discrete.discrete_model.MultinomialResults.llr statsmodels.discrete.discrete\_model.MultinomialResults.llr =========================================================== `MultinomialResults.llr()` statsmodels statsmodels.discrete.discrete_model.DiscreteResults.conf_int statsmodels.discrete.discrete\_model.DiscreteResults.conf\_int ============================================================== `DiscreteResults.conf_int(alpha=0.05, cols=None, method='default')` Returns the confidence interval of the fitted parameters. | Parameters: | * **alpha** (*float**,* *optional*) – The significance level for the confidence interval. ie., The default `alpha` = .05 returns a 95% confidence interval. * **cols** (*array-like**,* *optional*) – `cols` specifies which confidence intervals to return * **method** (*string*) – Not Implemented Yet Method to estimate the confidence\_interval. “Default” : uses self.bse which is based on inverse Hessian for MLE “hjjh” : “jac” : “boot-bse” “boot\_quant” “profile” | | Returns: | **conf\_int** – Each row contains [lower, upper] limits of the confidence interval for the corresponding parameter. The first column contains all lower, the second column contains all upper limits. | | Return type: | array | #### Examples ``` >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> results.conf_int() array([[-5496529.48322745, -1467987.78596704], [ -177.02903529, 207.15277984], [ -0.1115811 , 0.03994274], [ -3.12506664, -0.91539297], [ -1.5179487 , -0.54850503], [ -0.56251721, 0.460309 ], [ 798.7875153 , 2859.51541392]]) ``` ``` >>> results.conf_int(cols=(2,3)) array([[-0.1115811 , 0.03994274], [-3.12506664, -0.91539297]]) ``` #### Notes The confidence interval is based on the standard normal distribution. Models wish to use a different distribution should overwrite this method. statsmodels statsmodels.sandbox.stats.multicomp.ecdf statsmodels.sandbox.stats.multicomp.ecdf ======================================== `statsmodels.sandbox.stats.multicomp.ecdf(x)` no frills empirical cdf used in fdrcorrection statsmodels statsmodels.sandbox.distributions.transformed.Transf_gen.ppf statsmodels.sandbox.distributions.transformed.Transf\_gen.ppf ============================================================= `Transf_gen.ppf(q, *args, **kwds)` Percent point function (inverse of `cdf`) at q of the given RV. | Parameters: | * **q** (*array\_like*) – lower tail probability * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **x** – quantile corresponding to the lower tail probability q. | | Return type: | array\_like | statsmodels statsmodels.miscmodels.count.PoissonZiGMLE.loglikeobs statsmodels.miscmodels.count.PoissonZiGMLE.loglikeobs ===================================================== `PoissonZiGMLE.loglikeobs(params)` statsmodels statsmodels.sandbox.tsa.fftarma.ArmaFft.periodogram statsmodels.sandbox.tsa.fftarma.ArmaFft.periodogram =================================================== `ArmaFft.periodogram(nobs=None)` Periodogram for ARMA process given by lag-polynomials ar and ma | Parameters: | * **ar** (*array\_like*) – autoregressive lag-polynomial with leading 1 and lhs sign * **ma** (*array\_like*) – moving average lag-polynomial with leading 1 * **worN** (*{None**,* *int}**,* *optional*) – option for scipy.signal.freqz (read “w or N”) If None, then compute at 512 frequencies around the unit circle. If a single integer, the compute at that many frequencies. Otherwise, compute the response at frequencies given in worN * **whole** (*{0**,**1}**,* *optional*) – options for scipy.signal.freqz Normally, frequencies are computed from 0 to pi (upper-half of unit-circle. If whole is non-zero compute frequencies from 0 to 2\*pi. | | Returns: | * **w** (*array*) – frequencies * **sd** (*array*) – periodogram, spectral density | #### Notes Normalization ? This uses signal.freqz, which does not use fft. There is a fft version somewhere. statsmodels statsmodels.sandbox.distributions.transformed.ExpTransf_gen.logsf statsmodels.sandbox.distributions.transformed.ExpTransf\_gen.logsf ================================================================== `ExpTransf_gen.logsf(x, *args, **kwds)` Log of the survival function of the given RV. Returns the log of the “survival function,” defined as (1 - `cdf`), evaluated at `x`. | Parameters: | * **x** (*array\_like*) – quantiles * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **logsf** – Log of the survival function evaluated at `x`. | | Return type: | ndarray | statsmodels statsmodels.regression.linear_model.RegressionResults.ess statsmodels.regression.linear\_model.RegressionResults.ess ========================================================== `RegressionResults.ess()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#RegressionResults.ess) statsmodels statsmodels.discrete.discrete_model.Poisson.score statsmodels.discrete.discrete\_model.Poisson.score ================================================== `Poisson.score(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#Poisson.score) Poisson model score (gradient) vector of the log-likelihood | Parameters: | **params** (*array-like*) – The parameters of the model | | Returns: | **score** – The score vector of the model, i.e. the first derivative of the loglikelihood function, evaluated at `params` | | Return type: | ndarray, 1-D | #### Notes \[\frac{\partial\ln L}{\partial\beta}=\sum\_{i=1}^{n}\left(y\_{i}-\lambda\_{i}\right)x\_{i}\] where the loglinear model is assumed \[\ln\lambda\_{i}=x\_{i}\beta\] statsmodels statsmodels.regression.quantile_regression.QuantRegResults.bse statsmodels.regression.quantile\_regression.QuantRegResults.bse =============================================================== `QuantRegResults.bse()` statsmodels statsmodels.genmod.generalized_linear_model.GLMResults.wald_test_terms statsmodels.genmod.generalized\_linear\_model.GLMResults.wald\_test\_terms ========================================================================== `GLMResults.wald_test_terms(skip_single=False, extra_constraints=None, combine_terms=None)` Compute a sequence of Wald tests for terms over multiple columns This computes joined Wald tests for the hypothesis that all coefficients corresponding to a `term` are zero. `Terms` are defined by the underlying formula or by string matching. | Parameters: | * **skip\_single** (*boolean*) – If true, then terms that consist only of a single column and, therefore, refers only to a single parameter is skipped. If false, then all terms are included. * **extra\_constraints** (*ndarray*) – not tested yet * **combine\_terms** (*None* *or* *list of strings*) – Each string in this list is matched to the name of the terms or the name of the exogenous variables. All columns whose name includes that string are combined in one joint test. | | Returns: | **test\_result** – The result instance contains `table` which is a pandas DataFrame with the test results: test statistic, degrees of freedom and pvalues. | | Return type: | result instance | #### Examples ``` >>> res_ols = ols("np.log(Days+1) ~ C(Duration, Sum)*C(Weight, Sum)", data).fit() >>> res_ols.wald_test_terms() <class 'statsmodels.stats.contrast.WaldTestResults'> F P>F df constraint df denom Intercept 279.754525 2.37985521351e-22 1 51 C(Duration, Sum) 5.367071 0.0245738436636 1 51 C(Weight, Sum) 12.432445 3.99943118767e-05 2 51 C(Duration, Sum):C(Weight, Sum) 0.176002 0.83912310946 2 51 ``` ``` >>> res_poi = Poisson.from_formula("Days ~ C(Weight) * C(Duration)", data).fit(cov_type='HC0') >>> wt = res_poi.wald_test_terms(skip_single=False, combine_terms=['Duration', 'Weight']) >>> print(wt) chi2 P>chi2 df constraint Intercept 15.695625 7.43960374424e-05 1 C(Weight) 16.132616 0.000313940174705 2 C(Duration) 1.009147 0.315107378931 1 C(Weight):C(Duration) 0.216694 0.897315972824 2 Duration 11.187849 0.010752286833 3 Weight 30.263368 4.32586407145e-06 4 ```
programming_docs
statsmodels statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialP.fit_regularized statsmodels.discrete.count\_model.ZeroInflatedNegativeBinomialP.fit\_regularized ================================================================================ `ZeroInflatedNegativeBinomialP.fit_regularized(start_params=None, method='l1', maxiter='defined_by_method', full_output=1, disp=1, callback=None, alpha=0, trim_mode='auto', auto_trim_tol=0.01, size_trim_tol=0.0001, qc_tol=0.03, **kwargs)` Fit the model using a regularized maximum likelihood. The regularization method AND the solver used is determined by the argument method. | Parameters: | * **start\_params** (*array-like**,* *optional*) – Initial guess of the solution for the loglikelihood maximization. The default is an array of zeros. * **method** (*'l1'* *or* *'l1\_cvxopt\_cp'*) – See notes for details. * **maxiter** (*Integer* *or* *'defined\_by\_method'*) – Maximum number of iterations to perform. If ‘defined\_by\_method’, then use method defaults (see notes). * **full\_output** (*bool*) – Set to True to have all available output in the Results object’s mle\_retvals attribute. The output is dependent on the solver. See LikelihoodModelResults notes section for more information. * **disp** (*bool*) – Set to True to print convergence messages. * **fargs** (*tuple*) – Extra arguments passed to the likelihood function, i.e., loglike(x,\*args) * **callback** (*callable callback**(**xk**)*) – Called after each iteration, as callback(xk), where xk is the current parameter vector. * **retall** (*bool*) – Set to True to return list of solutions at each iteration. Available in Results object’s mle\_retvals attribute. * **alpha** (*non-negative scalar* *or* *numpy array* *(**same size as parameters**)*) – The weight multiplying the l1 penalty term * **trim\_mode** (*'auto**,* *'size'**, or* *'off'*) – If not ‘off’, trim (set to zero) parameters that would have been zero if the solver reached the theoretical minimum. If ‘auto’, trim params using the Theory above. If ‘size’, trim params if they have very small absolute value * **size\_trim\_tol** (*float* *or* *'auto'* *(**default = 'auto'**)*) – For use when trim\_mode == ‘size’ * **auto\_trim\_tol** (*float*) – For sue when trim\_mode == ‘auto’. Use * **qc\_tol** (*float*) – Print warning and don’t allow auto trim when (ii) (above) is violated by this much. * **qc\_verbose** (*Boolean*) – If true, print out a full QC report upon failure | #### Notes Extra parameters are not penalized if alpha is given as a scalar. An example is the shape parameter in NegativeBinomial `nb1` and `nb2`. Optional arguments for the solvers (available in Results.mle\_settings): ``` 'l1' acc : float (default 1e-6) Requested accuracy as used by slsqp 'l1_cvxopt_cp' abstol : float absolute accuracy (default: 1e-7). reltol : float relative accuracy (default: 1e-6). feastol : float tolerance for feasibility conditions (default: 1e-7). refinement : int number of iterative refinement steps when solving KKT equations (default: 1). ``` Optimization methodology With \(L\) the negative log likelihood, we solve the convex but non-smooth problem \[\min\_\beta L(\beta) + \sum\_k\alpha\_k |\beta\_k|\] via the transformation to the smooth, convex, constrained problem in twice as many variables (adding the “added variables” \(u\_k\)) \[\min\_{\beta,u} L(\beta) + \sum\_k\alpha\_k u\_k,\] subject to \[-u\_k \leq \beta\_k \leq u\_k.\] With \(\partial\_k L\) the derivative of \(L\) in the \(k^{th}\) parameter direction, theory dictates that, at the minimum, exactly one of two conditions holds: 1. \(|\partial\_k L| = \alpha\_k\) and \(\beta\_k \neq 0\) 2. \(|\partial\_k L| \leq \alpha\_k\) and \(\beta\_k = 0\) statsmodels statsmodels.tsa.vector_ar.vecm.VECMResults statsmodels.tsa.vector\_ar.vecm.VECMResults =========================================== `class statsmodels.tsa.vector_ar.vecm.VECMResults(endog, exog, exog_coint, k_ar, coint_rank, alpha, beta, gamma, sigma_u, deterministic='nc', seasons=0, first_season=0, delta_y_1_T=None, y_lag1=None, delta_x=None, model=None, names=None, dates=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/vecm.html#VECMResults) Class for holding estimation related results of a vector error correction model (VECM). | Parameters: | * **endog** (*ndarray* *(**neqs x nobs\_tot**)*) – Array of observations. * **exog** (ndarray (nobs\_tot x neqs) or `None`) – Deterministic terms outside the cointegration relation. * **exog\_coint** (ndarray (nobs\_tot x neqs) or `None`) – Deterministic terms inside the cointegration relation. * **k\_ar** (*int**,* *>= 1*) – Lags in the VAR representation. This implies that the number of lags in the VEC representation (=lagged differences) equals \(k\_{ar} - 1\). * **coint\_rank** (int, 0 <= `coint_rank` <= neqs) – Cointegration rank, equals the rank of the matrix \(\Pi\) and the number of columns of \(\alpha\) and \(\beta\). * **alpha** (ndarray (neqs x `coint_rank`)) – Estimate for the parameter \(\alpha\) of a VECM. * **beta** (ndarray (neqs x `coint_rank`)) – Estimate for the parameter \(\beta\) of a VECM. * **gamma** (*ndarray* *(**neqs x neqs\***(**k\_ar-1**)**)*) – Array containing the estimates of the \(k\_{ar}-1\) parameter matrices \(\Gamma\_1, \dots, \Gamma\_{k\_{ar}-1}\) of a VECM(\(k\_{ar}-1\)). The submatrices are stacked horizontally from left to right. * **sigma\_u** (*ndarray* *(**neqs x neqs**)*) – Estimate of white noise process covariance matrix \(\Sigma\_u\). * **deterministic** (str {`"nc"`, `"co"`, `"ci"`, `"lo"`, `"li"`}) – + `"nc"` - no deterministic terms + `"co"` - constant outside the cointegration relation + `"ci"` - constant within the cointegration relation + `"lo"` - linear trend outside the cointegration relation + `"li"` - linear trend within the cointegration relationCombinations of these are possible (e.g. `"cili"` or `"colo"` for linear trend with intercept). See the docstring of the [`VECM`](statsmodels.tsa.vector_ar.vecm.vecm#statsmodels.tsa.vector_ar.vecm.VECM "statsmodels.tsa.vector_ar.vecm.VECM")-class for more information. * **seasons** (*int**,* *default: 0*) – Number of periods in a seasonal cycle. 0 means no seasons. * **first\_season** (*int**,* *default: 0*) – Season of the first observation. * **delta\_y\_1\_T** (ndarray or `None`, default: `None`) – Auxilliary array for internal computations. It will be calculated if not given as parameter. * **y\_lag1** (ndarray or `None`, default: `None`) – Auxilliary array for internal computations. It will be calculated if not given as parameter. * **delta\_x** (ndarray or `None`, default: `None`) – Auxilliary array for internal computations. It will be calculated if not given as parameter. * **model** ([`VECM`](statsmodels.tsa.vector_ar.vecm.vecm#statsmodels.tsa.vector_ar.vecm.VECM "statsmodels.tsa.vector_ar.vecm.VECM")) – An instance of the [`VECM`](statsmodels.tsa.vector_ar.vecm.vecm#statsmodels.tsa.vector_ar.vecm.VECM "statsmodels.tsa.vector_ar.vecm.VECM")-class. * **names** (*list of str*) – Each str in the list represents the name of a variable of the time series. * **dates** (*array-like*) – For example a DatetimeIndex of length nobs\_tot. | | Returns: | * *\*\*Attributes\*\** * **nobs** (*int*) – Number of observations (excluding the presample). * **model** (*see Parameters*) * **y\_all** (see `endog` in Parameters) * **exog** (*see Parameters*) * **exog\_coint** (*see Parameters*) * **names** (*see Parameters*) * **dates** (*see Parameters*) * **neqs** (*int*) – Number of variables in the time series. * **k\_ar** (*see Parameters*) * **deterministic** (*see Parameters*) * **seasons** (*see Parameters*) * **first\_season** (*see Parameters*) * **alpha** (*see Parameters*) * **beta** (*see Parameters*) * **gamma** (*see Parameters*) * **sigma\_u** (*see Parameters*) * **det\_coef\_coint** (ndarray (#(determinist. terms inside the coint. rel.) x `coint_rank`)) – Estimated coefficients for the all deterministic terms inside the cointegration relation. * **const\_coint** (ndarray (1 x `coint_rank`)) – If there is a constant deterministic term inside the cointegration relation, then `const_coint` is the first row of `det_coef_coint`. Otherwise it’s an ndarray of zeros. * **lin\_trend\_coint** (ndarray (1 x `coint_rank`)) – If there is a linear deterministic term inside the cointegration relation, then `lin_trend_coint` contains the corresponding estimated coefficients. As such it represents the corresponding row of `det_coef_coint`. If there is no linear deterministic term inside the cointegration relation, then `lin_trend_coint` is an ndarray of zeros. * **exog\_coint\_coefs** (ndarray (exog\_coint.shape[1] x `coint_rank`) or `None`) – If deterministic terms inside the cointegration relation are passed via the `exog_coint` parameter, then `exog_coint_coefs` contains the corresponding estimated coefficients. As such `exog_coint_coefs` represents the last rows of `det_coef_coint`. If no deterministic terms were passed via the `exog_coint` parameter, this attribute is `None`. * **det\_coef** (*ndarray (neqs x #(deterministic terms outside the coint. rel.))*) – Estimated coefficients for the all deterministic terms outside the cointegration relation. * **const** (*ndarray (neqs x 1) or (neqs x 0)*) – If a constant deterministic term outside the cointegration is specified within the deterministic parameter, then `const` is the first column of `det_coef_coint`. Otherwise it’s an ndarray of size zero. * **seasonal** (*ndarray (neqs x seasons)*) – If the `seasons` parameter is > 0, then seasonal contains the estimated coefficients corresponding to the seasonal terms. Otherwise it’s an ndarray of size zero. * **lin\_trend** (*ndarray (neqs x 1) or (neqs x 0)*) – If a linear deterministic term outside the cointegration is specified within the deterministic parameter, then `lin_trend` contains the corresponding estimated coefficients. As such it represents the corresponding column of `det_coef_coint`. If there is no linear deterministic term outside the cointegration relation, then `lin_trend` is an ndarray of size zero. * **exog\_coefs** (*ndarray (neqs x exog\_coefs.shape[1])*) – If deterministic terms outside the cointegration relation are passed via the `exog` parameter, then `exog_coefs` contains the corresponding estimated coefficients. As such `exog_coefs` represents the last columns of `det_coef`. If no deterministic terms were passed via the `exog` parameter, this attribute is an ndarray of size zero. * **\_delta\_y\_1\_T** (*see delta\_y\_1\_T in Parameters*) * **\_y\_lag1** (*see y\_lag1 in Parameters*) * **\_delta\_x** (*see delta\_x in Parameters*) * **coint\_rank** (*int*) – Cointegration rank, equals the rank of the matrix \(\Pi\) and the number of columns of \(\alpha\) and \(\beta\). * **llf** (*float*) – The model’s log-likelihood. * **cov\_params** (*ndarray (d x d)*) – Covariance matrix of the parameters. The number of rows and columns, d (used in the dimension specification of this argument), is equal to neqs \* (neqs+num\_det\_coef\_coint + neqs\*(k\_ar-1)+number of deterministic dummy variables outside the cointegration relation). For the case with no deterministic terms this matrix is defined on p. 287 in [[1]](#id5) as \(\Sigma\_{co}\) and its relationship to the ML-estimators can be seen in eq. (7.2.21) on p. 296 in [[1]](#id5). * **cov\_params\_wo\_det** (*ndarray*) – Covariance matrix of the parameters \(\tilde{\Pi}, \tilde{\Gamma}\) where \(\tilde{\Pi} = \tilde{\alpha} \tilde{\beta'}\). Equals `cov_params` without the rows and columns related to deterministic terms. This matrix is defined as \(\Sigma\_{co}\) on p. 287 in [[1]](#id5). * **stderr\_params** (*ndarray (d)*) – Array containing the standard errors of \(\Pi\), \(\Gamma\), and estimated parameters related to deterministic terms. * **stderr\_coint** (ndarray (neqs+num\_det\_coef\_coint x `coint_rank`)) – Array containing the standard errors of \(\beta\) and estimated parameters related to deterministic terms inside the cointegration relation. * **stderr\_alpha** (ndarray (neqs x `coint_rank`)) – The standard errors of \(\alpha\). * **stderr\_beta** (ndarray (neqs x `coint_rank`)) – The standard errors of \(\beta\). * **stderr\_det\_coef\_coint** (ndarray (num\_det\_coef\_coint x `coint_rank`)) – The standard errors of estimated the parameters related to deterministic terms inside the cointegration relation. * **stderr\_gamma** (*ndarray (neqs x neqs\*(k\_ar-1))*) – The standard errors of \(\Gamma\_1, \ldots, \Gamma\_{k\_{ar}-1}\). * **stderr\_det\_coef** (*ndarray (neqs x det. terms outside the coint. relation)*) – The standard errors of estimated the parameters related to deterministic terms outside the cointegration relation. * **tvalues\_alpha** (ndarray (neqs x `coint_rank`)) * **tvalues\_beta** (ndarray (neqs x `coint_rank`)) * **tvalues\_det\_coef\_coint** (ndarray (num\_det\_coef\_coint x `coint_rank`)) * **tvalues\_gamma** (*ndarray (neqs x neqs\*(k\_ar-1))*) * **tvalues\_det\_coef** (*ndarray (neqs x det. terms outside the coint. relation)*) * **pvalues\_alpha** (ndarray (neqs x `coint_rank`)) * **pvalues\_beta** (ndarray (neqs x `coint_rank`)) * **pvalues\_det\_coef\_coint** (ndarray (num\_det\_coef\_coint x `coint_rank`)) * **pvalues\_gamma** (*ndarray (neqs x neqs\*(k\_ar-1))*) * **pvalues\_det\_coef** (*ndarray (neqs x det. terms outside the coint. relation)*) * **var\_rep** (*(k\_ar x neqs x neqs)*) – KxK parameter matrices \(A\_i\) of the corresponding VAR representation. If the return value is assigned to a variable `A`, these matrices can be accessed via `A[i]` for \(i=0, \ldots, k\_{ar}-1\). * **cov\_var\_repr** (*ndarray (neqs\*\*2 \* k\_ar x neqs\*\*2 \* k\_ar)*) – This matrix is called \(\Sigma^{co}\_{\alpha}\) on p. 289 in [[1]](#id5). It is needed e.g. for impulse-response-analysis. * **fittedvalues** (*ndarray (nobs x neqs)*) – The predicted in-sample values of the models’ endogenous variables. * **resid** (*ndarray (nobs x neqs)*) – The residuals. | #### References | | | | --- | --- | | [1] | *([1](#id1), [2](#id2), [3](#id3), [4](#id4))* Lütkepohl, H. 2005. *New Introduction to Multiple Time Series Analysis*. Springer. | #### Methods | | | | --- | --- | | [`conf_int_alpha`](statsmodels.tsa.vector_ar.vecm.vecmresults.conf_int_alpha#statsmodels.tsa.vector_ar.vecm.VECMResults.conf_int_alpha "statsmodels.tsa.vector_ar.vecm.VECMResults.conf_int_alpha")([alpha]) | | | [`conf_int_beta`](statsmodels.tsa.vector_ar.vecm.vecmresults.conf_int_beta#statsmodels.tsa.vector_ar.vecm.VECMResults.conf_int_beta "statsmodels.tsa.vector_ar.vecm.VECMResults.conf_int_beta")([alpha]) | | | [`conf_int_det_coef`](statsmodels.tsa.vector_ar.vecm.vecmresults.conf_int_det_coef#statsmodels.tsa.vector_ar.vecm.VECMResults.conf_int_det_coef "statsmodels.tsa.vector_ar.vecm.VECMResults.conf_int_det_coef")([alpha]) | | | [`conf_int_det_coef_coint`](statsmodels.tsa.vector_ar.vecm.vecmresults.conf_int_det_coef_coint#statsmodels.tsa.vector_ar.vecm.VECMResults.conf_int_det_coef_coint "statsmodels.tsa.vector_ar.vecm.VECMResults.conf_int_det_coef_coint")([alpha]) | | | [`conf_int_gamma`](statsmodels.tsa.vector_ar.vecm.vecmresults.conf_int_gamma#statsmodels.tsa.vector_ar.vecm.VECMResults.conf_int_gamma "statsmodels.tsa.vector_ar.vecm.VECMResults.conf_int_gamma")([alpha]) | | | [`cov_params_default`](statsmodels.tsa.vector_ar.vecm.vecmresults.cov_params_default#statsmodels.tsa.vector_ar.vecm.VECMResults.cov_params_default "statsmodels.tsa.vector_ar.vecm.VECMResults.cov_params_default")() | | | [`cov_params_wo_det`](statsmodels.tsa.vector_ar.vecm.vecmresults.cov_params_wo_det#statsmodels.tsa.vector_ar.vecm.VECMResults.cov_params_wo_det "statsmodels.tsa.vector_ar.vecm.VECMResults.cov_params_wo_det")() | | | [`cov_var_repr`](statsmodels.tsa.vector_ar.vecm.vecmresults.cov_var_repr#statsmodels.tsa.vector_ar.vecm.VECMResults.cov_var_repr "statsmodels.tsa.vector_ar.vecm.VECMResults.cov_var_repr")() | Gives the covariance matrix of the corresponding VAR-representation. | | [`fittedvalues`](statsmodels.tsa.vector_ar.vecm.vecmresults.fittedvalues#statsmodels.tsa.vector_ar.vecm.VECMResults.fittedvalues "statsmodels.tsa.vector_ar.vecm.VECMResults.fittedvalues")() | Return the in-sample values of endog calculated by the model. | | [`irf`](statsmodels.tsa.vector_ar.vecm.vecmresults.irf#statsmodels.tsa.vector_ar.vecm.VECMResults.irf "statsmodels.tsa.vector_ar.vecm.VECMResults.irf")([periods]) | | | [`llf`](statsmodels.tsa.vector_ar.vecm.vecmresults.llf#statsmodels.tsa.vector_ar.vecm.VECMResults.llf "statsmodels.tsa.vector_ar.vecm.VECMResults.llf")() | Compute the VECM’s loglikelihood. | | [`ma_rep`](statsmodels.tsa.vector_ar.vecm.vecmresults.ma_rep#statsmodels.tsa.vector_ar.vecm.VECMResults.ma_rep "statsmodels.tsa.vector_ar.vecm.VECMResults.ma_rep")([maxn]) | | | [`orth_ma_rep`](statsmodels.tsa.vector_ar.vecm.vecmresults.orth_ma_rep#statsmodels.tsa.vector_ar.vecm.VECMResults.orth_ma_rep "statsmodels.tsa.vector_ar.vecm.VECMResults.orth_ma_rep")([maxn, P]) | Compute orthogonalized MA coefficient matrices. | | [`plot_data`](statsmodels.tsa.vector_ar.vecm.vecmresults.plot_data#statsmodels.tsa.vector_ar.vecm.VECMResults.plot_data "statsmodels.tsa.vector_ar.vecm.VECMResults.plot_data")([with\_presample]) | Plot the input time series. | | [`plot_forecast`](statsmodels.tsa.vector_ar.vecm.vecmresults.plot_forecast#statsmodels.tsa.vector_ar.vecm.VECMResults.plot_forecast "statsmodels.tsa.vector_ar.vecm.VECMResults.plot_forecast")(steps[, alpha, plot\_conf\_int, …]) | Plot the forecast. | | [`predict`](statsmodels.tsa.vector_ar.vecm.vecmresults.predict#statsmodels.tsa.vector_ar.vecm.VECMResults.predict "statsmodels.tsa.vector_ar.vecm.VECMResults.predict")([steps, alpha, exog\_fc, exog\_coint\_fc]) | Calculate future values of the time series. | | [`pvalues_alpha`](statsmodels.tsa.vector_ar.vecm.vecmresults.pvalues_alpha#statsmodels.tsa.vector_ar.vecm.VECMResults.pvalues_alpha "statsmodels.tsa.vector_ar.vecm.VECMResults.pvalues_alpha")() | | | [`pvalues_beta`](statsmodels.tsa.vector_ar.vecm.vecmresults.pvalues_beta#statsmodels.tsa.vector_ar.vecm.VECMResults.pvalues_beta "statsmodels.tsa.vector_ar.vecm.VECMResults.pvalues_beta")() | | | [`pvalues_det_coef`](statsmodels.tsa.vector_ar.vecm.vecmresults.pvalues_det_coef#statsmodels.tsa.vector_ar.vecm.VECMResults.pvalues_det_coef "statsmodels.tsa.vector_ar.vecm.VECMResults.pvalues_det_coef")() | | | [`pvalues_det_coef_coint`](statsmodels.tsa.vector_ar.vecm.vecmresults.pvalues_det_coef_coint#statsmodels.tsa.vector_ar.vecm.VECMResults.pvalues_det_coef_coint "statsmodels.tsa.vector_ar.vecm.VECMResults.pvalues_det_coef_coint")() | | | [`pvalues_gamma`](statsmodels.tsa.vector_ar.vecm.vecmresults.pvalues_gamma#statsmodels.tsa.vector_ar.vecm.VECMResults.pvalues_gamma "statsmodels.tsa.vector_ar.vecm.VECMResults.pvalues_gamma")() | | | [`resid`](statsmodels.tsa.vector_ar.vecm.vecmresults.resid#statsmodels.tsa.vector_ar.vecm.VECMResults.resid "statsmodels.tsa.vector_ar.vecm.VECMResults.resid")() | Return the difference between observed and fitted values. | | [`stderr_alpha`](statsmodels.tsa.vector_ar.vecm.vecmresults.stderr_alpha#statsmodels.tsa.vector_ar.vecm.VECMResults.stderr_alpha "statsmodels.tsa.vector_ar.vecm.VECMResults.stderr_alpha")() | | | [`stderr_beta`](statsmodels.tsa.vector_ar.vecm.vecmresults.stderr_beta#statsmodels.tsa.vector_ar.vecm.VECMResults.stderr_beta "statsmodels.tsa.vector_ar.vecm.VECMResults.stderr_beta")() | | | [`stderr_coint`](statsmodels.tsa.vector_ar.vecm.vecmresults.stderr_coint#statsmodels.tsa.vector_ar.vecm.VECMResults.stderr_coint "statsmodels.tsa.vector_ar.vecm.VECMResults.stderr_coint")() | Standard errors of beta and deterministic terms inside the cointegration relation. | | [`stderr_det_coef`](statsmodels.tsa.vector_ar.vecm.vecmresults.stderr_det_coef#statsmodels.tsa.vector_ar.vecm.VECMResults.stderr_det_coef "statsmodels.tsa.vector_ar.vecm.VECMResults.stderr_det_coef")() | | | [`stderr_det_coef_coint`](statsmodels.tsa.vector_ar.vecm.vecmresults.stderr_det_coef_coint#statsmodels.tsa.vector_ar.vecm.VECMResults.stderr_det_coef_coint "statsmodels.tsa.vector_ar.vecm.VECMResults.stderr_det_coef_coint")() | | | [`stderr_gamma`](statsmodels.tsa.vector_ar.vecm.vecmresults.stderr_gamma#statsmodels.tsa.vector_ar.vecm.VECMResults.stderr_gamma "statsmodels.tsa.vector_ar.vecm.VECMResults.stderr_gamma")() | | | [`stderr_params`](statsmodels.tsa.vector_ar.vecm.vecmresults.stderr_params#statsmodels.tsa.vector_ar.vecm.VECMResults.stderr_params "statsmodels.tsa.vector_ar.vecm.VECMResults.stderr_params")() | | | [`summary`](statsmodels.tsa.vector_ar.vecm.vecmresults.summary#statsmodels.tsa.vector_ar.vecm.VECMResults.summary "statsmodels.tsa.vector_ar.vecm.VECMResults.summary")([alpha]) | Return a summary of the estimation results. | | [`test_granger_causality`](statsmodels.tsa.vector_ar.vecm.vecmresults.test_granger_causality#statsmodels.tsa.vector_ar.vecm.VECMResults.test_granger_causality "statsmodels.tsa.vector_ar.vecm.VECMResults.test_granger_causality")(caused[, causing, signif]) | Test for Granger-causality. | | [`test_inst_causality`](statsmodels.tsa.vector_ar.vecm.vecmresults.test_inst_causality#statsmodels.tsa.vector_ar.vecm.VECMResults.test_inst_causality "statsmodels.tsa.vector_ar.vecm.VECMResults.test_inst_causality")(causing[, signif]) | Test for instantaneous causality. | | [`test_normality`](statsmodels.tsa.vector_ar.vecm.vecmresults.test_normality#statsmodels.tsa.vector_ar.vecm.VECMResults.test_normality "statsmodels.tsa.vector_ar.vecm.VECMResults.test_normality")([signif]) | Test assumption of normal-distributed errors using Jarque-Bera-style omnibus \(\chi^2\) test. | | [`test_whiteness`](statsmodels.tsa.vector_ar.vecm.vecmresults.test_whiteness#statsmodels.tsa.vector_ar.vecm.VECMResults.test_whiteness "statsmodels.tsa.vector_ar.vecm.VECMResults.test_whiteness")([nlags, signif, adjusted]) | Test the whiteness of the residuals using the Portmanteau test. | | [`tvalues_alpha`](statsmodels.tsa.vector_ar.vecm.vecmresults.tvalues_alpha#statsmodels.tsa.vector_ar.vecm.VECMResults.tvalues_alpha "statsmodels.tsa.vector_ar.vecm.VECMResults.tvalues_alpha")() | | | [`tvalues_beta`](statsmodels.tsa.vector_ar.vecm.vecmresults.tvalues_beta#statsmodels.tsa.vector_ar.vecm.VECMResults.tvalues_beta "statsmodels.tsa.vector_ar.vecm.VECMResults.tvalues_beta")() | | | [`tvalues_det_coef`](statsmodels.tsa.vector_ar.vecm.vecmresults.tvalues_det_coef#statsmodels.tsa.vector_ar.vecm.VECMResults.tvalues_det_coef "statsmodels.tsa.vector_ar.vecm.VECMResults.tvalues_det_coef")() | | | [`tvalues_det_coef_coint`](statsmodels.tsa.vector_ar.vecm.vecmresults.tvalues_det_coef_coint#statsmodels.tsa.vector_ar.vecm.VECMResults.tvalues_det_coef_coint "statsmodels.tsa.vector_ar.vecm.VECMResults.tvalues_det_coef_coint")() | | | [`tvalues_gamma`](statsmodels.tsa.vector_ar.vecm.vecmresults.tvalues_gamma#statsmodels.tsa.vector_ar.vecm.VECMResults.tvalues_gamma "statsmodels.tsa.vector_ar.vecm.VECMResults.tvalues_gamma")() | | | [`var_rep`](statsmodels.tsa.vector_ar.vecm.vecmresults.var_rep#statsmodels.tsa.vector_ar.vecm.VECMResults.var_rep "statsmodels.tsa.vector_ar.vecm.VECMResults.var_rep")() | |
programming_docs
statsmodels statsmodels.tsa.statespace.mlemodel.MLEResults.tvalues statsmodels.tsa.statespace.mlemodel.MLEResults.tvalues ====================================================== `MLEResults.tvalues()` Return the t-statistic for a given parameter estimate. statsmodels statsmodels.sandbox.distributions.extras.SkewNorm2_gen statsmodels.sandbox.distributions.extras.SkewNorm2\_gen ======================================================= `class statsmodels.sandbox.distributions.extras.SkewNorm2_gen(momtype=1, a=None, b=None, xtol=1e-14, badvalue=None, name=None, longname=None, shapes=None, extradoc=None, seed=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/distributions/extras.html#SkewNorm2_gen) univariate Skew-Normal distribution of Azzalini class follows scipy.stats.distributions pattern #### Methods | | | | --- | --- | | [`cdf`](statsmodels.sandbox.distributions.extras.skewnorm2_gen.cdf#statsmodels.sandbox.distributions.extras.SkewNorm2_gen.cdf "statsmodels.sandbox.distributions.extras.SkewNorm2_gen.cdf")(x, \*args, \*\*kwds) | Cumulative distribution function of the given RV. | | [`entropy`](statsmodels.sandbox.distributions.extras.skewnorm2_gen.entropy#statsmodels.sandbox.distributions.extras.SkewNorm2_gen.entropy "statsmodels.sandbox.distributions.extras.SkewNorm2_gen.entropy")(\*args, \*\*kwds) | Differential entropy of the RV. | | [`expect`](statsmodels.sandbox.distributions.extras.skewnorm2_gen.expect#statsmodels.sandbox.distributions.extras.SkewNorm2_gen.expect "statsmodels.sandbox.distributions.extras.SkewNorm2_gen.expect")([func, args, loc, scale, lb, ub, …]) | Calculate expected value of a function with respect to the distribution. | | [`fit`](statsmodels.sandbox.distributions.extras.skewnorm2_gen.fit#statsmodels.sandbox.distributions.extras.SkewNorm2_gen.fit "statsmodels.sandbox.distributions.extras.SkewNorm2_gen.fit")(data, \*args, \*\*kwds) | Return MLEs for shape (if applicable), location, and scale parameters from data. | | [`fit_loc_scale`](statsmodels.sandbox.distributions.extras.skewnorm2_gen.fit_loc_scale#statsmodels.sandbox.distributions.extras.SkewNorm2_gen.fit_loc_scale "statsmodels.sandbox.distributions.extras.SkewNorm2_gen.fit_loc_scale")(data, \*args) | Estimate loc and scale parameters from data using 1st and 2nd moments. | | [`freeze`](statsmodels.sandbox.distributions.extras.skewnorm2_gen.freeze#statsmodels.sandbox.distributions.extras.SkewNorm2_gen.freeze "statsmodels.sandbox.distributions.extras.SkewNorm2_gen.freeze")(\*args, \*\*kwds) | Freeze the distribution for the given arguments. | | [`interval`](statsmodels.sandbox.distributions.extras.skewnorm2_gen.interval#statsmodels.sandbox.distributions.extras.SkewNorm2_gen.interval "statsmodels.sandbox.distributions.extras.SkewNorm2_gen.interval")(alpha, \*args, \*\*kwds) | Confidence interval with equal areas around the median. | | [`isf`](statsmodels.sandbox.distributions.extras.skewnorm2_gen.isf#statsmodels.sandbox.distributions.extras.SkewNorm2_gen.isf "statsmodels.sandbox.distributions.extras.SkewNorm2_gen.isf")(q, \*args, \*\*kwds) | Inverse survival function (inverse of `sf`) at q of the given RV. | | [`logcdf`](statsmodels.sandbox.distributions.extras.skewnorm2_gen.logcdf#statsmodels.sandbox.distributions.extras.SkewNorm2_gen.logcdf "statsmodels.sandbox.distributions.extras.SkewNorm2_gen.logcdf")(x, \*args, \*\*kwds) | Log of the cumulative distribution function at x of the given RV. | | [`logpdf`](statsmodels.sandbox.distributions.extras.skewnorm2_gen.logpdf#statsmodels.sandbox.distributions.extras.SkewNorm2_gen.logpdf "statsmodels.sandbox.distributions.extras.SkewNorm2_gen.logpdf")(x, \*args, \*\*kwds) | Log of the probability density function at x of the given RV. | | [`logsf`](statsmodels.sandbox.distributions.extras.skewnorm2_gen.logsf#statsmodels.sandbox.distributions.extras.SkewNorm2_gen.logsf "statsmodels.sandbox.distributions.extras.SkewNorm2_gen.logsf")(x, \*args, \*\*kwds) | Log of the survival function of the given RV. | | [`mean`](statsmodels.sandbox.distributions.extras.skewnorm2_gen.mean#statsmodels.sandbox.distributions.extras.SkewNorm2_gen.mean "statsmodels.sandbox.distributions.extras.SkewNorm2_gen.mean")(\*args, \*\*kwds) | Mean of the distribution. | | [`median`](statsmodels.sandbox.distributions.extras.skewnorm2_gen.median#statsmodels.sandbox.distributions.extras.SkewNorm2_gen.median "statsmodels.sandbox.distributions.extras.SkewNorm2_gen.median")(\*args, \*\*kwds) | Median of the distribution. | | [`moment`](statsmodels.sandbox.distributions.extras.skewnorm2_gen.moment#statsmodels.sandbox.distributions.extras.SkewNorm2_gen.moment "statsmodels.sandbox.distributions.extras.SkewNorm2_gen.moment")(n, \*args, \*\*kwds) | n-th order non-central moment of distribution. | | [`nnlf`](statsmodels.sandbox.distributions.extras.skewnorm2_gen.nnlf#statsmodels.sandbox.distributions.extras.SkewNorm2_gen.nnlf "statsmodels.sandbox.distributions.extras.SkewNorm2_gen.nnlf")(theta, x) | Return negative loglikelihood function. | | [`pdf`](statsmodels.sandbox.distributions.extras.skewnorm2_gen.pdf#statsmodels.sandbox.distributions.extras.SkewNorm2_gen.pdf "statsmodels.sandbox.distributions.extras.SkewNorm2_gen.pdf")(x, \*args, \*\*kwds) | Probability density function at x of the given RV. | | [`ppf`](statsmodels.sandbox.distributions.extras.skewnorm2_gen.ppf#statsmodels.sandbox.distributions.extras.SkewNorm2_gen.ppf "statsmodels.sandbox.distributions.extras.SkewNorm2_gen.ppf")(q, \*args, \*\*kwds) | Percent point function (inverse of `cdf`) at q of the given RV. | | [`rvs`](statsmodels.sandbox.distributions.extras.skewnorm2_gen.rvs#statsmodels.sandbox.distributions.extras.SkewNorm2_gen.rvs "statsmodels.sandbox.distributions.extras.SkewNorm2_gen.rvs")(\*args, \*\*kwds) | Random variates of given type. | | [`sf`](statsmodels.sandbox.distributions.extras.skewnorm2_gen.sf#statsmodels.sandbox.distributions.extras.SkewNorm2_gen.sf "statsmodels.sandbox.distributions.extras.SkewNorm2_gen.sf")(x, \*args, \*\*kwds) | Survival function (1 - `cdf`) at x of the given RV. | | [`stats`](statsmodels.sandbox.distributions.extras.skewnorm2_gen.stats#statsmodels.sandbox.distributions.extras.SkewNorm2_gen.stats "statsmodels.sandbox.distributions.extras.SkewNorm2_gen.stats")(\*args, \*\*kwds) | Some statistics of the given RV. | | [`std`](statsmodels.sandbox.distributions.extras.skewnorm2_gen.std#statsmodels.sandbox.distributions.extras.SkewNorm2_gen.std "statsmodels.sandbox.distributions.extras.SkewNorm2_gen.std")(\*args, \*\*kwds) | Standard deviation of the distribution. | | [`var`](statsmodels.sandbox.distributions.extras.skewnorm2_gen.var#statsmodels.sandbox.distributions.extras.SkewNorm2_gen.var "statsmodels.sandbox.distributions.extras.SkewNorm2_gen.var")(\*args, \*\*kwds) | Variance of the distribution. | #### Attributes | | | | --- | --- | | `random_state` | Get or set the RandomState object for generating random variates. | statsmodels statsmodels.discrete.discrete_model.DiscreteResults.cov_params statsmodels.discrete.discrete\_model.DiscreteResults.cov\_params ================================================================ `DiscreteResults.cov_params(r_matrix=None, column=None, scale=None, cov_p=None, other=None)` Returns the variance/covariance matrix. The variance/covariance matrix can be of a linear contrast of the estimates of params or all params multiplied by scale which will usually be an estimate of sigma^2. Scale is assumed to be a scalar. | Parameters: | * **r\_matrix** (*array-like*) – Can be 1d, or 2d. Can be used alone or with other. * **column** (*array-like**,* *optional*) – Must be used on its own. Can be 0d or 1d see below. * **scale** (*float**,* *optional*) – Can be specified or not. Default is None, which means that the scale argument is taken from the model. * **other** (*array-like**,* *optional*) – Can be used when r\_matrix is specified. | | Returns: | **cov** – covariance matrix of the parameter estimates or of linear combination of parameter estimates. See Notes. | | Return type: | ndarray | #### Notes (The below are assumed to be in matrix notation.) If no argument is specified returns the covariance matrix of a model `(scale)*(X.T X)^(-1)` If contrast is specified it pre and post-multiplies as follows `(scale) * r_matrix (X.T X)^(-1) r_matrix.T` If contrast and other are specified returns `(scale) * r_matrix (X.T X)^(-1) other.T` If column is specified returns `(scale) * (X.T X)^(-1)[column,column]` if column is 0d OR `(scale) * (X.T X)^(-1)[column][:,column]` if column is 1d statsmodels statsmodels.regression.mixed_linear_model.MixedLMResults.normalized_cov_params statsmodels.regression.mixed\_linear\_model.MixedLMResults.normalized\_cov\_params ================================================================================== `MixedLMResults.normalized_cov_params()` statsmodels statsmodels.iolib.foreign.genfromdta statsmodels.iolib.foreign.genfromdta ==================================== `statsmodels.iolib.foreign.genfromdta(fname, missing_flt=-999.0, encoding=None, pandas=False, convert_dates=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/iolib/foreign.html#genfromdta) Returns an ndarray or DataFrame from a Stata .dta file. | Parameters: | * **fname** (*str* *or* *filehandle*) – Stata .dta file. * **missing\_flt** (*numeric*) – The numeric value to replace missing values with. Will be used for any numeric value. * **encoding** (*string**,* *optional*) – Used for Python 3 only. Encoding to use when reading the .dta file. Defaults to `locale.getpreferredencoding` * **pandas** (*bool*) – Optionally return a DataFrame instead of an ndarray * **convert\_dates** (*bool*) – If convert\_dates is True, then Stata formatted dates will be converted to datetime types according to the variable’s format. | statsmodels statsmodels.genmod.families.links.Logit.inverse statsmodels.genmod.families.links.Logit.inverse =============================================== `Logit.inverse(z)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/links.html#Logit.inverse) Inverse of the logit transform | Parameters: | **z** (*array-like*) – The value of the logit transform at `p` | | Returns: | **p** – Probabilities | | Return type: | array | #### Notes g^(-1)(z) = exp(z)/(1+exp(z)) statsmodels statsmodels.discrete.discrete_model.ProbitResults.pvalues statsmodels.discrete.discrete\_model.ProbitResults.pvalues ========================================================== `ProbitResults.pvalues()` statsmodels statsmodels.discrete.discrete_model.LogitResults.tvalues statsmodels.discrete.discrete\_model.LogitResults.tvalues ========================================================= `LogitResults.tvalues()` Return the t-statistic for a given parameter estimate. statsmodels statsmodels.regression.linear_model.OLSResults.resid statsmodels.regression.linear\_model.OLSResults.resid ===================================================== `OLSResults.resid()` statsmodels statsmodels.discrete.discrete_model.Probit.loglike statsmodels.discrete.discrete\_model.Probit.loglike =================================================== `Probit.loglike(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#Probit.loglike) Log-likelihood of probit model (i.e., the normal distribution). | Parameters: | **params** (*array-like*) – The parameters of the model. | | Returns: | **loglike** – The log-likelihood function of the model evaluated at `params`. See notes. | | Return type: | float | #### Notes \[\ln L=\sum\_{i}\ln\Phi\left(q\_{i}x\_{i}^{\prime}\beta\right)\] Where \(q=2y-1\). This simplification comes from the fact that the normal distribution is symmetric. statsmodels statsmodels.regression.linear_model.RegressionResults.get_prediction statsmodels.regression.linear\_model.RegressionResults.get\_prediction ====================================================================== `RegressionResults.get_prediction(exog=None, transform=True, weights=None, row_labels=None, **kwds)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#RegressionResults.get_prediction) compute prediction results | Parameters: | * **exog** (*array-like**,* *optional*) – The values for which you want to predict. * **transform** (*bool**,* *optional*) – If the model was fit via a formula, do you want to pass exog through the formula. Default is True. E.g., if you fit a model y ~ log(x1) + log(x2), and transform is True, then you can pass a data structure that contains x1 and x2 in their original form. Otherwise, you’d need to log the data first. * **weights** (*array\_like**,* *optional*) – Weights interpreted as in WLS, used for the variance of the predicted residual. * **kwargs** (*args**,*) – Some models can take additional arguments or keywords, see the predict method of the model for the details. | | Returns: | **prediction\_results** – The prediction results instance contains prediction and prediction variance and can on demand calculate confidence intervals and summary tables for the prediction of the mean and of new observations. | | Return type: | [linear\_model.PredictionResults](statsmodels.regression.linear_model.predictionresults#statsmodels.regression.linear_model.PredictionResults "statsmodels.regression.linear_model.PredictionResults") | statsmodels statsmodels.stats.power.TTestIndPower.solve_power statsmodels.stats.power.TTestIndPower.solve\_power ================================================== `TTestIndPower.solve_power(effect_size=None, nobs1=None, alpha=None, power=None, ratio=1.0, alternative='two-sided')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/power.html#TTestIndPower.solve_power) solve for any one parameter of the power of a two sample t-test for t-test the keywords are: effect\_size, nobs1, alpha, power, ratio exactly one needs to be `None`, all others need numeric values | Parameters: | * **effect\_size** (*float*) – standardized effect size, difference between the two means divided by the standard deviation. `effect_size` has to be positive. * **nobs1** (*int* *or* *float*) – number of observations of sample 1. The number of observations of sample two is ratio times the size of sample 1, i.e. `nobs2 = nobs1 * ratio` * **alpha** (*float in interval* *(**0**,**1**)*) – significance level, e.g. 0.05, is the probability of a type I error, that is wrong rejections if the Null Hypothesis is true. * **power** (*float in interval* *(**0**,**1**)*) – power of the test, e.g. 0.8, is one minus the probability of a type II error. Power is the probability that the test correctly rejects the Null Hypothesis if the Alternative Hypothesis is true. * **ratio** (*float*) – ratio of the number of observations in sample 2 relative to sample 1. see description of nobs1 The default for ratio is 1; to solve for ratio given the other arguments it has to be explicitly set to None. * **alternative** (*string**,* *'two-sided'* *(**default**)**,* *'larger'**,* *'smaller'*) – extra argument to choose whether the power is calculated for a two-sided (default) or one sided test. The one-sided test can be either ‘larger’, ‘smaller’. | | Returns: | **value** – The value of the parameter that was set to None in the call. The value solves the power equation given the remaining parameters. | | Return type: | float | #### Notes The function uses scipy.optimize for finding the value that satisfies the power equation. It first uses `brentq` with a prior search for bounds. If this fails to find a root, `fsolve` is used. If `fsolve` also fails, then, for `alpha`, `power` and `effect_size`, `brentq` with fixed bounds is used. However, there can still be cases where this fails. statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.conf_int statsmodels.tsa.statespace.dynamic\_factor.DynamicFactorResults.conf\_int ========================================================================= `DynamicFactorResults.conf_int(alpha=0.05, cols=None, method='default')` Returns the confidence interval of the fitted parameters. | Parameters: | * **alpha** (*float**,* *optional*) – The significance level for the confidence interval. ie., The default `alpha` = .05 returns a 95% confidence interval. * **cols** (*array-like**,* *optional*) – `cols` specifies which confidence intervals to return * **method** (*string*) – Not Implemented Yet Method to estimate the confidence\_interval. “Default” : uses self.bse which is based on inverse Hessian for MLE “hjjh” : “jac” : “boot-bse” “boot\_quant” “profile” | | Returns: | **conf\_int** – Each row contains [lower, upper] limits of the confidence interval for the corresponding parameter. The first column contains all lower, the second column contains all upper limits. | | Return type: | array | #### Examples ``` >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> results.conf_int() array([[-5496529.48322745, -1467987.78596704], [ -177.02903529, 207.15277984], [ -0.1115811 , 0.03994274], [ -3.12506664, -0.91539297], [ -1.5179487 , -0.54850503], [ -0.56251721, 0.460309 ], [ 798.7875153 , 2859.51541392]]) ``` ``` >>> results.conf_int(cols=(2,3)) array([[-0.1115811 , 0.03994274], [-3.12506664, -0.91539297]]) ``` #### Notes The confidence interval is based on the standard normal distribution. Models wish to use a different distribution should overwrite this method. statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.initialize statsmodels.tsa.statespace.dynamic\_factor.DynamicFactor.initialize =================================================================== `DynamicFactor.initialize()` Initialize (possibly re-initialize) a Model instance. For instance, the design matrix of a linear model may change and some things must be recomputed. statsmodels statsmodels.genmod.cov_struct.CovStruct.covariance_matrix_solve statsmodels.genmod.cov\_struct.CovStruct.covariance\_matrix\_solve ================================================================== `CovStruct.covariance_matrix_solve(expval, index, stdev, rhs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/cov_struct.html#CovStruct.covariance_matrix_solve) Solves matrix equations of the form `covmat * soln = rhs` and returns the values of `soln`, where `covmat` is the covariance matrix represented by this class. | Parameters: | * **expval** (*array-like*) – The expected value of endog for each observed value in the group. * **index** (*integer*) – The group index. * **stdev** (*array-like*) – The standard deviation of endog for each observation in the group. * **rhs** (*list/tuple of array-like*) – A set of right-hand sides; each defines a matrix equation to be solved. | | Returns: | **soln** – The solutions to the matrix equations. | | Return type: | list/tuple of array-like | #### Notes Returns None if the solver fails. Some dependence structures do not use `expval` and/or `index` to determine the correlation matrix. Some families (e.g. binomial) do not use the `stdev` parameter when forming the covariance matrix. If the covariance matrix is singular or not SPD, it is projected to the nearest such matrix. These projection events are recorded in the fit\_history member of the GEE model. Systems of linear equations with the covariance matrix as the left hand side (LHS) are solved for different right hand sides (RHS); the LHS is only factorized once to save time. This is a default implementation, it can be reimplemented in subclasses to optimize the linear algebra according to the struture of the covariance matrix.
programming_docs
statsmodels statsmodels.stats.outliers_influence.OLSInfluence.ess_press statsmodels.stats.outliers\_influence.OLSInfluence.ess\_press ============================================================= `OLSInfluence.ess_press()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/outliers_influence.html#OLSInfluence.ess_press) (cached attribute) error sum of squares of PRESS residuals statsmodels statsmodels.genmod.bayes_mixed_glm.BinomialBayesMixedGLM.vb_elbo statsmodels.genmod.bayes\_mixed\_glm.BinomialBayesMixedGLM.vb\_elbo =================================================================== `BinomialBayesMixedGLM.vb_elbo(vb_mean, vb_sd)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/bayes_mixed_glm.html#BinomialBayesMixedGLM.vb_elbo) Returns the evidence lower bound (ELBO) for the model. statsmodels statsmodels.regression.linear_model.RegressionResults.ssr statsmodels.regression.linear\_model.RegressionResults.ssr ========================================================== `RegressionResults.ssr()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#RegressionResults.ssr) statsmodels statsmodels.regression.quantile_regression.QuantRegResults.fittedvalues statsmodels.regression.quantile\_regression.QuantRegResults.fittedvalues ======================================================================== `QuantRegResults.fittedvalues()` statsmodels statsmodels.stats.contingency_tables.StratifiedTable.logodds_pooled_confint statsmodels.stats.contingency\_tables.StratifiedTable.logodds\_pooled\_confint ============================================================================== `StratifiedTable.logodds_pooled_confint(alpha=0.05, method='normal')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#StratifiedTable.logodds_pooled_confint) A confidence interval for the pooled log odds ratio. | Parameters: | * **alpha** (*float*) – `1 - alpha` is the nominal coverage probability of the interval. * **method** (*string*) – The method for producing the confidence interval. Currently must be ‘normal’ which uses the normal approximation. | | Returns: | * **lcb** (*float*) – The lower confidence limit. * **ucb** (*float*) – The upper confidence limit. | statsmodels statsmodels.regression.recursive_ls.RecursiveLSResults.aic statsmodels.regression.recursive\_ls.RecursiveLSResults.aic =========================================================== `RecursiveLSResults.aic()` (float) Akaike Information Criterion statsmodels statsmodels.discrete.discrete_model.Poisson.hessian statsmodels.discrete.discrete\_model.Poisson.hessian ==================================================== `Poisson.hessian(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#Poisson.hessian) Poisson model Hessian matrix of the loglikelihood | Parameters: | **params** (*array-like*) – The parameters of the model | | Returns: | **hess** – The Hessian, second derivative of loglikelihood function, evaluated at `params` | | Return type: | ndarray, (k\_vars, k\_vars) | #### Notes \[\frac{\partial^{2}\ln L}{\partial\beta\partial\beta^{\prime}}=-\sum\_{i=1}^{n}\lambda\_{i}x\_{i}x\_{i}^{\prime}\] where the loglinear model is assumed \[\ln\lambda\_{i}=x\_{i}\beta\] statsmodels statsmodels.genmod.cov_struct.CovStruct.covariance_matrix statsmodels.genmod.cov\_struct.CovStruct.covariance\_matrix =========================================================== `CovStruct.covariance_matrix(endog_expval, index)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/cov_struct.html#CovStruct.covariance_matrix) Returns the working covariance or correlation matrix for a given cluster of data. | Parameters: | * **endog\_expval** (*array-like*) – The expected values of endog for the cluster for which the covariance or correlation matrix will be returned * **index** (*integer*) – The index of the cluster for which the covariane or correlation matrix will be returned | | Returns: | * **M** (*matrix*) – The covariance or correlation matrix of endog * **is\_cor** (*bool*) – True if M is a correlation matrix, False if M is a covariance matrix | statsmodels statsmodels.sandbox.tsa.fftarma.ArmaFft.pacf statsmodels.sandbox.tsa.fftarma.ArmaFft.pacf ============================================ `ArmaFft.pacf(lags=None)` Partial autocorrelation function of an ARMA process | Parameters: | * **ar** (*array\_like**,* *1d*) – coefficient for autoregressive lag polynomial, including zero lag * **ma** (*array\_like**,* *1d*) – coefficient for moving-average lag polynomial, including zero lag * **lags** (*int*) – number of terms (lags plus zero lag) to include in returned pacf | | Returns: | **pacf** – partial autocorrelation of ARMA process given by ar, ma | | Return type: | array | #### Notes solves yule-walker equation for each lag order up to nobs lags not tested/checked yet statsmodels statsmodels.genmod.families.family.InverseGaussian statsmodels.genmod.families.family.InverseGaussian ================================================== `class statsmodels.genmod.families.family.InverseGaussian(link=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/family.html#InverseGaussian) InverseGaussian exponential family. | Parameters: | **link** (*a link instance**,* *optional*) – The default link for the inverse Gaussian family is the inverse squared link. Available links are inverse\_squared, inverse, log, and identity. See statsmodels.genmod.families.links for more information. | `link` *a link instance* – The link function of the inverse Gaussian instance `variance` *varfunc instance* – `variance` is an instance of statsmodels.genmod.families.varfuncs.mu\_cubed See also [`statsmodels.genmod.families.family.Family`](statsmodels.genmod.families.family.family#statsmodels.genmod.families.family.Family "statsmodels.genmod.families.family.Family"), [Link Functions](../glm#links) #### Notes The inverse Guassian distribution is sometimes referred to in the literature as the Wald distribution. #### Methods | | | | --- | --- | | [`deviance`](statsmodels.genmod.families.family.inversegaussian.deviance#statsmodels.genmod.families.family.InverseGaussian.deviance "statsmodels.genmod.families.family.InverseGaussian.deviance")(endog, mu[, var\_weights, …]) | The deviance function evaluated at (endog, mu, var\_weights, freq\_weights, scale) for the distribution. | | [`fitted`](statsmodels.genmod.families.family.inversegaussian.fitted#statsmodels.genmod.families.family.InverseGaussian.fitted "statsmodels.genmod.families.family.InverseGaussian.fitted")(lin\_pred) | Fitted values based on linear predictors lin\_pred. | | [`loglike`](statsmodels.genmod.families.family.inversegaussian.loglike#statsmodels.genmod.families.family.InverseGaussian.loglike "statsmodels.genmod.families.family.InverseGaussian.loglike")(endog, mu[, var\_weights, …]) | The log-likelihood function in terms of the fitted mean response. | | [`loglike_obs`](statsmodels.genmod.families.family.inversegaussian.loglike_obs#statsmodels.genmod.families.family.InverseGaussian.loglike_obs "statsmodels.genmod.families.family.InverseGaussian.loglike_obs")(endog, mu[, var\_weights, scale]) | The log-likelihood function for each observation in terms of the fitted mean response for the Inverse Gaussian distribution. | | [`predict`](statsmodels.genmod.families.family.inversegaussian.predict#statsmodels.genmod.families.family.InverseGaussian.predict "statsmodels.genmod.families.family.InverseGaussian.predict")(mu) | Linear predictors based on given mu values. | | [`resid_anscombe`](statsmodels.genmod.families.family.inversegaussian.resid_anscombe#statsmodels.genmod.families.family.InverseGaussian.resid_anscombe "statsmodels.genmod.families.family.InverseGaussian.resid_anscombe")(endog, mu[, var\_weights, scale]) | The Anscombe residuals | | [`resid_dev`](statsmodels.genmod.families.family.inversegaussian.resid_dev#statsmodels.genmod.families.family.InverseGaussian.resid_dev "statsmodels.genmod.families.family.InverseGaussian.resid_dev")(endog, mu[, var\_weights, scale]) | The deviance residuals | | [`starting_mu`](statsmodels.genmod.families.family.inversegaussian.starting_mu#statsmodels.genmod.families.family.InverseGaussian.starting_mu "statsmodels.genmod.families.family.InverseGaussian.starting_mu")(y) | Starting value for mu in the IRLS algorithm. | | [`weights`](statsmodels.genmod.families.family.inversegaussian.weights#statsmodels.genmod.families.family.InverseGaussian.weights "statsmodels.genmod.families.family.InverseGaussian.weights")(mu) | Weights for IRLS steps | statsmodels statsmodels.tsa.statespace.mlemodel.MLEModel.observed_information_matrix statsmodels.tsa.statespace.mlemodel.MLEModel.observed\_information\_matrix ========================================================================== `MLEModel.observed_information_matrix(params, transformed=True, approx_complex_step=None, approx_centered=False, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEModel.observed_information_matrix) Observed information matrix | Parameters: | * **params** (*array\_like**,* *optional*) – Array of parameters at which to evaluate the loglikelihood function. * **\*\*kwargs** – Additional keyword arguments to pass to the Kalman filter. See `KalmanFilter.filter` for more details. | #### Notes This method is from Harvey (1989), which shows that the information matrix only depends on terms from the gradient. This implementation is partially analytic and partially numeric approximation, therefore, because it uses the analytic formula for the information matrix, with numerically computed elements of the gradient. #### References Harvey, Andrew C. 1990. Forecasting, Structural Time Series Models and the Kalman Filter. Cambridge University Press. statsmodels statsmodels.robust.scale.HuberScale statsmodels.robust.scale.HuberScale =================================== `class statsmodels.robust.scale.HuberScale(d=2.5, tol=1e-08, maxiter=30)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/scale.html#HuberScale) Huber’s scaling for fitting robust linear models. Huber’s scale is intended to be used as the scale estimate in the IRLS algorithm and is slightly different than the `Huber` class. | Parameters: | * **d** (*float**,* *optional*) – d is the tuning constant for Huber’s scale. Default is 2.5 * **tol** (*float**,* *optional*) – The convergence tolerance * **maxiter** (*int**,* *optiona*) – The maximum number of iterations. The default is 30. | `call()` Return’s Huber’s scale computed as below #### Notes Huber’s scale is the iterative solution to scale\_(i+1)\*\*2 = 1/(n\*h)\*sum(chi(r/sigma\_i)\*sigma\_i\*\*2 where the Huber function is chi(x) = (x\*\*2)/2 for |x| < d chi(x) = (d\*\*2)/2 for |x| >= d and the Huber constant h = (n-p)/n\*(d\*\*2 + (1-d\*\*2)\* scipy.stats.norm.cdf(d) - .5 - d\*sqrt(2\*pi)\*exp(-0.5\*d\*\*2) #### Methods statsmodels statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoissonResults.llr_pvalue statsmodels.discrete.count\_model.ZeroInflatedGeneralizedPoissonResults.llr\_pvalue =================================================================================== `ZeroInflatedGeneralizedPoissonResults.llr_pvalue()` statsmodels statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.initialize statsmodels.discrete.count\_model.ZeroInflatedGeneralizedPoisson.initialize =========================================================================== `ZeroInflatedGeneralizedPoisson.initialize()` Initialize is called by statsmodels.model.LikelihoodModel.\_\_init\_\_ and should contain any preprocessing that needs to be done for a model. statsmodels statsmodels.sandbox.regression.gmm.IV2SLS.information statsmodels.sandbox.regression.gmm.IV2SLS.information ===================================================== `IV2SLS.information(params)` Fisher information matrix of model Returns -Hessian of loglike evaluated at params. statsmodels statsmodels.genmod.cov_struct.Autoregressive.covariance_matrix_solve statsmodels.genmod.cov\_struct.Autoregressive.covariance\_matrix\_solve ======================================================================= `Autoregressive.covariance_matrix_solve(expval, index, stdev, rhs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/cov_struct.html#Autoregressive.covariance_matrix_solve) Solves matrix equations of the form `covmat * soln = rhs` and returns the values of `soln`, where `covmat` is the covariance matrix represented by this class. | Parameters: | * **expval** (*array-like*) – The expected value of endog for each observed value in the group. * **index** (*integer*) – The group index. * **stdev** (*array-like*) – The standard deviation of endog for each observation in the group. * **rhs** (*list/tuple of array-like*) – A set of right-hand sides; each defines a matrix equation to be solved. | | Returns: | **soln** – The solutions to the matrix equations. | | Return type: | list/tuple of array-like | #### Notes Returns None if the solver fails. Some dependence structures do not use `expval` and/or `index` to determine the correlation matrix. Some families (e.g. binomial) do not use the `stdev` parameter when forming the covariance matrix. If the covariance matrix is singular or not SPD, it is projected to the nearest such matrix. These projection events are recorded in the fit\_history member of the GEE model. Systems of linear equations with the covariance matrix as the left hand side (LHS) are solved for different right hand sides (RHS); the LHS is only factorized once to save time. This is a default implementation, it can be reimplemented in subclasses to optimize the linear algebra according to the struture of the covariance matrix. statsmodels statsmodels.tsa.holtwinters.ExponentialSmoothing.score statsmodels.tsa.holtwinters.ExponentialSmoothing.score ====================================================== `ExponentialSmoothing.score(params)` Score vector of model. The gradient of logL with respect to each parameter. statsmodels statsmodels.tsa.holtwinters.SimpleExpSmoothing.predict statsmodels.tsa.holtwinters.SimpleExpSmoothing.predict ====================================================== `SimpleExpSmoothing.predict(params, start=None, end=None)` Returns in-sample and out-of-sample prediction. | Parameters: | * **params** (*array*) – The fitted model parameters. * **start** (*int**,* *str**, or* *datetime*) – Zero-indexed observation number at which to start forecasting, ie., the first forecast is start. Can also be a date string to parse or a datetime type. * **end** (*int**,* *str**, or* *datetime*) – Zero-indexed observation number at which to end forecasting, ie., the first forecast is start. Can also be a date string to parse or a datetime type. | | Returns: | **predicted values** | | Return type: | array | statsmodels statsmodels.graphics.gofplots.ProbPlot.qqplot statsmodels.graphics.gofplots.ProbPlot.qqplot ============================================= `ProbPlot.qqplot(xlabel=None, ylabel=None, line=None, other=None, ax=None, **plotkwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/graphics/gofplots.html#ProbPlot.qqplot) Q-Q plot of the quantiles of x versus the quantiles/ppf of a distribution or the quantiles of another `ProbPlot` instance. | Parameters: | * **ylabel** (*xlabel**,*) – User-provided lables for the x-axis and y-axis. If None (default), other values are used depending on the status of the kwarg `other`. * **line** (*str {'45'**,* *'s'**,* *'r'**,* *q'}* *or* *None**,* *optional*) – Options for the reference line to which the data is compared: + ‘45’ - 45-degree line + ’s‘ - standardized line, the expected order statistics are scaled by the standard deviation of the given sample and have the mean added to them + ’r’ - A regression line is fit + ’q’ - A line is fit through the quartiles. + None - by default no reference line is added to the plot. * **other** (`ProbPlot` instance, array-like, or None, optional) – If provided, the sample quantiles of this `ProbPlot` instance are plotted against the sample quantiles of the `other` `ProbPlot` instance. If an array-like object is provided, it will be turned into a `ProbPlot` instance using default parameters. If not provided (default), the theoretical quantiles are used. * **ax** (*Matplotlib AxesSubplot instance**,* *optional*) – If given, this subplot is used to plot in instead of a new figure being created. * **\*\*plotkwargs** (*additional matplotlib arguments to be passed to the*) – `plot` command. | | Returns: | **fig** – If `ax` is None, the created figure. Otherwise the figure to which `ax` is connected. | | Return type: | Matplotlib figure instance | statsmodels statsmodels.discrete.discrete_model.BinaryResults.t_test_pairwise statsmodels.discrete.discrete\_model.BinaryResults.t\_test\_pairwise ==================================================================== `BinaryResults.t_test_pairwise(term_name, method='hs', alpha=0.05, factor_labels=None)` perform pairwise t\_test with multiple testing corrected p-values This uses the formula design\_info encoding contrast matrix and should work for all encodings of a main effect. | Parameters: | * **result** (*result instance*) – The results of an estimated model with a categorical main effect. * **term\_name** (*str*) – name of the term for which pairwise comparisons are computed. Term names for categorical effects are created by patsy and correspond to the main part of the exog names. * **method** (*str* *or* *list of strings*) – multiple testing p-value correction, default is ‘hs’, see stats.multipletesting * **alpha** (*float*) – significance level for multiple testing reject decision. * **factor\_labels** (*None**,* *list of str*) – Labels for the factor levels used for pairwise labels. If not provided, then the labels from the formula design\_info are used. | | Returns: | **results** – The results are stored as attributes, the main attributes are the following two. Other attributes are added for debugging purposes or as background information.* result\_frame : pandas DataFrame with t\_test results and multiple testing corrected p-values. * contrasts : matrix of constraints of the null hypothesis in the t\_test. | | Return type: | instance of a simple Results class | #### Notes Status: experimental. Currently only checked for treatment coding with and without specified reference level. Currently there are no multiple testing corrected confidence intervals available. #### Examples ``` >>> res = ols("np.log(Days+1) ~ C(Weight) + C(Duration)", data).fit() >>> pw = res.t_test_pairwise("C(Weight)") >>> pw.result_frame coef std err t P>|t| Conf. Int. Low 2-1 0.632315 0.230003 2.749157 8.028083e-03 0.171563 3-1 1.302555 0.230003 5.663201 5.331513e-07 0.841803 3-2 0.670240 0.230003 2.914044 5.119126e-03 0.209488 Conf. Int. Upp. pvalue-hs reject-hs 2-1 1.093067 0.010212 True 3-1 1.763307 0.000002 True 3-2 1.130992 0.010212 True ``` statsmodels statsmodels.tsa.vector_ar.var_model.VARResults.intercept_longrun statsmodels.tsa.vector\_ar.var\_model.VARResults.intercept\_longrun =================================================================== `VARResults.intercept_longrun()` Long run intercept of stable VAR process Lütkepohl eq. 2.1.23 \[\mu = (I - A\_1 - \dots - A\_p)^{-1} \alpha\] where alpha is the intercept (parameter of the constant)
programming_docs
statsmodels statsmodels.discrete.discrete_model.NegativeBinomialResults.conf_int statsmodels.discrete.discrete\_model.NegativeBinomialResults.conf\_int ====================================================================== `NegativeBinomialResults.conf_int(alpha=0.05, cols=None, method='default')` Returns the confidence interval of the fitted parameters. | Parameters: | * **alpha** (*float**,* *optional*) – The significance level for the confidence interval. ie., The default `alpha` = .05 returns a 95% confidence interval. * **cols** (*array-like**,* *optional*) – `cols` specifies which confidence intervals to return * **method** (*string*) – Not Implemented Yet Method to estimate the confidence\_interval. “Default” : uses self.bse which is based on inverse Hessian for MLE “hjjh” : “jac” : “boot-bse” “boot\_quant” “profile” | | Returns: | **conf\_int** – Each row contains [lower, upper] limits of the confidence interval for the corresponding parameter. The first column contains all lower, the second column contains all upper limits. | | Return type: | array | #### Examples ``` >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> results.conf_int() array([[-5496529.48322745, -1467987.78596704], [ -177.02903529, 207.15277984], [ -0.1115811 , 0.03994274], [ -3.12506664, -0.91539297], [ -1.5179487 , -0.54850503], [ -0.56251721, 0.460309 ], [ 798.7875153 , 2859.51541392]]) ``` ``` >>> results.conf_int(cols=(2,3)) array([[-0.1115811 , 0.03994274], [-3.12506664, -0.91539297]]) ``` #### Notes The confidence interval is based on the standard normal distribution. Models wish to use a different distribution should overwrite this method. statsmodels statsmodels.genmod.families.family.NegativeBinomial statsmodels.genmod.families.family.NegativeBinomial =================================================== `class statsmodels.genmod.families.family.NegativeBinomial(link=None, alpha=1.0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/family.html#NegativeBinomial) Negative Binomial exponential family. | Parameters: | * **link** (*a link instance**,* *optional*) – The default link for the negative binomial family is the log link. Available links are log, cloglog, identity, nbinom and power. See statsmodels.genmod.families.links for more information. * **alpha** (*float**,* *optional*) – The ancillary parameter for the negative binomial distribution. For now `alpha` is assumed to be nonstochastic. The default value is 1. Permissible values are usually assumed to be between .01 and 2. | `link` *a link instance* – The link function of the negative binomial instance `variance` *varfunc instance* – `variance` is an instance of statsmodels.genmod.families.varfuncs.nbinom See also [`statsmodels.genmod.families.family.Family`](statsmodels.genmod.families.family.family#statsmodels.genmod.families.family.Family "statsmodels.genmod.families.family.Family"), [Link Functions](../glm#links) #### Notes Power link functions are not yet supported. Parameterization for \(y=0, 1, 2, \ldots\) is \[f(y) = \frac{\Gamma(y+\frac{1}{\alpha})}{y!\Gamma(\frac{1}{\alpha})} \left(\frac{1}{1+\alpha\mu}\right)^{\frac{1}{\alpha}} \left(\frac{\alpha\mu}{1+\alpha\mu}\right)^y\] with \(E[Y]=\mu\,\) and \(Var[Y]=\mu+\alpha\mu^2\). #### Methods | | | | --- | --- | | [`deviance`](statsmodels.genmod.families.family.negativebinomial.deviance#statsmodels.genmod.families.family.NegativeBinomial.deviance "statsmodels.genmod.families.family.NegativeBinomial.deviance")(endog, mu[, var\_weights, …]) | The deviance function evaluated at (endog, mu, var\_weights, freq\_weights, scale) for the distribution. | | [`fitted`](statsmodels.genmod.families.family.negativebinomial.fitted#statsmodels.genmod.families.family.NegativeBinomial.fitted "statsmodels.genmod.families.family.NegativeBinomial.fitted")(lin\_pred) | Fitted values based on linear predictors lin\_pred. | | [`loglike`](statsmodels.genmod.families.family.negativebinomial.loglike#statsmodels.genmod.families.family.NegativeBinomial.loglike "statsmodels.genmod.families.family.NegativeBinomial.loglike")(endog, mu[, var\_weights, …]) | The log-likelihood function in terms of the fitted mean response. | | [`loglike_obs`](statsmodels.genmod.families.family.negativebinomial.loglike_obs#statsmodels.genmod.families.family.NegativeBinomial.loglike_obs "statsmodels.genmod.families.family.NegativeBinomial.loglike_obs")(endog, mu[, var\_weights, scale]) | The log-likelihood function for each observation in terms of the fitted mean response for the Negative Binomial distribution. | | [`predict`](statsmodels.genmod.families.family.negativebinomial.predict#statsmodels.genmod.families.family.NegativeBinomial.predict "statsmodels.genmod.families.family.NegativeBinomial.predict")(mu) | Linear predictors based on given mu values. | | [`resid_anscombe`](statsmodels.genmod.families.family.negativebinomial.resid_anscombe#statsmodels.genmod.families.family.NegativeBinomial.resid_anscombe "statsmodels.genmod.families.family.NegativeBinomial.resid_anscombe")(endog, mu[, var\_weights, scale]) | The Anscombe residuals | | [`resid_dev`](statsmodels.genmod.families.family.negativebinomial.resid_dev#statsmodels.genmod.families.family.NegativeBinomial.resid_dev "statsmodels.genmod.families.family.NegativeBinomial.resid_dev")(endog, mu[, var\_weights, scale]) | The deviance residuals | | [`starting_mu`](statsmodels.genmod.families.family.negativebinomial.starting_mu#statsmodels.genmod.families.family.NegativeBinomial.starting_mu "statsmodels.genmod.families.family.NegativeBinomial.starting_mu")(y) | Starting value for mu in the IRLS algorithm. | | [`weights`](statsmodels.genmod.families.family.negativebinomial.weights#statsmodels.genmod.families.family.NegativeBinomial.weights "statsmodels.genmod.families.family.NegativeBinomial.weights")(mu) | Weights for IRLS steps | statsmodels statsmodels.regression.recursive_ls.RecursiveLSResults.plot_diagnostics statsmodels.regression.recursive\_ls.RecursiveLSResults.plot\_diagnostics ========================================================================= `RecursiveLSResults.plot_diagnostics(variable=0, lags=10, fig=None, figsize=None)` Diagnostic plots for standardized residuals of one endogenous variable | Parameters: | * **variable** (*integer**,* *optional*) – Index of the endogenous variable for which the diagnostic plots should be created. Default is 0. * **lags** (*integer**,* *optional*) – Number of lags to include in the correlogram. Default is 10. * **fig** (*Matplotlib Figure instance**,* *optional*) – If given, subplots are created in this figure instead of in a new figure. Note that the 2x2 grid will be created in the provided figure using `fig.add_subplot()`. * **figsize** (*tuple**,* *optional*) – If a figure is created, this argument allows specifying a size. The tuple is (width, height). | #### Notes Produces a 2x2 plot grid with the following plots (ordered clockwise from top left): 1. Standardized residuals over time 2. Histogram plus estimated density of standardized residulas, along with a Normal(0,1) density plotted for reference. 3. Normal Q-Q plot, with Normal reference line. 4. Correlogram See also [`statsmodels.graphics.gofplots.qqplot`](statsmodels.graphics.gofplots.qqplot#statsmodels.graphics.gofplots.qqplot "statsmodels.graphics.gofplots.qqplot"), [`statsmodels.graphics.tsaplots.plot_acf`](statsmodels.graphics.tsaplots.plot_acf#statsmodels.graphics.tsaplots.plot_acf "statsmodels.graphics.tsaplots.plot_acf") statsmodels statsmodels.tsa.statespace.structural.UnobservedComponents.fit statsmodels.tsa.statespace.structural.UnobservedComponents.fit ============================================================== `UnobservedComponents.fit(start_params=None, transformed=True, cov_type='opg', cov_kwds=None, method='lbfgs', maxiter=50, full_output=1, disp=5, callback=None, return_params=False, optim_score=None, optim_complex_step=None, optim_hessian=None, flags=None, **kwargs)` Fits the model by maximum likelihood via Kalman filter. | Parameters: | * **start\_params** (*array\_like**,* *optional*) – Initial guess of the solution for the loglikelihood maximization. If None, the default is given by Model.start\_params. * **transformed** (*boolean**,* *optional*) – Whether or not `start_params` is already transformed. Default is True. * **cov\_type** (*str**,* *optional*) – The `cov_type` keyword governs the method for calculating the covariance matrix of parameter estimates. Can be one of: + ’opg’ for the outer product of gradient estimator + ’oim’ for the observed information matrix estimator, calculated using the method of Harvey (1989) + ’approx’ for the observed information matrix estimator, calculated using a numerical approximation of the Hessian matrix. + ’robust’ for an approximate (quasi-maximum likelihood) covariance matrix that may be valid even in the presense of some misspecifications. Intermediate calculations use the ‘oim’ method. + ’robust\_approx’ is the same as ‘robust’ except that the intermediate calculations use the ‘approx’ method. + ’none’ for no covariance matrix calculation. * **cov\_kwds** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)") *or* *None**,* *optional*) – A dictionary of arguments affecting covariance matrix computation. **opg, oim, approx, robust, robust\_approx** + ’approx\_complex\_step’ : boolean, optional - If True, numerical approximations are computed using complex-step methods. If False, numerical approximations are computed using finite difference methods. Default is True. + ’approx\_centered’ : boolean, optional - If True, numerical approximations computed using finite difference methods use a centered approximation. Default is False. * **method** (*str**,* *optional*) – The `method` determines which solver from `scipy.optimize` is used, and it can be chosen from among the following strings: + ’newton’ for Newton-Raphson, ‘nm’ for Nelder-Mead + ’bfgs’ for Broyden-Fletcher-Goldfarb-Shanno (BFGS) + ’lbfgs’ for limited-memory BFGS with optional box constraints + ’powell’ for modified Powell’s method + ’cg’ for conjugate gradient + ’ncg’ for Newton-conjugate gradient + ’basinhopping’ for global basin-hopping solverThe explicit arguments in `fit` are passed to the solver, with the exception of the basin-hopping solver. Each solver has several optional arguments that are not the same across solvers. See the notes section below (or scipy.optimize) for the available arguments and for the list of explicit arguments that the basin-hopping solver supports. * **maxiter** (*int**,* *optional*) – The maximum number of iterations to perform. * **full\_output** (*boolean**,* *optional*) – Set to True to have all available output in the Results object’s mle\_retvals attribute. The output is dependent on the solver. See LikelihoodModelResults notes section for more information. * **disp** (*boolean**,* *optional*) – Set to True to print convergence messages. * **callback** (*callable callback**(**xk**)**,* *optional*) – Called after each iteration, as callback(xk), where xk is the current parameter vector. * **return\_params** (*boolean**,* *optional*) – Whether or not to return only the array of maximizing parameters. Default is False. * **optim\_score** (*{'harvey'**,* *'approx'}* *or* *None**,* *optional*) – The method by which the score vector is calculated. ‘harvey’ uses the method from Harvey (1989), ‘approx’ uses either finite difference or complex step differentiation depending upon the value of `optim_complex_step`, and None uses the built-in gradient approximation of the optimizer. Default is None. This keyword is only relevant if the optimization method uses the score. * **optim\_complex\_step** (*bool**,* *optional*) – Whether or not to use complex step differentiation when approximating the score; if False, finite difference approximation is used. Default is True. This keyword is only relevant if `optim_score` is set to ‘harvey’ or ‘approx’. * **optim\_hessian** (*{'opg'**,**'oim'**,**'approx'}**,* *optional*) – The method by which the Hessian is numerically approximated. ‘opg’ uses outer product of gradients, ‘oim’ uses the information matrix formula from Harvey (1989), and ‘approx’ uses numerical approximation. This keyword is only relevant if the optimization method uses the Hessian matrix. * **\*\*kwargs** – Additional keyword arguments to pass to the optimizer. | | Returns: | | | Return type: | [MLEResults](statsmodels.tsa.statespace.mlemodel.mleresults#statsmodels.tsa.statespace.mlemodel.MLEResults "statsmodels.tsa.statespace.mlemodel.MLEResults") | See also [`statsmodels.base.model.LikelihoodModel.fit`](http://www.statsmodels.org/stable/dev/generated/statsmodels.base.model.LikelihoodModel.fit.html#statsmodels.base.model.LikelihoodModel.fit "statsmodels.base.model.LikelihoodModel.fit"), `MLEResults` statsmodels statsmodels.genmod.generalized_estimating_equations.GEEResults.pvalues statsmodels.genmod.generalized\_estimating\_equations.GEEResults.pvalues ======================================================================== `GEEResults.pvalues()` statsmodels statsmodels.genmod.bayes_mixed_glm.PoissonBayesMixedGLM.vb_elbo_grad_base statsmodels.genmod.bayes\_mixed\_glm.PoissonBayesMixedGLM.vb\_elbo\_grad\_base ============================================================================== `PoissonBayesMixedGLM.vb_elbo_grad_base(h, tm, tv, fep_mean, vcp_mean, vc_mean, fep_sd, vcp_sd, vc_sd)` Return the gradient of the ELBO function. See vb\_elbo\_base for parameters. statsmodels statsmodels.tsa.vector_ar.var_model.VAR.predict statsmodels.tsa.vector\_ar.var\_model.VAR.predict ================================================= `VAR.predict(params, start=None, end=None, lags=1, trend='c')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/var_model.html#VAR.predict) Returns in-sample predictions or forecasts statsmodels statsmodels.discrete.discrete_model.CountResults.fittedvalues statsmodels.discrete.discrete\_model.CountResults.fittedvalues ============================================================== `CountResults.fittedvalues()` statsmodels statsmodels.tsa.ar_model.ARResults.conf_int statsmodels.tsa.ar\_model.ARResults.conf\_int ============================================= `ARResults.conf_int(alpha=0.05, cols=None, method='default')` Returns the confidence interval of the fitted parameters. | Parameters: | * **alpha** (*float**,* *optional*) – The significance level for the confidence interval. ie., The default `alpha` = .05 returns a 95% confidence interval. * **cols** (*array-like**,* *optional*) – `cols` specifies which confidence intervals to return * **method** (*string*) – Not Implemented Yet Method to estimate the confidence\_interval. “Default” : uses self.bse which is based on inverse Hessian for MLE “hjjh” : “jac” : “boot-bse” “boot\_quant” “profile” | | Returns: | **conf\_int** – Each row contains [lower, upper] limits of the confidence interval for the corresponding parameter. The first column contains all lower, the second column contains all upper limits. | | Return type: | array | #### Examples ``` >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> results.conf_int() array([[-5496529.48322745, -1467987.78596704], [ -177.02903529, 207.15277984], [ -0.1115811 , 0.03994274], [ -3.12506664, -0.91539297], [ -1.5179487 , -0.54850503], [ -0.56251721, 0.460309 ], [ 798.7875153 , 2859.51541392]]) ``` ``` >>> results.conf_int(cols=(2,3)) array([[-0.1115811 , 0.03994274], [-3.12506664, -0.91539297]]) ``` #### Notes The confidence interval is based on the standard normal distribution. Models wish to use a different distribution should overwrite this method. statsmodels statsmodels.tsa.statespace.sarimax.SARIMAXResults.fittedvalues statsmodels.tsa.statespace.sarimax.SARIMAXResults.fittedvalues ============================================================== `SARIMAXResults.fittedvalues()` (array) The predicted values of the model. An (nobs x k\_endog) array. statsmodels statsmodels.tsa.vector_ar.var_model.VARProcess statsmodels.tsa.vector\_ar.var\_model.VARProcess ================================================ `class statsmodels.tsa.vector_ar.var_model.VARProcess(coefs, coefs_exog, sigma_u, names=None, _params_info=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/var_model.html#VARProcess) Class represents a known VAR(p) process | Parameters: | * **coefs** (*ndarray* *(**p x k x k**)*) – coefficients for lags of endog, part or params reshaped * **coefs\_exog** (*ndarray*) – parameters for trend and user provided exog * **sigma\_u** (*ndarray* *(**k x k**)*) – residual covariance * **names** (*sequence* *(**length k**)*) – * **\_params\_info** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")) – internal dict to provide information about the composition of `params`, specifically `k_trend` (trend order) and `k_exog_user` (the number of exog variables provided by the user). If it is None, then coefs\_exog are assumed to be for the intercept and trend. | | Returns: | | | Return type: | \*\*Attributes\*\* | #### Methods | | | | --- | --- | | [`acf`](statsmodels.tsa.vector_ar.var_model.varprocess.acf#statsmodels.tsa.vector_ar.var_model.VARProcess.acf "statsmodels.tsa.vector_ar.var_model.VARProcess.acf")([nlags]) | Compute theoretical autocovariance function | | [`acorr`](statsmodels.tsa.vector_ar.var_model.varprocess.acorr#statsmodels.tsa.vector_ar.var_model.VARProcess.acorr "statsmodels.tsa.vector_ar.var_model.VARProcess.acorr")([nlags]) | Compute theoretical autocorrelation function | | [`forecast`](statsmodels.tsa.vector_ar.var_model.varprocess.forecast#statsmodels.tsa.vector_ar.var_model.VARProcess.forecast "statsmodels.tsa.vector_ar.var_model.VARProcess.forecast")(y, steps[, exog\_future]) | Produce linear minimum MSE forecasts for desired number of steps ahead, using prior values y | | [`forecast_cov`](statsmodels.tsa.vector_ar.var_model.varprocess.forecast_cov#statsmodels.tsa.vector_ar.var_model.VARProcess.forecast_cov "statsmodels.tsa.vector_ar.var_model.VARProcess.forecast_cov")(steps) | Compute theoretical forecast error variance matrices | | [`forecast_interval`](statsmodels.tsa.vector_ar.var_model.varprocess.forecast_interval#statsmodels.tsa.vector_ar.var_model.VARProcess.forecast_interval "statsmodels.tsa.vector_ar.var_model.VARProcess.forecast_interval")(y, steps[, alpha, exog\_future]) | Construct forecast interval estimates assuming the y are Gaussian | | [`get_eq_index`](statsmodels.tsa.vector_ar.var_model.varprocess.get_eq_index#statsmodels.tsa.vector_ar.var_model.VARProcess.get_eq_index "statsmodels.tsa.vector_ar.var_model.VARProcess.get_eq_index")(name) | Return integer position of requested equation name | | [`intercept_longrun`](statsmodels.tsa.vector_ar.var_model.varprocess.intercept_longrun#statsmodels.tsa.vector_ar.var_model.VARProcess.intercept_longrun "statsmodels.tsa.vector_ar.var_model.VARProcess.intercept_longrun")() | Long run intercept of stable VAR process | | [`is_stable`](statsmodels.tsa.vector_ar.var_model.varprocess.is_stable#statsmodels.tsa.vector_ar.var_model.VARProcess.is_stable "statsmodels.tsa.vector_ar.var_model.VARProcess.is_stable")([verbose]) | Determine stability based on model coefficients | | [`long_run_effects`](statsmodels.tsa.vector_ar.var_model.varprocess.long_run_effects#statsmodels.tsa.vector_ar.var_model.VARProcess.long_run_effects "statsmodels.tsa.vector_ar.var_model.VARProcess.long_run_effects")() | Compute long-run effect of unit impulse | | [`ma_rep`](statsmodels.tsa.vector_ar.var_model.varprocess.ma_rep#statsmodels.tsa.vector_ar.var_model.VARProcess.ma_rep "statsmodels.tsa.vector_ar.var_model.VARProcess.ma_rep")([maxn]) | Compute MA(\(\infty\)) coefficient matrices | | [`mean`](statsmodels.tsa.vector_ar.var_model.varprocess.mean#statsmodels.tsa.vector_ar.var_model.VARProcess.mean "statsmodels.tsa.vector_ar.var_model.VARProcess.mean")() | Long run intercept of stable VAR process | | [`mse`](statsmodels.tsa.vector_ar.var_model.varprocess.mse#statsmodels.tsa.vector_ar.var_model.VARProcess.mse "statsmodels.tsa.vector_ar.var_model.VARProcess.mse")(steps) | Compute theoretical forecast error variance matrices | | [`orth_ma_rep`](statsmodels.tsa.vector_ar.var_model.varprocess.orth_ma_rep#statsmodels.tsa.vector_ar.var_model.VARProcess.orth_ma_rep "statsmodels.tsa.vector_ar.var_model.VARProcess.orth_ma_rep")([maxn, P]) | Compute orthogonalized MA coefficient matrices using P matrix such that \(\Sigma\_u = PP^\prime\). | | [`plot_acorr`](statsmodels.tsa.vector_ar.var_model.varprocess.plot_acorr#statsmodels.tsa.vector_ar.var_model.VARProcess.plot_acorr "statsmodels.tsa.vector_ar.var_model.VARProcess.plot_acorr")([nlags, linewidth]) | Plot theoretical autocorrelation function | | [`plotsim`](statsmodels.tsa.vector_ar.var_model.varprocess.plotsim#statsmodels.tsa.vector_ar.var_model.VARProcess.plotsim "statsmodels.tsa.vector_ar.var_model.VARProcess.plotsim")([steps, offset, seed]) | Plot a simulation from the VAR(p) process for the desired number of steps | | [`simulate_var`](statsmodels.tsa.vector_ar.var_model.varprocess.simulate_var#statsmodels.tsa.vector_ar.var_model.VARProcess.simulate_var "statsmodels.tsa.vector_ar.var_model.VARProcess.simulate_var")([steps, offset, seed]) | simulate the VAR(p) process for the desired number of steps | | [`to_vecm`](statsmodels.tsa.vector_ar.var_model.varprocess.to_vecm#statsmodels.tsa.vector_ar.var_model.VARProcess.to_vecm "statsmodels.tsa.vector_ar.var_model.VARProcess.to_vecm")() | |
programming_docs
statsmodels statsmodels.miscmodels.count.PoissonZiGMLE statsmodels.miscmodels.count.PoissonZiGMLE ========================================== `class statsmodels.miscmodels.count.PoissonZiGMLE(endog, exog=None, offset=None, missing='none', **kwds)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/miscmodels/count.html#PoissonZiGMLE) Maximum Likelihood Estimation of Poisson Model This is an example for generic MLE which has the same statistical model as discretemod.Poisson but adds offset and zero-inflation. Except for defining the negative log-likelihood method, all methods and results are generic. Gradients and Hessian and all resulting statistics are based on numerical differentiation. There are numerical problems if there is no zero-inflation. #### Methods | | | | --- | --- | | [`expandparams`](statsmodels.miscmodels.count.poissonzigmle.expandparams#statsmodels.miscmodels.count.PoissonZiGMLE.expandparams "statsmodels.miscmodels.count.PoissonZiGMLE.expandparams")(params) | expand to full parameter array when some parameters are fixed | | [`fit`](statsmodels.miscmodels.count.poissonzigmle.fit#statsmodels.miscmodels.count.PoissonZiGMLE.fit "statsmodels.miscmodels.count.PoissonZiGMLE.fit")([start\_params, method, maxiter, …]) | Fit the model using maximum likelihood. | | [`from_formula`](statsmodels.miscmodels.count.poissonzigmle.from_formula#statsmodels.miscmodels.count.PoissonZiGMLE.from_formula "statsmodels.miscmodels.count.PoissonZiGMLE.from_formula")(formula, data[, subset, drop\_cols]) | Create a Model from a formula and dataframe. | | [`hessian`](statsmodels.miscmodels.count.poissonzigmle.hessian#statsmodels.miscmodels.count.PoissonZiGMLE.hessian "statsmodels.miscmodels.count.PoissonZiGMLE.hessian")(params) | Hessian of log-likelihood evaluated at params | | [`hessian_factor`](statsmodels.miscmodels.count.poissonzigmle.hessian_factor#statsmodels.miscmodels.count.PoissonZiGMLE.hessian_factor "statsmodels.miscmodels.count.PoissonZiGMLE.hessian_factor")(params[, scale, observed]) | Weights for calculating Hessian | | [`information`](statsmodels.miscmodels.count.poissonzigmle.information#statsmodels.miscmodels.count.PoissonZiGMLE.information "statsmodels.miscmodels.count.PoissonZiGMLE.information")(params) | Fisher information matrix of model | | [`initialize`](statsmodels.miscmodels.count.poissonzigmle.initialize#statsmodels.miscmodels.count.PoissonZiGMLE.initialize "statsmodels.miscmodels.count.PoissonZiGMLE.initialize")() | Initialize (possibly re-initialize) a Model instance. | | [`loglike`](statsmodels.miscmodels.count.poissonzigmle.loglike#statsmodels.miscmodels.count.PoissonZiGMLE.loglike "statsmodels.miscmodels.count.PoissonZiGMLE.loglike")(params) | Log-likelihood of model. | | [`loglikeobs`](statsmodels.miscmodels.count.poissonzigmle.loglikeobs#statsmodels.miscmodels.count.PoissonZiGMLE.loglikeobs "statsmodels.miscmodels.count.PoissonZiGMLE.loglikeobs")(params) | | | [`nloglike`](statsmodels.miscmodels.count.poissonzigmle.nloglike#statsmodels.miscmodels.count.PoissonZiGMLE.nloglike "statsmodels.miscmodels.count.PoissonZiGMLE.nloglike")(params) | | | [`nloglikeobs`](statsmodels.miscmodels.count.poissonzigmle.nloglikeobs#statsmodels.miscmodels.count.PoissonZiGMLE.nloglikeobs "statsmodels.miscmodels.count.PoissonZiGMLE.nloglikeobs")(params) | Loglikelihood of Poisson model | | [`predict`](statsmodels.miscmodels.count.poissonzigmle.predict#statsmodels.miscmodels.count.PoissonZiGMLE.predict "statsmodels.miscmodels.count.PoissonZiGMLE.predict")(params[, exog]) | After a model has been fit predict returns the fitted values. | | [`reduceparams`](statsmodels.miscmodels.count.poissonzigmle.reduceparams#statsmodels.miscmodels.count.PoissonZiGMLE.reduceparams "statsmodels.miscmodels.count.PoissonZiGMLE.reduceparams")(params) | | | [`score`](statsmodels.miscmodels.count.poissonzigmle.score#statsmodels.miscmodels.count.PoissonZiGMLE.score "statsmodels.miscmodels.count.PoissonZiGMLE.score")(params) | Gradient of log-likelihood evaluated at params | | [`score_obs`](statsmodels.miscmodels.count.poissonzigmle.score_obs#statsmodels.miscmodels.count.PoissonZiGMLE.score_obs "statsmodels.miscmodels.count.PoissonZiGMLE.score_obs")(params, \*\*kwds) | Jacobian/Gradient of log-likelihood evaluated at params for each observation. | #### Attributes | | | | --- | --- | | `endog_names` | Names of endogenous variables | | `exog_names` | Names of exogenous variables | statsmodels statsmodels.sandbox.regression.gmm.IVGMM.score_cu statsmodels.sandbox.regression.gmm.IVGMM.score\_cu ================================================== `IVGMM.score_cu(params, epsilon=None, centered=True)` statsmodels statsmodels.sandbox.distributions.transformed.LogTransf_gen.mean statsmodels.sandbox.distributions.transformed.LogTransf\_gen.mean ================================================================= `LogTransf_gen.mean(*args, **kwds)` Mean of the distribution. | Parameters: | * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **mean** – the mean of the distribution | | Return type: | float | statsmodels statsmodels.stats.contingency_tables.StratifiedTable.summary statsmodels.stats.contingency\_tables.StratifiedTable.summary ============================================================= `StratifiedTable.summary(alpha=0.05, float_format='%.3f', method='normal')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#StratifiedTable.summary) A summary of all the main results. | Parameters: | * **alpha** (*float*) – `1 - alpha` is the nominal coverage probability of the confidence intervals. * **float\_format** (*string*) – Used for formatting numeric values in the summary. * **method** (*string*) – The method for producing the confidence interval. Currently must be ‘normal’ which uses the normal approximation. | statsmodels statsmodels.regression.linear_model.OLS.predict statsmodels.regression.linear\_model.OLS.predict ================================================ `OLS.predict(params, exog=None)` Return linear predicted values from a design matrix. | Parameters: | * **params** (*array-like*) – Parameters of a linear model * **exog** (*array-like**,* *optional.*) – Design / exogenous data. Model exog is used if None. | | Returns: | | | Return type: | An array of fitted values | #### Notes If the model has not yet been fit, params is not optional. statsmodels statsmodels.tsa.statespace.sarimax.SARIMAXResults.impulse_responses statsmodels.tsa.statespace.sarimax.SARIMAXResults.impulse\_responses ==================================================================== `SARIMAXResults.impulse_responses(steps=1, impulse=0, orthogonalized=False, cumulative=False, **kwargs)` Impulse response function | Parameters: | * **steps** (*int**,* *optional*) – The number of steps for which impulse responses are calculated. Default is 1. Note that the initial impulse is not counted as a step, so if `steps=1`, the output will have 2 entries. * **impulse** (*int* *or* *array\_like*) – If an integer, the state innovation to pulse; must be between 0 and `k_posdef-1`. Alternatively, a custom impulse vector may be provided; must be shaped `k_posdef x 1`. * **orthogonalized** (*boolean**,* *optional*) – Whether or not to perform impulse using orthogonalized innovations. Note that this will also affect custum `impulse` vectors. Default is False. * **cumulative** (*boolean**,* *optional*) – Whether or not to return cumulative impulse responses. Default is False. * **\*\*kwargs** – If the model is time-varying and `steps` is greater than the number of observations, any of the state space representation matrices that are time-varying must have updated values provided for the out-of-sample steps. For example, if `design` is a time-varying component, `nobs` is 10, and `steps` is 15, a (`k_endog` x `k_states` x 5) matrix must be provided with the new design matrix values. | | Returns: | **impulse\_responses** – Responses for each endogenous variable due to the impulse given by the `impulse` argument. A (steps + 1 x k\_endog) array. | | Return type: | array | #### Notes Intercepts in the measurement and state equation are ignored when calculating impulse responses. statsmodels statsmodels.graphics.gofplots.qqplot statsmodels.graphics.gofplots.qqplot ==================================== `statsmodels.graphics.gofplots.qqplot(data, dist=<scipy.stats._continuous_distns.norm_gen object>, distargs=(), a=0, loc=0, scale=1, fit=False, line=None, ax=None, **plotkwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/graphics/gofplots.html#qqplot) Q-Q plot of the quantiles of x versus the quantiles/ppf of a distribution. Can take arguments specifying the parameters for dist or fit them automatically. (See fit under Parameters.) | Parameters: | * **data** (*array-like*) – 1d data array * **dist** (*A scipy.stats* *or* *statsmodels distribution*) – Compare x against dist. The default is scipy.stats.distributions.norm (a standard normal). * **distargs** (*tuple*) – A tuple of arguments passed to dist to specify it fully so dist.ppf may be called. * **loc** (*float*) – Location parameter for dist * **a** (*float*) – Offset for the plotting position of an expected order statistic, for example. The plotting positions are given by (i - a)/(nobs - 2\*a + 1) for i in range(0,nobs+1) * **scale** (*float*) – Scale parameter for dist * **fit** (*boolean*) – If fit is false, loc, scale, and distargs are passed to the distribution. If fit is True then the parameters for dist are fit automatically using dist.fit. The quantiles are formed from the standardized data, after subtracting the fitted loc and dividing by the fitted scale. * **line** (*str {'45'**,* *'s'**,* *'r'**,* *q'}* *or* *None*) – Options for the reference line to which the data is compared: + ‘45’ - 45-degree line + ’s‘ - standardized line, the expected order statistics are scaled by the standard deviation of the given sample and have the mean added to them + ’r’ - A regression line is fit + ’q’ - A line is fit through the quartiles. + None - by default no reference line is added to the plot. * **ax** (*Matplotlib AxesSubplot instance**,* *optional*) – If given, this subplot is used to plot in instead of a new figure being created. * **\*\*plotkwargs** (*additional matplotlib arguments to be passed to the*) – `plot` command. | | Returns: | **fig** – If `ax` is None, the created figure. Otherwise the figure to which `ax` is connected. | | Return type: | Matplotlib figure instance | See also `scipy.stats.probplot` #### Examples ``` >>> import statsmodels.api as sm >>> from matplotlib import pyplot as plt >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> mod_fit = sm.OLS(data.endog, data.exog).fit() >>> res = mod_fit.resid # residuals >>> fig = sm.qqplot(res) >>> plt.show() ``` qqplot of the residuals against quantiles of t-distribution with 4 degrees of freedom: ``` >>> import scipy.stats as stats >>> fig = sm.qqplot(res, stats.t, distargs=(4,)) >>> plt.show() ``` qqplot against same as above, but with mean 3 and std 10: ``` >>> fig = sm.qqplot(res, stats.t, distargs=(4,), loc=3, scale=10) >>> plt.show() ``` Automatically determine parameters for t distribution including the loc and scale: ``` >>> fig = sm.qqplot(res, stats.t, fit=True, line='45') >>> plt.show() ``` The following plot displays some options, follow the link to see the code. ([Source code](../plots/graphics_gofplots_qqplot.py)) ([png](../plots/graphics_gofplots_qqplot_00.png), [hires.png](../plots/graphics_gofplots_qqplot_00.hires.png), [pdf](../plots/graphics_gofplots_qqplot_00.pdf)) ([png](../plots/graphics_gofplots_qqplot_01.png), [hires.png](../plots/graphics_gofplots_qqplot_01.hires.png), [pdf](../plots/graphics_gofplots_qqplot_01.pdf)) ([png](../plots/graphics_gofplots_qqplot_02.png), [hires.png](../plots/graphics_gofplots_qqplot_02.hires.png), [pdf](../plots/graphics_gofplots_qqplot_02.pdf)) ([png](../plots/graphics_gofplots_qqplot_03.png), [hires.png](../plots/graphics_gofplots_qqplot_03.hires.png), [pdf](../plots/graphics_gofplots_qqplot_03.pdf)) #### Notes Depends on matplotlib. If `fit` is True then the parameters are fit using the distribution’s fit() method. statsmodels statsmodels.duration.hazard_regression.PHRegResults.wald_test statsmodels.duration.hazard\_regression.PHRegResults.wald\_test =============================================================== `PHRegResults.wald_test(r_matrix, cov_p=None, scale=1.0, invcov=None, use_f=None)` Compute a Wald-test for a joint linear hypothesis. | Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) – + array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length p row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – Default is 1.0 for no scaling. * **invcov** (*array-like**,* *optional*) – A q x q array to specify an inverse covariance matrix based on a restrictions matrix. * **use\_f** (*bool*) – If True, then the F-distribution is used. If False, then the asymptotic distribution, chisquare is used. If use\_f is None, then the F distribution is used if the model specifies that use\_t is True. The test statistic is proportionally adjusted for the distribution by the number of constraints in the hypothesis. | | Returns: | **res** – The results for the test are attributes of this results instance. | | Return type: | ContrastResults instance | See also [`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`f_test`](statsmodels.duration.hazard_regression.phregresults.f_test#statsmodels.duration.hazard_regression.PHRegResults.f_test "statsmodels.duration.hazard_regression.PHRegResults.f_test"), [`t_test`](statsmodels.duration.hazard_regression.phregresults.t_test#statsmodels.duration.hazard_regression.PHRegResults.t_test "statsmodels.duration.hazard_regression.PHRegResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") #### Notes The matrix `r_matrix` is assumed to be non-singular. More precisely, r\_matrix (pX pX.T) r\_matrix.T is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full. statsmodels statsmodels.tsa.vector_ar.vecm.VECMResults.stderr_beta statsmodels.tsa.vector\_ar.vecm.VECMResults.stderr\_beta ======================================================== `VECMResults.stderr_beta()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/vecm.html#VECMResults.stderr_beta) statsmodels statsmodels.genmod.bayes_mixed_glm.BinomialBayesMixedGLM.logposterior statsmodels.genmod.bayes\_mixed\_glm.BinomialBayesMixedGLM.logposterior ======================================================================= `BinomialBayesMixedGLM.logposterior(params)` The overall log-density: log p(y, fe, vc, vcp). This differs by an additive constant from the log posterior log p(fe, vc, vcp | y). statsmodels statsmodels.tsa.statespace.structural.UnobservedComponentsResults.fittedvalues statsmodels.tsa.statespace.structural.UnobservedComponentsResults.fittedvalues ============================================================================== `UnobservedComponentsResults.fittedvalues()` (array) The predicted values of the model. An (nobs x k\_endog) array. statsmodels statsmodels.tsa.statespace.kalman_filter.KalmanFilter.filter statsmodels.tsa.statespace.kalman\_filter.KalmanFilter.filter ============================================================= `KalmanFilter.filter(filter_method=None, inversion_method=None, stability_method=None, conserve_memory=None, filter_timing=None, tolerance=None, loglikelihood_burn=None, complex_step=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/kalman_filter.html#KalmanFilter.filter) Apply the Kalman filter to the statespace model. | Parameters: | * **filter\_method** (*int**,* *optional*) – Determines which Kalman filter to use. Default is conventional. * **inversion\_method** (*int**,* *optional*) – Determines which inversion technique to use. Default is by Cholesky decomposition. * **stability\_method** (*int**,* *optional*) – Determines which numerical stability techniques to use. Default is to enforce symmetry of the predicted state covariance matrix. * **conserve\_memory** (*int**,* *optional*) – Determines what output from the filter to store. Default is to store everything. * **filter\_timing** (*int**,* *optional*) – Determines the timing convention of the filter. Default is that from Durbin and Koopman (2012), in which the filter is initialized with predicted values. * **tolerance** (*float**,* *optional*) – The tolerance at which the Kalman filter determines convergence to steady-state. Default is 1e-19. * **loglikelihood\_burn** (*int**,* *optional*) – The number of initial periods during which the loglikelihood is not recorded. Default is 0. | #### Notes This function by default does not compute variables required for smoothing. statsmodels statsmodels.tsa.arima_model.ARMAResults.summary2 statsmodels.tsa.arima\_model.ARMAResults.summary2 ================================================= `ARMAResults.summary2(title=None, alpha=0.05, float_format='%.4f')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_model.html#ARMAResults.summary2) Experimental summary function for ARIMA Results | Parameters: | * **title** (*string**,* *optional*) – Title for the top table. If not None, then this replaces the default title * **alpha** (*float*) – significance level for the confidence intervals * **float\_format** (*string*) – print format for floats in parameters summary | | Returns: | **smry** – This holds the summary table and text, which can be printed or converted to various output formats. | | Return type: | Summary instance | See also [`statsmodels.iolib.summary2.Summary`](statsmodels.iolib.summary2.summary#statsmodels.iolib.summary2.Summary "statsmodels.iolib.summary2.Summary") class to hold summary results statsmodels statsmodels.tsa.statespace.tools.companion_matrix statsmodels.tsa.statespace.tools.companion\_matrix ================================================== `statsmodels.tsa.statespace.tools.companion_matrix(polynomial)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/tools.html#companion_matrix) Create a companion matrix | Parameters: | **polynomial** (*array\_like* *or* *list*) – If an iterable, interpreted as the coefficients of the polynomial from which to form the companion matrix. Polynomial coefficients are in order of increasing degree, and may be either scalars (as in an AR(p) model) or coefficient matrices (as in a VAR(p) model). If an integer, it is interpereted as the size of a companion matrix of a scalar polynomial, where the polynomial coefficients are initialized to zeros. If a matrix polynomial is passed, \(C\_0\) may be set to the scalar value 1 to indicate an identity matrix (doing so will improve the speed of the companion matrix creation). | | Returns: | **companion\_matrix** | | Return type: | array | #### Notes Given coefficients of a lag polynomial of the form: \[c(L) = c\_0 + c\_1 L + \dots + c\_p L^p\] returns a matrix of the form \[\begin{split}\begin{bmatrix} \phi\_1 & 1 & 0 & \cdots & 0 \\ \phi\_2 & 0 & 1 & & 0 \\ \vdots & & & \ddots & 0 \\ & & & & 1 \\ \phi\_n & 0 & 0 & \cdots & 0 \\ \end{bmatrix}\end{split}\] where some or all of the \(\phi\_i\) may be non-zero (if `polynomial` is None, then all are equal to zero). If the coefficients provided are scalars \((c\_0, c\_1, \dots, c\_p)\), then the companion matrix is an \(n \times n\) matrix formed with the elements in the first column defined as \(\phi\_i = -\frac{c\_i}{c\_0}, i \in 1, \dots, p\). If the coefficients provided are matrices \((C\_0, C\_1, \dots, C\_p)\), each of shape \((m, m)\), then the companion matrix is an \(nm \times nm\) matrix formed with the elements in the first column defined as \(\phi\_i = -C\_0^{-1} C\_i', i \in 1, \dots, p\). It is important to understand the expected signs of the coefficients. A typical AR(p) model is written as: \[y\_t = a\_1 y\_{t-1} + \dots + a\_p y\_{t-p} + \varepsilon\_t\] This can be rewritten as: \[\begin{split}(1 - a\_1 L - \dots - a\_p L^p )y\_t = \varepsilon\_t \\ (1 + c\_1 L + \dots + c\_p L^p )y\_t = \varepsilon\_t \\ c(L) y\_t = \varepsilon\_t\end{split}\] The coefficients from this form are defined to be \(c\_i = - a\_i\), and it is the \(c\_i\) coefficients that this function expects to be provided.
programming_docs
statsmodels statsmodels.discrete.discrete_model.CountModel.from_formula statsmodels.discrete.discrete\_model.CountModel.from\_formula ============================================================= `classmethod CountModel.from_formula(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** (*extra arguments*) – These are passed to the model * **kwargs** (*extra keyword arguments*) – These are passed to the model with one exception. The `eval_env` keyword is passed to patsy. It can be either a [`patsy.EvalEnvironment`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.EvalEnvironment "(in patsy v0.5.0+dev)") 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** | | Return type: | 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 statsmodels.regression.quantile_regression.QuantRegResults.wald_test_terms statsmodels.regression.quantile\_regression.QuantRegResults.wald\_test\_terms ============================================================================= `QuantRegResults.wald_test_terms(skip_single=False, extra_constraints=None, combine_terms=None)` Compute a sequence of Wald tests for terms over multiple columns This computes joined Wald tests for the hypothesis that all coefficients corresponding to a `term` are zero. `Terms` are defined by the underlying formula or by string matching. | Parameters: | * **skip\_single** (*boolean*) – If true, then terms that consist only of a single column and, therefore, refers only to a single parameter is skipped. If false, then all terms are included. * **extra\_constraints** (*ndarray*) – not tested yet * **combine\_terms** (*None* *or* *list of strings*) – Each string in this list is matched to the name of the terms or the name of the exogenous variables. All columns whose name includes that string are combined in one joint test. | | Returns: | **test\_result** – The result instance contains `table` which is a pandas DataFrame with the test results: test statistic, degrees of freedom and pvalues. | | Return type: | result instance | #### Examples ``` >>> res_ols = ols("np.log(Days+1) ~ C(Duration, Sum)*C(Weight, Sum)", data).fit() >>> res_ols.wald_test_terms() <class 'statsmodels.stats.contrast.WaldTestResults'> F P>F df constraint df denom Intercept 279.754525 2.37985521351e-22 1 51 C(Duration, Sum) 5.367071 0.0245738436636 1 51 C(Weight, Sum) 12.432445 3.99943118767e-05 2 51 C(Duration, Sum):C(Weight, Sum) 0.176002 0.83912310946 2 51 ``` ``` >>> res_poi = Poisson.from_formula("Days ~ C(Weight) * C(Duration)", data).fit(cov_type='HC0') >>> wt = res_poi.wald_test_terms(skip_single=False, combine_terms=['Duration', 'Weight']) >>> print(wt) chi2 P>chi2 df constraint Intercept 15.695625 7.43960374424e-05 1 C(Weight) 16.132616 0.000313940174705 2 C(Duration) 1.009147 0.315107378931 1 C(Weight):C(Duration) 0.216694 0.897315972824 2 Duration 11.187849 0.010752286833 3 Weight 30.263368 4.32586407145e-06 4 ``` statsmodels statsmodels.discrete.discrete_model.MultinomialResults.save statsmodels.discrete.discrete\_model.MultinomialResults.save ============================================================ `MultinomialResults.save(fname, remove_data=False)` save a pickle of this instance | Parameters: | * **fname** (*string* *or* *filehandle*) – fname can be a string to a file path or filename, or a filehandle. * **remove\_data** (*bool*) – If False (default), then the instance is pickled without changes. If True, then all arrays with length nobs are set to None before pickling. See the remove\_data method. In some cases not all arrays will be set to None. | #### Notes If remove\_data is true and the model result does not implement a remove\_data method then this will raise an exception. statsmodels statsmodels.regression.linear_model.OLSResults.HC0_se statsmodels.regression.linear\_model.OLSResults.HC0\_se ======================================================= `OLSResults.HC0_se()` See statsmodels.RegressionResults statsmodels statsmodels.sandbox.regression.gmm.GMM.from_formula statsmodels.sandbox.regression.gmm.GMM.from\_formula ==================================================== `classmethod GMM.from_formula(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** (*extra arguments*) – These are passed to the model * **kwargs** (*extra keyword arguments*) – These are passed to the model with one exception. The `eval_env` keyword is passed to patsy. It can be either a [`patsy.EvalEnvironment`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.EvalEnvironment "(in patsy v0.5.0+dev)") 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** | | Return type: | 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 statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.load statsmodels.tsa.statespace.dynamic\_factor.DynamicFactorResults.load ==================================================================== `classmethod DynamicFactorResults.load(fname)` load a pickle, (class method) | Parameters: | **fname** (*string* *or* *filehandle*) – fname can be a string to a file path or filename, or a filehandle. | | Returns: | | | Return type: | unpickled instance | statsmodels statsmodels.sandbox.distributions.transformed.LogTransf_gen.fit statsmodels.sandbox.distributions.transformed.LogTransf\_gen.fit ================================================================ `LogTransf_gen.fit(data, *args, **kwds)` Return MLEs for shape (if applicable), location, and scale parameters from data. MLE stands for Maximum Likelihood Estimate. Starting estimates for the fit are given by input arguments; for any arguments not provided with starting estimates, `self._fitstart(data)` is called to generate such. One can hold some parameters fixed to specific values by passing in keyword arguments `f0`, `f1`, …, `fn` (for shape parameters) and `floc` and `fscale` (for location and scale parameters, respectively). | Parameters: | * **data** (*array\_like*) – Data to use in calculating the MLEs. * **args** (*floats**,* *optional*) – Starting value(s) for any shape-characterizing arguments (those not provided will be determined by a call to `_fitstart(data)`). No default value. * **kwds** (*floats**,* *optional*) – Starting values for the location and scale parameters; no default. Special keyword arguments are recognized as holding certain parameters fixed: + f0…fn : hold respective shape parameters fixed. Alternatively, shape parameters to fix can be specified by name. For example, if `self.shapes == "a, b"`, `fa``and ``fix_a` are equivalent to `f0`, and `fb` and `fix_b` are equivalent to `f1`. + floc : hold location parameter fixed to specified value. + fscale : hold scale parameter fixed to specified value. + optimizer : The optimizer to use. The optimizer must take `func`, and starting position as the first two arguments, plus `args` (for extra arguments to pass to the function to be optimized) and `disp=0` to suppress output as keyword arguments. | | Returns: | **mle\_tuple** – MLEs for any shape parameters (if applicable), followed by those for location and scale. For most random variables, shape statistics will be returned, but there are exceptions (e.g. `norm`). | | Return type: | tuple of floats | #### Notes This fit is computed by maximizing a log-likelihood function, with penalty applied for samples outside of range of the distribution. The returned answer is not guaranteed to be the globally optimal MLE, it may only be locally optimal, or the optimization may fail altogether. #### Examples Generate some data to fit: draw random variates from the `beta` distribution ``` >>> from scipy.stats import beta >>> a, b = 1., 2. >>> x = beta.rvs(a, b, size=1000) ``` Now we can fit all four parameters (`a`, `b`, `loc` and `scale`): ``` >>> a1, b1, loc1, scale1 = beta.fit(x) ``` We can also use some prior knowledge about the dataset: let’s keep `loc` and `scale` fixed: ``` >>> a1, b1, loc1, scale1 = beta.fit(x, floc=0, fscale=1) >>> loc1, scale1 (0, 1) ``` We can also keep shape parameters fixed by using `f`-keywords. To keep the zero-th shape parameter `a` equal 1, use `f0=1` or, equivalently, `fa=1`: ``` >>> a1, b1, loc1, scale1 = beta.fit(x, fa=1, floc=0, fscale=1) >>> a1 1 ``` Not all distributions return estimates for the shape parameters. `norm` for example just returns estimates for location and scale: ``` >>> from scipy.stats import norm >>> x = norm.rvs(a, b, size=1000, random_state=123) >>> loc1, scale1 = norm.fit(x) >>> loc1, scale1 (0.92087172783841631, 2.0015750750324668) ``` statsmodels statsmodels.graphics.tsaplots.month_plot statsmodels.graphics.tsaplots.month\_plot ========================================= `statsmodels.graphics.tsaplots.month_plot(x, dates=None, ylabel=None, ax=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/graphics/tsaplots.html#month_plot) Seasonal plot of monthly data | Parameters: | * **x** (*array-like*) – Seasonal data to plot. If dates is None, x must be a pandas object with a PeriodIndex or DatetimeIndex with a monthly frequency. * **dates** (*array-like**,* *optional*) – If `x` is not a pandas object, then dates must be supplied. * **ylabel** (*str**,* *optional*) – The label for the y-axis. Will attempt to use the `name` attribute of the Series. * **ax** (*matplotlib.axes**,* *optional*) – Existing axes instance. | | Returns: | | | Return type: | matplotlib.Figure | #### Examples ``` >>> import statsmodels.api as sm >>> import pandas as pd ``` ``` >>> dta = sm.datasets.elnino.load_pandas().data >>> dta['YEAR'] = dta.YEAR.astype(int).astype(str) >>> dta = dta.set_index('YEAR').T.unstack() >>> dates = pd.to_datetime(list(map(lambda x : '-'.join(x) + '-1', ... dta.index.values))) ``` ``` >>> dta.index = pd.DatetimeIndex(dates, freq='MS') >>> fig = sm.graphics.tsa.month_plot(dta) ``` ([Source code](../plots/graphics_month_plot.py), [png](../plots/graphics_month_plot.png), [hires.png](../plots/graphics_month_plot.hires.png), [pdf](../plots/graphics_month_plot.pdf)) statsmodels statsmodels.stats.diagnostic.CompareCox.run statsmodels.stats.diagnostic.CompareCox.run =========================================== `CompareCox.run(results_x, results_z, attach=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/diagnostic.html#CompareCox.run) run Cox test for non-nested models | Parameters: | * **results\_x** (*Result instance*) – result instance of first model * **results\_z** (*Result instance*) – result instance of second model * **attach** (*bool*) – If true, then the intermediate results are attached to the instance. | | Returns: | * **tstat** (*float*) – t statistic for the test that including the fitted values of the first model in the second model has no effect. * **pvalue** (*float*) – two-sided pvalue for the t statistic | #### Notes Tests of non-nested hypothesis might not provide unambiguous answers. The test should be performed in both directions and it is possible that both or neither test rejects. see ??? for more information. #### References ??? statsmodels statsmodels.stats.weightstats.CompareMeans.ttost_ind statsmodels.stats.weightstats.CompareMeans.ttost\_ind ===================================================== `CompareMeans.ttost_ind(low, upp, usevar='pooled')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/weightstats.html#CompareMeans.ttost_ind) test of equivalence for two independent samples, base on t-test | Parameters: | * **upp** (*low**,*) – equivalence interval low < m1 - m2 < upp * **usevar** (*string**,* *'pooled'* *or* *'unequal'*) – If `pooled`, then the standard deviation of the samples is assumed to be the same. If `unequal`, then Welsh ttest with Satterthwait degrees of freedom is used | | Returns: | * **pvalue** (*float*) – pvalue of the non-equivalence test * **t1, pv1** (*tuple of floats*) – test statistic and pvalue for lower threshold test * **t2, pv2** (*tuple of floats*) – test statistic and pvalue for upper threshold test | statsmodels statsmodels.regression.recursive_ls.RecursiveLS.initialize_stationary statsmodels.regression.recursive\_ls.RecursiveLS.initialize\_stationary ======================================================================= `RecursiveLS.initialize_stationary()` statsmodels statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialResults.t_test statsmodels.discrete.count\_model.ZeroInflatedNegativeBinomialResults.t\_test ============================================================================= `ZeroInflatedNegativeBinomialResults.t_test(r_matrix, cov_p=None, scale=None, use_t=None)` Compute a t-test for a each linear hypothesis of the form Rb = q | Parameters: | * **r\_matrix** (*array-like**,* *str**,* *tuple*) – + array : If an array is given, a p x k 2d array or length k 1d array specifying the linear restrictions. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q). If q is given, can be either a scalar or a length p row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – An optional `scale` to use. Default is the scale specified by the model fit. * **use\_t** (*bool**,* *optional*) – If use\_t is None, then the default of the model is used. If use\_t is True, then the p-values are based on the t distribution. If use\_t is False, then the p-values are based on the normal distribution. | | Returns: | **res** – The results for the test are attributes of this results instance. The available results have the same elements as the parameter table in `summary()`. | | Return type: | ContrastResults instance | #### Examples ``` >>> import numpy as np >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> r = np.zeros_like(results.params) >>> r[5:] = [1,-1] >>> print(r) [ 0. 0. 0. 0. 0. 1. -1.] ``` r tests that the coefficients on the 5th and 6th independent variable are the same. ``` >>> T_test = results.t_test(r) >>> print(T_test) Test for Constraints ============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------ c0 -1829.2026 455.391 -4.017 0.003 -2859.368 -799.037 ============================================================================== >>> T_test.effect -1829.2025687192481 >>> T_test.sd 455.39079425193762 >>> T_test.tvalue -4.0167754636411717 >>> T_test.pvalue 0.0015163772380899498 ``` Alternatively, you can specify the hypothesis tests using a string ``` >>> from statsmodels.formula.api import ols >>> dta = sm.datasets.longley.load_pandas().data >>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' >>> results = ols(formula, dta).fit() >>> hypotheses = 'GNPDEFL = GNP, UNEMP = 2, YEAR/1829 = 1' >>> t_test = results.t_test(hypotheses) >>> print(t_test) Test for Constraints ============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------ c0 15.0977 84.937 0.178 0.863 -177.042 207.238 c1 -2.0202 0.488 -8.231 0.000 -3.125 -0.915 c2 1.0001 0.249 0.000 1.000 0.437 1.563 ============================================================================== ``` See also [`tvalues`](statsmodels.discrete.count_model.zeroinflatednegativebinomialresults.tvalues#statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialResults.tvalues "statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialResults.tvalues") individual t statistics [`f_test`](statsmodels.discrete.count_model.zeroinflatednegativebinomialresults.f_test#statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialResults.f_test "statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialResults.f_test") for F tests [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") statsmodels statsmodels.tsa.vector_ar.vecm.VECMResults.cov_var_repr statsmodels.tsa.vector\_ar.vecm.VECMResults.cov\_var\_repr ========================================================== `VECMResults.cov_var_repr()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/vecm.html#VECMResults.cov_var_repr) Gives the covariance matrix of the corresponding VAR-representation. More precisely, the covariance matrix of the vector consisting of the columns of the corresponding VAR coefficient matrices (i.e. vec(self.var\_rep)). | Returns: | **cov** | | Return type: | array (neqs\*\*2 \* k\_ar x neqs\*\*2 \* k\_ar) | statsmodels statsmodels.tsa.vector_ar.hypothesis_test_results.HypothesisTestResults.summary statsmodels.tsa.vector\_ar.hypothesis\_test\_results.HypothesisTestResults.summary ================================================================================== `HypothesisTestResults.summary()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/hypothesis_test_results.html#HypothesisTestResults.summary)
programming_docs
statsmodels statsmodels.robust.robust_linear_model.RLMResults statsmodels.robust.robust\_linear\_model.RLMResults =================================================== `class statsmodels.robust.robust_linear_model.RLMResults(model, params, normalized_cov_params, scale)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/robust_linear_model.html#RLMResults) Class to contain RLM results | Returns: | * *\*\*Attributes\*\** * **bcov\_scaled** (*array*) – p x p scaled covariance matrix specified in the model fit method. The default is H1. H1 is defined as `k**2 * (1/df_resid*sum(M.psi(sresid)**2)*scale**2)/ ((1/nobs*sum(M.psi_deriv(sresid)))**2) * (X.T X)^(-1)`where `k = 1 + (df_model +1)/nobs * var_psiprime/m**2` where `m = mean(M.psi_deriv(sresid))` and `var_psiprime = var(M.psi_deriv(sresid))` H2 is defined as `k * (1/df_resid) * sum(M.psi(sresid)**2) *scale**2/ ((1/nobs)*sum(M.psi_deriv(sresid)))*W_inv` H3 is defined as `1/k * (1/df_resid * sum(M.psi(sresid)**2)*scale**2 * (W_inv X.T X W_inv))` where `k` is defined as above and `W_inv = (M.psi_deriv(sresid) exog.T exog)^(-1)` See the technical documentation for cleaner formulae. * **bcov\_unscaled** (*array*) – The usual p x p covariance matrix with scale set equal to 1. It is then just equivalent to normalized\_cov\_params. * **bse** (*array*) – An array of the standard errors of the parameters. The standard errors are taken from the robust covariance matrix specified in the argument to fit. * **chisq** (*array*) – An array of the chi-squared values of the paramter estimates. * *df\_model* – See RLM.df\_model * *df\_resid* – See RLM.df\_resid * **fit\_history** (*dict*) – Contains information about the iterations. Its keys are `deviance`, `params`, `iteration` and the convergence criteria specified in `RLM.fit`, if different from `deviance` or `params`. * **fit\_options** (*dict*) – Contains the options given to fit. * **fittedvalues** (*array*) – The linear predicted values. dot(exog, params) * **model** (*statsmodels.rlm.RLM*) – A reference to the model instance * **nobs** (*float*) – The number of observations n * **normalized\_cov\_params** (*array*) – See RLM.normalized\_cov\_params * **params** (*array*) – The coefficients of the fitted model * **pinv\_wexog** (*array*) – See RLM.pinv\_wexog * **pvalues** (*array*) – The p values associated with `tvalues`. Note that `tvalues` are assumed to be distributed standard normal rather than Student’s t. * **resid** (*array*) – The residuals of the fitted model. endog - fittedvalues * **scale** (*float*) – The type of scale is determined in the arguments to the fit method in RLM. The reported scale is taken from the residuals of the weighted least squares in the last IRLS iteration if update\_scale is True. If update\_scale is False, then it is the scale given by the first OLS fit before the IRLS iterations. * **sresid** (*array*) – The scaled residuals. * **tvalues** (*array*) – The “t-statistics” of params. These are defined as params/bse where bse are taken from the robust covariance matrix specified in the argument to fit. * **weights** (*array*) – The reported weights are determined by passing the scaled residuals from the last weighted least squares fit in the IRLS algortihm. | See also [`statsmodels.base.model.LikelihoodModelResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.base.model.LikelihoodModelResults.html#statsmodels.base.model.LikelihoodModelResults "statsmodels.base.model.LikelihoodModelResults") #### Methods | | | | --- | --- | | [`bcov_scaled`](statsmodels.robust.robust_linear_model.rlmresults.bcov_scaled#statsmodels.robust.robust_linear_model.RLMResults.bcov_scaled "statsmodels.robust.robust_linear_model.RLMResults.bcov_scaled")() | | | [`bcov_unscaled`](statsmodels.robust.robust_linear_model.rlmresults.bcov_unscaled#statsmodels.robust.robust_linear_model.RLMResults.bcov_unscaled "statsmodels.robust.robust_linear_model.RLMResults.bcov_unscaled")() | | | [`bse`](statsmodels.robust.robust_linear_model.rlmresults.bse#statsmodels.robust.robust_linear_model.RLMResults.bse "statsmodels.robust.robust_linear_model.RLMResults.bse")() | | | [`chisq`](statsmodels.robust.robust_linear_model.rlmresults.chisq#statsmodels.robust.robust_linear_model.RLMResults.chisq "statsmodels.robust.robust_linear_model.RLMResults.chisq")() | | | [`conf_int`](statsmodels.robust.robust_linear_model.rlmresults.conf_int#statsmodels.robust.robust_linear_model.RLMResults.conf_int "statsmodels.robust.robust_linear_model.RLMResults.conf_int")([alpha, cols, method]) | Returns the confidence interval of the fitted parameters. | | [`cov_params`](statsmodels.robust.robust_linear_model.rlmresults.cov_params#statsmodels.robust.robust_linear_model.RLMResults.cov_params "statsmodels.robust.robust_linear_model.RLMResults.cov_params")([r\_matrix, column, scale, cov\_p, …]) | Returns the variance/covariance matrix. | | [`f_test`](statsmodels.robust.robust_linear_model.rlmresults.f_test#statsmodels.robust.robust_linear_model.RLMResults.f_test "statsmodels.robust.robust_linear_model.RLMResults.f_test")(r\_matrix[, cov\_p, scale, invcov]) | Compute the F-test for a joint linear hypothesis. | | [`fittedvalues`](statsmodels.robust.robust_linear_model.rlmresults.fittedvalues#statsmodels.robust.robust_linear_model.RLMResults.fittedvalues "statsmodels.robust.robust_linear_model.RLMResults.fittedvalues")() | | | [`initialize`](statsmodels.robust.robust_linear_model.rlmresults.initialize#statsmodels.robust.robust_linear_model.RLMResults.initialize "statsmodels.robust.robust_linear_model.RLMResults.initialize")(model, params, \*\*kwd) | | | [`llf`](statsmodels.robust.robust_linear_model.rlmresults.llf#statsmodels.robust.robust_linear_model.RLMResults.llf "statsmodels.robust.robust_linear_model.RLMResults.llf")() | | | [`load`](statsmodels.robust.robust_linear_model.rlmresults.load#statsmodels.robust.robust_linear_model.RLMResults.load "statsmodels.robust.robust_linear_model.RLMResults.load")(fname) | load a pickle, (class method) | | [`normalized_cov_params`](statsmodels.robust.robust_linear_model.rlmresults.normalized_cov_params#statsmodels.robust.robust_linear_model.RLMResults.normalized_cov_params "statsmodels.robust.robust_linear_model.RLMResults.normalized_cov_params")() | | | [`predict`](statsmodels.robust.robust_linear_model.rlmresults.predict#statsmodels.robust.robust_linear_model.RLMResults.predict "statsmodels.robust.robust_linear_model.RLMResults.predict")([exog, transform]) | Call self.model.predict with self.params as the first argument. | | [`pvalues`](statsmodels.robust.robust_linear_model.rlmresults.pvalues#statsmodels.robust.robust_linear_model.RLMResults.pvalues "statsmodels.robust.robust_linear_model.RLMResults.pvalues")() | | | [`remove_data`](statsmodels.robust.robust_linear_model.rlmresults.remove_data#statsmodels.robust.robust_linear_model.RLMResults.remove_data "statsmodels.robust.robust_linear_model.RLMResults.remove_data")() | remove data arrays, all nobs arrays from result and model | | [`resid`](statsmodels.robust.robust_linear_model.rlmresults.resid#statsmodels.robust.robust_linear_model.RLMResults.resid "statsmodels.robust.robust_linear_model.RLMResults.resid")() | | | [`save`](statsmodels.robust.robust_linear_model.rlmresults.save#statsmodels.robust.robust_linear_model.RLMResults.save "statsmodels.robust.robust_linear_model.RLMResults.save")(fname[, remove\_data]) | save a pickle of this instance | | [`sresid`](statsmodels.robust.robust_linear_model.rlmresults.sresid#statsmodels.robust.robust_linear_model.RLMResults.sresid "statsmodels.robust.robust_linear_model.RLMResults.sresid")() | | | [`summary`](statsmodels.robust.robust_linear_model.rlmresults.summary#statsmodels.robust.robust_linear_model.RLMResults.summary "statsmodels.robust.robust_linear_model.RLMResults.summary")([yname, xname, title, alpha, return\_fmt]) | This is for testing the new summary setup | | [`summary2`](statsmodels.robust.robust_linear_model.rlmresults.summary2#statsmodels.robust.robust_linear_model.RLMResults.summary2 "statsmodels.robust.robust_linear_model.RLMResults.summary2")([xname, yname, title, alpha, …]) | Experimental summary function for regression results | | [`t_test`](statsmodels.robust.robust_linear_model.rlmresults.t_test#statsmodels.robust.robust_linear_model.RLMResults.t_test "statsmodels.robust.robust_linear_model.RLMResults.t_test")(r\_matrix[, cov\_p, scale, use\_t]) | Compute a t-test for a each linear hypothesis of the form Rb = q | | [`t_test_pairwise`](statsmodels.robust.robust_linear_model.rlmresults.t_test_pairwise#statsmodels.robust.robust_linear_model.RLMResults.t_test_pairwise "statsmodels.robust.robust_linear_model.RLMResults.t_test_pairwise")(term\_name[, method, alpha, …]) | perform pairwise t\_test with multiple testing corrected p-values | | [`tvalues`](statsmodels.robust.robust_linear_model.rlmresults.tvalues#statsmodels.robust.robust_linear_model.RLMResults.tvalues "statsmodels.robust.robust_linear_model.RLMResults.tvalues")() | Return the t-statistic for a given parameter estimate. | | [`wald_test`](statsmodels.robust.robust_linear_model.rlmresults.wald_test#statsmodels.robust.robust_linear_model.RLMResults.wald_test "statsmodels.robust.robust_linear_model.RLMResults.wald_test")(r\_matrix[, cov\_p, scale, invcov, …]) | Compute a Wald-test for a joint linear hypothesis. | | [`wald_test_terms`](statsmodels.robust.robust_linear_model.rlmresults.wald_test_terms#statsmodels.robust.robust_linear_model.RLMResults.wald_test_terms "statsmodels.robust.robust_linear_model.RLMResults.wald_test_terms")([skip\_single, …]) | Compute a sequence of Wald tests for terms over multiple columns | | [`weights`](statsmodels.robust.robust_linear_model.rlmresults.weights#statsmodels.robust.robust_linear_model.RLMResults.weights "statsmodels.robust.robust_linear_model.RLMResults.weights")() | | #### Attributes | | | | --- | --- | | `use_t` | | statsmodels statsmodels.discrete.count_model.ZeroInflatedPoissonResults.fittedvalues statsmodels.discrete.count\_model.ZeroInflatedPoissonResults.fittedvalues ========================================================================= `ZeroInflatedPoissonResults.fittedvalues()` statsmodels statsmodels.genmod.families.links.nbinom.deriv2 statsmodels.genmod.families.links.nbinom.deriv2 =============================================== `nbinom.deriv2(p)` Second derivative of the negative binomial link function. | Parameters: | **p** (*array-like*) – Mean parameters | | Returns: | **g’‘(p)** – The second derivative of the negative binomial transform link function | | Return type: | array | #### Notes g’‘(x) = -(1+2\*alpha\*x)/(x+alpha\*x^2)^2 statsmodels statsmodels.duration.hazard_regression.PHRegResults.summary statsmodels.duration.hazard\_regression.PHRegResults.summary ============================================================ `PHRegResults.summary(yname=None, xname=None, title=None, alpha=0.05)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/duration/hazard_regression.html#PHRegResults.summary) Summarize the proportional hazards regression results. | Parameters: | * **yname** (*string**,* *optional*) – Default is `y` * **xname** (*list of strings**,* *optional*) – Default is `x#` for ## in p the number of regressors * **title** (*string**,* *optional*) – Title for the top table. If not None, then this replaces the default title * **alpha** (*float*) – significance level for the confidence intervals | | Returns: | **smry** – this holds the summary tables and text, which can be printed or converted to various output formats. | | Return type: | Summary instance | See also [`statsmodels.iolib.summary.Summary`](statsmodels.iolib.summary.summary#statsmodels.iolib.summary.Summary "statsmodels.iolib.summary.Summary") class to hold summary results statsmodels statsmodels.discrete.discrete_model.BinaryResults.pvalues statsmodels.discrete.discrete\_model.BinaryResults.pvalues ========================================================== `BinaryResults.pvalues()` statsmodels statsmodels.regression.linear_model.OLSResults.el_test statsmodels.regression.linear\_model.OLSResults.el\_test ======================================================== `OLSResults.el_test(b0_vals, param_nums, return_weights=0, ret_params=0, method='nm', stochastic_exog=1, return_params=0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#OLSResults.el_test) Tests single or joint hypotheses of the regression parameters using Empirical Likelihood. | Parameters: | * **b0\_vals** (*1darray*) – The hypothesized value of the parameter to be tested * **param\_nums** (*1darray*) – The parameter number to be tested * **print\_weights** (*bool*) – If true, returns the weights that optimize the likelihood ratio at b0\_vals. Default is False * **ret\_params** (*bool*) – If true, returns the parameter vector that maximizes the likelihood ratio at b0\_vals. Also returns the weights. Default is False * **method** (*string*) – Can either be ‘nm’ for Nelder-Mead or ‘powell’ for Powell. The optimization method that optimizes over nuisance parameters. Default is ‘nm’ * **stochastic\_exog** (*bool*) – When TRUE, the exogenous variables are assumed to be stochastic. When the regressors are nonstochastic, moment conditions are placed on the exogenous variables. Confidence intervals for stochastic regressors are at least as large as non-stochastic regressors. Default = TRUE | | Returns: | **res** – The p-value and -2 times the log-likelihood ratio for the hypothesized values. | | Return type: | tuple | #### Examples ``` >>> import statsmodels.api as sm >>> data = sm.datasets.stackloss.load() >>> endog = data.endog >>> exog = sm.add_constant(data.exog) >>> model = sm.OLS(endog, exog) >>> fitted = model.fit() >>> fitted.params >>> array([-39.91967442, 0.7156402 , 1.29528612, -0.15212252]) >>> fitted.rsquared >>> 0.91357690446068196 >>> # Test that the slope on the first variable is 0 >>> fitted.el_test([0], [1]) >>> (27.248146353888796, 1.7894660442330235e-07) ``` statsmodels statsmodels.tsa.statespace.mlemodel.MLEResults.cov_params_robust_approx statsmodels.tsa.statespace.mlemodel.MLEResults.cov\_params\_robust\_approx ========================================================================== `MLEResults.cov_params_robust_approx()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEResults.cov_params_robust_approx) (array) The QMLE variance / covariance matrix. Computed using the numerical Hessian as the evaluated hessian. statsmodels statsmodels.sandbox.distributions.extras.ACSkewT_gen.freeze statsmodels.sandbox.distributions.extras.ACSkewT\_gen.freeze ============================================================ `ACSkewT_gen.freeze(*args, **kwds)` Freeze the distribution for the given arguments. | Parameters: | **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution. Should include all the non-optional arguments, may include `loc` and `scale`. | | Returns: | **rv\_frozen** – The frozen distribution. | | Return type: | rv\_frozen instance | statsmodels statsmodels.genmod.cov_struct.Nested.summary statsmodels.genmod.cov\_struct.Nested.summary ============================================= `Nested.summary()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/cov_struct.html#Nested.summary) Returns a summary string describing the state of the dependence structure. statsmodels statsmodels.tsa.vector_ar.vecm.VECMResults.stderr_det_coef statsmodels.tsa.vector\_ar.vecm.VECMResults.stderr\_det\_coef ============================================================= `VECMResults.stderr_det_coef()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/vecm.html#VECMResults.stderr_det_coef) statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactor.set_inversion_method statsmodels.tsa.statespace.dynamic\_factor.DynamicFactor.set\_inversion\_method =============================================================================== `DynamicFactor.set_inversion_method(inversion_method=None, **kwargs)` Set the inversion method The Kalman filter may contain one matrix inversion: that of the forecast error covariance matrix. The inversion method controls how and if that inverse is performed. | Parameters: | * **inversion\_method** (*integer**,* *optional*) – Bitmask value to set the inversion method to. See notes for details. * **\*\*kwargs** – Keyword arguments may be used to influence the inversion method by setting individual boolean flags. See notes for details. | #### Notes This method is rarely used. See the corresponding function in the `KalmanFilter` class for details. statsmodels statsmodels.stats.contingency_tables.Table.standardized_resids statsmodels.stats.contingency\_tables.Table.standardized\_resids ================================================================ `Table.standardized_resids()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table.standardized_resids) statsmodels statsmodels.genmod.families.family.Tweedie.predict statsmodels.genmod.families.family.Tweedie.predict ================================================== `Tweedie.predict(mu)` Linear predictors based on given mu values. | Parameters: | **mu** (*array*) – The mean response variables | | Returns: | **lin\_pred** – Linear predictors based on the mean response variables. The value of the link function at the given mu. | | Return type: | array | statsmodels statsmodels.tsa.statespace.sarimax.SARIMAX.set_filter_method statsmodels.tsa.statespace.sarimax.SARIMAX.set\_filter\_method ============================================================== `SARIMAX.set_filter_method(filter_method=None, **kwargs)` Set the filtering method The filtering method controls aspects of which Kalman filtering approach will be used. | Parameters: | * **filter\_method** (*integer**,* *optional*) – Bitmask value to set the filter method to. See notes for details. * **\*\*kwargs** – Keyword arguments may be used to influence the filter method by setting individual boolean flags. See notes for details. | #### Notes This method is rarely used. See the corresponding function in the `KalmanFilter` class for details. statsmodels statsmodels.tsa.statespace.sarimax.SARIMAXResults.t_test statsmodels.tsa.statespace.sarimax.SARIMAXResults.t\_test ========================================================= `SARIMAXResults.t_test(r_matrix, cov_p=None, scale=None, use_t=None)` Compute a t-test for a each linear hypothesis of the form Rb = q | Parameters: | * **r\_matrix** (*array-like**,* *str**,* *tuple*) – + array : If an array is given, a p x k 2d array or length k 1d array specifying the linear restrictions. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q). If q is given, can be either a scalar or a length p row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – An optional `scale` to use. Default is the scale specified by the model fit. * **use\_t** (*bool**,* *optional*) – If use\_t is None, then the default of the model is used. If use\_t is True, then the p-values are based on the t distribution. If use\_t is False, then the p-values are based on the normal distribution. | | Returns: | **res** – The results for the test are attributes of this results instance. The available results have the same elements as the parameter table in `summary()`. | | Return type: | ContrastResults instance | #### Examples ``` >>> import numpy as np >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> r = np.zeros_like(results.params) >>> r[5:] = [1,-1] >>> print(r) [ 0. 0. 0. 0. 0. 1. -1.] ``` r tests that the coefficients on the 5th and 6th independent variable are the same. ``` >>> T_test = results.t_test(r) >>> print(T_test) Test for Constraints ============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------ c0 -1829.2026 455.391 -4.017 0.003 -2859.368 -799.037 ============================================================================== >>> T_test.effect -1829.2025687192481 >>> T_test.sd 455.39079425193762 >>> T_test.tvalue -4.0167754636411717 >>> T_test.pvalue 0.0015163772380899498 ``` Alternatively, you can specify the hypothesis tests using a string ``` >>> from statsmodels.formula.api import ols >>> dta = sm.datasets.longley.load_pandas().data >>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' >>> results = ols(formula, dta).fit() >>> hypotheses = 'GNPDEFL = GNP, UNEMP = 2, YEAR/1829 = 1' >>> t_test = results.t_test(hypotheses) >>> print(t_test) Test for Constraints ============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------ c0 15.0977 84.937 0.178 0.863 -177.042 207.238 c1 -2.0202 0.488 -8.231 0.000 -3.125 -0.915 c2 1.0001 0.249 0.000 1.000 0.437 1.563 ============================================================================== ``` See also [`tvalues`](statsmodels.tsa.statespace.sarimax.sarimaxresults.tvalues#statsmodels.tsa.statespace.sarimax.SARIMAXResults.tvalues "statsmodels.tsa.statespace.sarimax.SARIMAXResults.tvalues") individual t statistics [`f_test`](statsmodels.tsa.statespace.sarimax.sarimaxresults.f_test#statsmodels.tsa.statespace.sarimax.SARIMAXResults.f_test "statsmodels.tsa.statespace.sarimax.SARIMAXResults.f_test") for F tests [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)")
programming_docs
statsmodels statsmodels.regression.quantile_regression.QuantRegResults.llf statsmodels.regression.quantile\_regression.QuantRegResults.llf =============================================================== `QuantRegResults.llf()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/quantile_regression.html#QuantRegResults.llf) statsmodels statsmodels.discrete.discrete_model.GeneralizedPoisson statsmodels.discrete.discrete\_model.GeneralizedPoisson ======================================================= `class statsmodels.discrete.discrete_model.GeneralizedPoisson(endog, exog, p=1, offset=None, exposure=None, missing='none', **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#GeneralizedPoisson) Generalized Poisson model for count data | Parameters: | * **endog** (*array-like*) – 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 `statsmodels.tools.add_constant`. * **p** (*scalar*) – P denotes parameterizations for GP regression. p=1 for GP-1 and p=2 for GP-2. Default is p=1. * **offset** (*array\_like*) – Offset is added to the linear prediction with coefficient equal to 1. * **exposure** (*array\_like*) – Log(exposure) 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.’ | `endog` *array* – A reference to the endogenous response variable `exog` *array* – A reference to the exogenous design. #### Methods | | | | --- | --- | | [`cdf`](statsmodels.discrete.discrete_model.generalizedpoisson.cdf#statsmodels.discrete.discrete_model.GeneralizedPoisson.cdf "statsmodels.discrete.discrete_model.GeneralizedPoisson.cdf")(X) | The cumulative distribution function of the model. | | [`cov_params_func_l1`](statsmodels.discrete.discrete_model.generalizedpoisson.cov_params_func_l1#statsmodels.discrete.discrete_model.GeneralizedPoisson.cov_params_func_l1 "statsmodels.discrete.discrete_model.GeneralizedPoisson.cov_params_func_l1")(likelihood\_model, xopt, …) | Computes cov\_params on a reduced parameter space corresponding to the nonzero parameters resulting from the l1 regularized fit. | | [`fit`](statsmodels.discrete.discrete_model.generalizedpoisson.fit#statsmodels.discrete.discrete_model.GeneralizedPoisson.fit "statsmodels.discrete.discrete_model.GeneralizedPoisson.fit")([start\_params, method, maxiter, …]) | Fit the model using maximum likelihood. | | [`fit_regularized`](statsmodels.discrete.discrete_model.generalizedpoisson.fit_regularized#statsmodels.discrete.discrete_model.GeneralizedPoisson.fit_regularized "statsmodels.discrete.discrete_model.GeneralizedPoisson.fit_regularized")([start\_params, method, …]) | Fit the model using a regularized maximum likelihood. | | [`from_formula`](statsmodels.discrete.discrete_model.generalizedpoisson.from_formula#statsmodels.discrete.discrete_model.GeneralizedPoisson.from_formula "statsmodels.discrete.discrete_model.GeneralizedPoisson.from_formula")(formula, data[, subset, drop\_cols]) | Create a Model from a formula and dataframe. | | [`hessian`](statsmodels.discrete.discrete_model.generalizedpoisson.hessian#statsmodels.discrete.discrete_model.GeneralizedPoisson.hessian "statsmodels.discrete.discrete_model.GeneralizedPoisson.hessian")(params) | Generalized Poisson model Hessian matrix of the loglikelihood | | [`information`](statsmodels.discrete.discrete_model.generalizedpoisson.information#statsmodels.discrete.discrete_model.GeneralizedPoisson.information "statsmodels.discrete.discrete_model.GeneralizedPoisson.information")(params) | Fisher information matrix of model | | [`initialize`](statsmodels.discrete.discrete_model.generalizedpoisson.initialize#statsmodels.discrete.discrete_model.GeneralizedPoisson.initialize "statsmodels.discrete.discrete_model.GeneralizedPoisson.initialize")() | Initialize is called by statsmodels.model.LikelihoodModel.\_\_init\_\_ and should contain any preprocessing that needs to be done for a model. | | [`loglike`](statsmodels.discrete.discrete_model.generalizedpoisson.loglike#statsmodels.discrete.discrete_model.GeneralizedPoisson.loglike "statsmodels.discrete.discrete_model.GeneralizedPoisson.loglike")(params) | Loglikelihood of Generalized Poisson model | | [`loglikeobs`](statsmodels.discrete.discrete_model.generalizedpoisson.loglikeobs#statsmodels.discrete.discrete_model.GeneralizedPoisson.loglikeobs "statsmodels.discrete.discrete_model.GeneralizedPoisson.loglikeobs")(params) | Loglikelihood for observations of Generalized Poisson model | | [`pdf`](statsmodels.discrete.discrete_model.generalizedpoisson.pdf#statsmodels.discrete.discrete_model.GeneralizedPoisson.pdf "statsmodels.discrete.discrete_model.GeneralizedPoisson.pdf")(X) | The probability density (mass) function of the model. | | [`predict`](statsmodels.discrete.discrete_model.generalizedpoisson.predict#statsmodels.discrete.discrete_model.GeneralizedPoisson.predict "statsmodels.discrete.discrete_model.GeneralizedPoisson.predict")(params[, exog, exposure, offset, which]) | Predict response variable of a count model given exogenous variables. | | [`score`](statsmodels.discrete.discrete_model.generalizedpoisson.score#statsmodels.discrete.discrete_model.GeneralizedPoisson.score "statsmodels.discrete.discrete_model.GeneralizedPoisson.score")(params) | Score vector of model. | | [`score_obs`](statsmodels.discrete.discrete_model.generalizedpoisson.score_obs#statsmodels.discrete.discrete_model.GeneralizedPoisson.score_obs "statsmodels.discrete.discrete_model.GeneralizedPoisson.score_obs")(params) | | #### Attributes | | | | --- | --- | | `endog_names` | Names of endogenous variables | | `exog_names` | Names of exogenous variables | statsmodels statsmodels.tsa.arima_model.ARMAResults.t_test_pairwise statsmodels.tsa.arima\_model.ARMAResults.t\_test\_pairwise ========================================================== `ARMAResults.t_test_pairwise(term_name, method='hs', alpha=0.05, factor_labels=None)` perform pairwise t\_test with multiple testing corrected p-values This uses the formula design\_info encoding contrast matrix and should work for all encodings of a main effect. | Parameters: | * **result** (*result instance*) – The results of an estimated model with a categorical main effect. * **term\_name** (*str*) – name of the term for which pairwise comparisons are computed. Term names for categorical effects are created by patsy and correspond to the main part of the exog names. * **method** (*str* *or* *list of strings*) – multiple testing p-value correction, default is ‘hs’, see stats.multipletesting * **alpha** (*float*) – significance level for multiple testing reject decision. * **factor\_labels** (*None**,* *list of str*) – Labels for the factor levels used for pairwise labels. If not provided, then the labels from the formula design\_info are used. | | Returns: | **results** – The results are stored as attributes, the main attributes are the following two. Other attributes are added for debugging purposes or as background information.* result\_frame : pandas DataFrame with t\_test results and multiple testing corrected p-values. * contrasts : matrix of constraints of the null hypothesis in the t\_test. | | Return type: | instance of a simple Results class | #### Notes Status: experimental. Currently only checked for treatment coding with and without specified reference level. Currently there are no multiple testing corrected confidence intervals available. #### Examples ``` >>> res = ols("np.log(Days+1) ~ C(Weight) + C(Duration)", data).fit() >>> pw = res.t_test_pairwise("C(Weight)") >>> pw.result_frame coef std err t P>|t| Conf. Int. Low 2-1 0.632315 0.230003 2.749157 8.028083e-03 0.171563 3-1 1.302555 0.230003 5.663201 5.331513e-07 0.841803 3-2 0.670240 0.230003 2.914044 5.119126e-03 0.209488 Conf. Int. Upp. pvalue-hs reject-hs 2-1 1.093067 0.010212 True 3-1 1.763307 0.000002 True 3-2 1.130992 0.010212 True ``` statsmodels statsmodels.stats.diagnostic.unitroot_adf statsmodels.stats.diagnostic.unitroot\_adf ========================================== `statsmodels.stats.diagnostic.unitroot_adf(x, maxlag=None, trendorder=0, autolag='AIC', store=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/diagnostic.html#unitroot_adf) statsmodels statsmodels.discrete.count_model.GenericZeroInflated.loglikeobs statsmodels.discrete.count\_model.GenericZeroInflated.loglikeobs ================================================================ `GenericZeroInflated.loglikeobs(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/count_model.html#GenericZeroInflated.loglikeobs) Loglikelihood for observations of Generic Zero Inflated model | Parameters: | **params** (*array-like*) – The parameters of the model. | | Returns: | **loglike** – The log likelihood for each observation of the model evaluated at `params`. See Notes | | Return type: | ndarray | #### Notes \[\ln L=\ln(w\_{i}+(1-w\_{i})\*P\_{main\\_model})+ \ln(1-w\_{i})+L\_{main\\_model} where P - pdf of main model, L - loglike function of main model.\] for observations \(i=1,...,n\) statsmodels statsmodels.discrete.discrete_model.ProbitResults.remove_data statsmodels.discrete.discrete\_model.ProbitResults.remove\_data =============================================================== `ProbitResults.remove_data()` remove data arrays, all nobs arrays from result and model This reduces the size of the instance, so it can be pickled with less memory. Currently tested for use with predict from an unpickled results and model instance. Warning Since data and some intermediate results have been removed calculating new statistics that require them will raise exceptions. The exception will occur the first time an attribute is accessed that has been set to None. Not fully tested for time series models, tsa, and might delete too much for prediction or not all that would be possible. The lists of arrays to delete are maintained as attributes of the result and model instance, except for cached values. These lists could be changed before calling remove\_data. The attributes to remove are named in: `model._data_attr : arrays attached to both the model instance` and the results instance with the same attribute name. `result.data_in_cache : arrays that may exist as values in` result.\_cache (TODO : should privatize name) `result._data_attr_model : arrays attached to the model` instance but not to the results instance statsmodels statsmodels.sandbox.stats.runs.median_test_ksample statsmodels.sandbox.stats.runs.median\_test\_ksample ==================================================== `statsmodels.sandbox.stats.runs.median_test_ksample(x, groups)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/runs.html#median_test_ksample) chisquare test for equality of median/location This tests whether all groups have the same fraction of observations above the median. | Parameters: | * **x** (*array\_like*) – data values stacked for all groups * **groups** (*array\_like*) – group labels or indicator | | Returns: | * **stat** (*float*) – test statistic * **pvalue** (*float*) – pvalue from the chisquare distribution * *others ????* – currently some test output, table and expected | statsmodels statsmodels.sandbox.distributions.extras.SkewNorm2_gen.median statsmodels.sandbox.distributions.extras.SkewNorm2\_gen.median ============================================================== `SkewNorm2_gen.median(*args, **kwds)` Median of the distribution. | Parameters: | * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – Location parameter, Default is 0. * **scale** (*array\_like**,* *optional*) – Scale parameter, Default is 1. | | Returns: | **median** – The median of the distribution. | | Return type: | float | See also `stats.distributions.rv_discrete.ppf` Inverse of the CDF statsmodels statsmodels.stats.stattools.jarque_bera statsmodels.stats.stattools.jarque\_bera ======================================== `statsmodels.stats.stattools.jarque_bera(resids, axis=0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/stattools.html#jarque_bera) Calculates the Jarque-Bera test for normality | Parameters: | * **data** (*array-like*) – Data to test for normality * **axis** (*int**,* *optional*) – Axis to use if data has more than 1 dimension. Default is 0 | | Returns: | * **JB** (*float or array*) – The Jarque-Bera test statistic * **JBpv** (*float or array*) – The pvalue of the test statistic * **skew** (*float or array*) – Estimated skewness of the data * **kurtosis** (*float or array*) – Estimated kurtosis of the data | #### Notes Each output returned has 1 dimension fewer than data The Jarque-Bera test statistic tests the null that the data is normally distributed against an alternative that the data follow some other distribution. The test statistic is based on two moments of the data, the skewness, and the kurtosis, and has an asymptotic \(\chi^2\_2\) distribution. The test statistic is defined \[JB = n(S^2/6+(K-3)^2/24)\] where n is the number of data points, S is the sample skewness, and K is the sample kurtosis of the data. statsmodels statsmodels.discrete.discrete_model.Probit.score_obs statsmodels.discrete.discrete\_model.Probit.score\_obs ====================================================== `Probit.score_obs(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#Probit.score_obs) Probit model Jacobian for each observation | Parameters: | **params** (*array-like*) – The parameters of the model | | Returns: | **jac** – The derivative of the loglikelihood for each observation evaluated at `params`. | | Return type: | array-like | #### Notes \[\frac{\partial\ln L\_{i}}{\partial\beta}=\left[\frac{q\_{i}\phi\left(q\_{i}x\_{i}^{\prime}\beta\right)}{\Phi\left(q\_{i}x\_{i}^{\prime}\beta\right)}\right]x\_{i}\] for observations \(i=1,...,n\) Where \(q=2y-1\). This simplification comes from the fact that the normal distribution is symmetric. statsmodels statsmodels.genmod.generalized_linear_model.GLMResults.tvalues statsmodels.genmod.generalized\_linear\_model.GLMResults.tvalues ================================================================ `GLMResults.tvalues()` Return the t-statistic for a given parameter estimate. statsmodels statsmodels.tsa.arima_process.ArmaProcess statsmodels.tsa.arima\_process.ArmaProcess ========================================== `class statsmodels.tsa.arima_process.ArmaProcess(ar=None, ma=None, nobs=100)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_process.html#ArmaProcess) Theoretical properties of an ARMA process for specified lag-polynomials | Parameters: | * **ar** (*array\_like**,* *1d**,* *optional*) – Coefficient for autoregressive lag polynomial, including zero lag. See the notes for some information about the sign. * **ma** (*array\_like**,* *1d**,* *optional*) – Coefficient for moving-average lag polynomial, including zero lag * **nobs** (*int**,* *optional*) – Length of simulated time series. Used, for example, if a sample is generated. See example. | #### Notes Both the AR and MA components must include the coefficient on the zero-lag. In almost all cases these values should be 1. Further, due to using the lag-polynomial representation, the AR parameters should have the opposite sign of what one would write in the ARMA representation. See the examples below. The ARMA(p,q) process is described by \[y\_{t}=\phi\_{1}y\_{t-1}+\ldots+\phi\_{p}y\_{t-p}+\theta\_{1}\epsilon\_{t-1} +\ldots+\theta\_{q}\epsilon\_{t-q}+\epsilon\_{t}\] and the parameterization used in this function uses the lag-polynomial representation, \[\left(1-\phi\_{1}L-\ldots-\phi\_{p}L^{p}\right)y\_{t} = \left(1-\theta\_{1}L-\ldots-\theta\_{q}L^{q}\right)\] #### Examples ``` >>> import numpy as np >>> np.random.seed(12345) >>> arparams = np.array([.75, -.25]) >>> maparams = np.array([.65, .35]) >>> ar = np.r_[1, -ar] # add zero-lag and negate >>> ma = np.r_[1, ma] # add zero-lag >>> arma_process = sm.tsa.ArmaProcess(ar, ma) >>> arma_process.isstationary True >>> arma_process.isinvertible True >>> y = arma_process.generate_sample(250) >>> model = sm.tsa.ARMA(y, (2, 2)).fit(trend='nc', disp=0) >>> model.params array([ 0.79044189, -0.23140636, 0.70072904, 0.40608028]) ``` #### Methods | | | | --- | --- | | [`acf`](statsmodels.tsa.arima_process.armaprocess.acf#statsmodels.tsa.arima_process.ArmaProcess.acf "statsmodels.tsa.arima_process.ArmaProcess.acf")([lags]) | Theoretical autocorrelation function of an ARMA process | | [`acovf`](statsmodels.tsa.arima_process.armaprocess.acovf#statsmodels.tsa.arima_process.ArmaProcess.acovf "statsmodels.tsa.arima_process.ArmaProcess.acovf")([nobs]) | Theoretical autocovariance function of ARMA process | | [`arma2ar`](statsmodels.tsa.arima_process.armaprocess.arma2ar#statsmodels.tsa.arima_process.ArmaProcess.arma2ar "statsmodels.tsa.arima_process.ArmaProcess.arma2ar")([lags]) | | | [`arma2ma`](statsmodels.tsa.arima_process.armaprocess.arma2ma#statsmodels.tsa.arima_process.ArmaProcess.arma2ma "statsmodels.tsa.arima_process.ArmaProcess.arma2ma")([lags]) | | | [`from_coeffs`](statsmodels.tsa.arima_process.armaprocess.from_coeffs#statsmodels.tsa.arima_process.ArmaProcess.from_coeffs "statsmodels.tsa.arima_process.ArmaProcess.from_coeffs")([arcoefs, macoefs, nobs]) | Convenience function to create ArmaProcess from ARMA representation | | [`from_estimation`](statsmodels.tsa.arima_process.armaprocess.from_estimation#statsmodels.tsa.arima_process.ArmaProcess.from_estimation "statsmodels.tsa.arima_process.ArmaProcess.from_estimation")(model\_results[, nobs]) | Convenience function to create an ArmaProcess from the results of an ARMA estimation | | [`generate_sample`](statsmodels.tsa.arima_process.armaprocess.generate_sample#statsmodels.tsa.arima_process.ArmaProcess.generate_sample "statsmodels.tsa.arima_process.ArmaProcess.generate_sample")([nsample, scale, distrvs, …]) | Simulate an ARMA | | [`impulse_response`](statsmodels.tsa.arima_process.armaprocess.impulse_response#statsmodels.tsa.arima_process.ArmaProcess.impulse_response "statsmodels.tsa.arima_process.ArmaProcess.impulse_response")([leads]) | Get the impulse response function (MA representation) for ARMA process | | [`invertroots`](statsmodels.tsa.arima_process.armaprocess.invertroots#statsmodels.tsa.arima_process.ArmaProcess.invertroots "statsmodels.tsa.arima_process.ArmaProcess.invertroots")([retnew]) | Make MA polynomial invertible by inverting roots inside unit circle | | [`pacf`](statsmodels.tsa.arima_process.armaprocess.pacf#statsmodels.tsa.arima_process.ArmaProcess.pacf "statsmodels.tsa.arima_process.ArmaProcess.pacf")([lags]) | Partial autocorrelation function of an ARMA process | | [`periodogram`](statsmodels.tsa.arima_process.armaprocess.periodogram#statsmodels.tsa.arima_process.ArmaProcess.periodogram "statsmodels.tsa.arima_process.ArmaProcess.periodogram")([nobs]) | Periodogram for ARMA process given by lag-polynomials ar and ma | #### Attributes | | | | --- | --- | | `arroots` | Roots of autoregressive lag-polynomial | | `isinvertible` | Arma process is invertible if MA roots are outside unit circle | | `isstationary` | Arma process is stationary if AR roots are outside unit circle | | `maroots` | Roots of moving average lag-polynomial |
programming_docs
statsmodels statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.set_filter_timing statsmodels.tsa.statespace.kalman\_smoother.KalmanSmoother.set\_filter\_timing ============================================================================== `KalmanSmoother.set_filter_timing(alternate_timing=None, **kwargs)` Set the filter timing convention By default, the Kalman filter follows Durbin and Koopman, 2012, in initializing the filter with predicted values. Kim and Nelson, 1999, instead initialize the filter with filtered values, which is essentially just a different timing convention. | Parameters: | * **alternate\_timing** (*integer**,* *optional*) – Whether or not to use the alternate timing convention. Default is unspecified. * **\*\*kwargs** – Keyword arguments may be used to influence the memory conservation method by setting individual boolean flags. See notes for details. | statsmodels statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialP.initialize statsmodels.discrete.count\_model.ZeroInflatedNegativeBinomialP.initialize ========================================================================== `ZeroInflatedNegativeBinomialP.initialize()` Initialize is called by statsmodels.model.LikelihoodModel.\_\_init\_\_ and should contain any preprocessing that needs to be done for a model. statsmodels statsmodels.iolib.summary2.Summary.as_latex statsmodels.iolib.summary2.Summary.as\_latex ============================================ `Summary.as_latex()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/iolib/summary2.html#Summary.as_latex) Generate LaTeX Summary Table statsmodels statsmodels.tsa.statespace.mlemodel.MLEResults.remove_data statsmodels.tsa.statespace.mlemodel.MLEResults.remove\_data =========================================================== `MLEResults.remove_data()` remove data arrays, all nobs arrays from result and model This reduces the size of the instance, so it can be pickled with less memory. Currently tested for use with predict from an unpickled results and model instance. Warning Since data and some intermediate results have been removed calculating new statistics that require them will raise exceptions. The exception will occur the first time an attribute is accessed that has been set to None. Not fully tested for time series models, tsa, and might delete too much for prediction or not all that would be possible. The lists of arrays to delete are maintained as attributes of the result and model instance, except for cached values. These lists could be changed before calling remove\_data. The attributes to remove are named in: `model._data_attr : arrays attached to both the model instance` and the results instance with the same attribute name. `result.data_in_cache : arrays that may exist as values in` result.\_cache (TODO : should privatize name) `result._data_attr_model : arrays attached to the model` instance but not to the results instance statsmodels statsmodels.discrete.discrete_model.CountResults.aic statsmodels.discrete.discrete\_model.CountResults.aic ===================================================== `CountResults.aic()` statsmodels statsmodels.genmod.generalized_linear_model.PredictionResults.conf_int statsmodels.genmod.generalized\_linear\_model.PredictionResults.conf\_int ========================================================================= `PredictionResults.conf_int(method='endpoint', alpha=0.05, **kwds)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/_prediction.html#PredictionResults.conf_int) Returns the confidence interval of the value, `effect` of the constraint. This is currently only available for t and z tests. | Parameters: | * **alpha** (*float**,* *optional*) – The significance level for the confidence interval. ie., The default `alpha` = .05 returns a 95% confidence interval. * **kwds** (*extra keyword arguments*) – currently ignored, only for compatibility, consistent signature | | Returns: | **ci** – The array has the lower and the upper limit of the confidence interval in the columns. | | Return type: | ndarray, (k\_constraints, 2) | statsmodels statsmodels.multivariate.manova.MANOVA.from_formula statsmodels.multivariate.manova.MANOVA.from\_formula ==================================================== `classmethod MANOVA.from_formula(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** (*extra arguments*) – These are passed to the model * **kwargs** (*extra keyword arguments*) – These are passed to the model with one exception. The `eval_env` keyword is passed to patsy. It can be either a [`patsy.EvalEnvironment`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.EvalEnvironment "(in patsy v0.5.0+dev)") 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** | | Return type: | 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 statsmodels.discrete.discrete_model.CountResults.t_test_pairwise statsmodels.discrete.discrete\_model.CountResults.t\_test\_pairwise =================================================================== `CountResults.t_test_pairwise(term_name, method='hs', alpha=0.05, factor_labels=None)` perform pairwise t\_test with multiple testing corrected p-values This uses the formula design\_info encoding contrast matrix and should work for all encodings of a main effect. | Parameters: | * **result** (*result instance*) – The results of an estimated model with a categorical main effect. * **term\_name** (*str*) – name of the term for which pairwise comparisons are computed. Term names for categorical effects are created by patsy and correspond to the main part of the exog names. * **method** (*str* *or* *list of strings*) – multiple testing p-value correction, default is ‘hs’, see stats.multipletesting * **alpha** (*float*) – significance level for multiple testing reject decision. * **factor\_labels** (*None**,* *list of str*) – Labels for the factor levels used for pairwise labels. If not provided, then the labels from the formula design\_info are used. | | Returns: | **results** – The results are stored as attributes, the main attributes are the following two. Other attributes are added for debugging purposes or as background information.* result\_frame : pandas DataFrame with t\_test results and multiple testing corrected p-values. * contrasts : matrix of constraints of the null hypothesis in the t\_test. | | Return type: | instance of a simple Results class | #### Notes Status: experimental. Currently only checked for treatment coding with and without specified reference level. Currently there are no multiple testing corrected confidence intervals available. #### Examples ``` >>> res = ols("np.log(Days+1) ~ C(Weight) + C(Duration)", data).fit() >>> pw = res.t_test_pairwise("C(Weight)") >>> pw.result_frame coef std err t P>|t| Conf. Int. Low 2-1 0.632315 0.230003 2.749157 8.028083e-03 0.171563 3-1 1.302555 0.230003 5.663201 5.331513e-07 0.841803 3-2 0.670240 0.230003 2.914044 5.119126e-03 0.209488 Conf. Int. Upp. pvalue-hs reject-hs 2-1 1.093067 0.010212 True 3-1 1.763307 0.000002 True 3-2 1.130992 0.010212 True ``` statsmodels statsmodels.tsa.statespace.sarimax.SARIMAXResults.initialize statsmodels.tsa.statespace.sarimax.SARIMAXResults.initialize ============================================================ `SARIMAXResults.initialize(model, params, **kwd)` statsmodels statsmodels.emplike.descriptive.DescStatUV statsmodels.emplike.descriptive.DescStatUV ========================================== `class statsmodels.emplike.descriptive.DescStatUV(endog)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/emplike/descriptive.html#DescStatUV) A class to compute confidence intervals and hypothesis tests involving mean, variance, kurtosis and skewness of a univariate random variable. | Parameters: | **endog** (*1darray*) – Data to be analyzed | `endog` *1darray* – Data to be analyzed `nobs` *float* – Number of observations #### Methods | | | | --- | --- | | [`ci_kurt`](statsmodels.emplike.descriptive.descstatuv.ci_kurt#statsmodels.emplike.descriptive.DescStatUV.ci_kurt "statsmodels.emplike.descriptive.DescStatUV.ci_kurt")([sig, upper\_bound, lower\_bound]) | Returns the confidence interval for kurtosis. | | [`ci_mean`](statsmodels.emplike.descriptive.descstatuv.ci_mean#statsmodels.emplike.descriptive.DescStatUV.ci_mean "statsmodels.emplike.descriptive.DescStatUV.ci_mean")([sig, method, epsilon, gamma\_low, …]) | Returns the confidence interval for the mean. | | [`ci_skew`](statsmodels.emplike.descriptive.descstatuv.ci_skew#statsmodels.emplike.descriptive.DescStatUV.ci_skew "statsmodels.emplike.descriptive.DescStatUV.ci_skew")([sig, upper\_bound, lower\_bound]) | Returns the confidence interval for skewness. | | [`ci_var`](statsmodels.emplike.descriptive.descstatuv.ci_var#statsmodels.emplike.descriptive.DescStatUV.ci_var "statsmodels.emplike.descriptive.DescStatUV.ci_var")([lower\_bound, upper\_bound, sig]) | Returns the confidence interval for the variance. | | [`plot_contour`](statsmodels.emplike.descriptive.descstatuv.plot_contour#statsmodels.emplike.descriptive.DescStatUV.plot_contour "statsmodels.emplike.descriptive.DescStatUV.plot_contour")(mu\_low, mu\_high, var\_low, …) | Returns a plot of the confidence region for a univariate mean and variance. | | [`test_joint_skew_kurt`](statsmodels.emplike.descriptive.descstatuv.test_joint_skew_kurt#statsmodels.emplike.descriptive.DescStatUV.test_joint_skew_kurt "statsmodels.emplike.descriptive.DescStatUV.test_joint_skew_kurt")(skew0, kurt0[, …]) | Returns - 2 x log-likelihood and the p-value for the joint hypothesis test for skewness and kurtosis | | [`test_kurt`](statsmodels.emplike.descriptive.descstatuv.test_kurt#statsmodels.emplike.descriptive.DescStatUV.test_kurt "statsmodels.emplike.descriptive.DescStatUV.test_kurt")(kurt0[, return\_weights]) | Returns -2 x log-likelihood and the p-value for the hypothesized kurtosis. | | [`test_mean`](statsmodels.emplike.descriptive.descstatuv.test_mean#statsmodels.emplike.descriptive.DescStatUV.test_mean "statsmodels.emplike.descriptive.DescStatUV.test_mean")(mu0[, return\_weights]) | Returns - 2 x log-likelihood ratio, p-value and weights for a hypothesis test of the mean. | | [`test_skew`](statsmodels.emplike.descriptive.descstatuv.test_skew#statsmodels.emplike.descriptive.DescStatUV.test_skew "statsmodels.emplike.descriptive.DescStatUV.test_skew")(skew0[, return\_weights]) | Returns -2 x log-likelihood and p-value for the hypothesized skewness. | | [`test_var`](statsmodels.emplike.descriptive.descstatuv.test_var#statsmodels.emplike.descriptive.DescStatUV.test_var "statsmodels.emplike.descriptive.DescStatUV.test_var")(sig2\_0[, return\_weights]) | Returns -2 x log-likelihoog ratio and the p-value for the hypothesized variance | statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.wald_test statsmodels.tsa.statespace.dynamic\_factor.DynamicFactorResults.wald\_test ========================================================================== `DynamicFactorResults.wald_test(r_matrix, cov_p=None, scale=1.0, invcov=None, use_f=None)` Compute a Wald-test for a joint linear hypothesis. | Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) – + array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length p row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – Default is 1.0 for no scaling. * **invcov** (*array-like**,* *optional*) – A q x q array to specify an inverse covariance matrix based on a restrictions matrix. * **use\_f** (*bool*) – If True, then the F-distribution is used. If False, then the asymptotic distribution, chisquare is used. If use\_f is None, then the F distribution is used if the model specifies that use\_t is True. The test statistic is proportionally adjusted for the distribution by the number of constraints in the hypothesis. | | Returns: | **res** – The results for the test are attributes of this results instance. | | Return type: | ContrastResults instance | See also [`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`f_test`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactorresults.f_test#statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.f_test "statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.f_test"), [`t_test`](statsmodels.tsa.statespace.dynamic_factor.dynamicfactorresults.t_test#statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.t_test "statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") #### Notes The matrix `r_matrix` is assumed to be non-singular. More precisely, r\_matrix (pX pX.T) r\_matrix.T is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full. statsmodels statsmodels.regression.linear_model.OLSResults.get_prediction statsmodels.regression.linear\_model.OLSResults.get\_prediction =============================================================== `OLSResults.get_prediction(exog=None, transform=True, weights=None, row_labels=None, **kwds)` compute prediction results | Parameters: | * **exog** (*array-like**,* *optional*) – The values for which you want to predict. * **transform** (*bool**,* *optional*) – If the model was fit via a formula, do you want to pass exog through the formula. Default is True. E.g., if you fit a model y ~ log(x1) + log(x2), and transform is True, then you can pass a data structure that contains x1 and x2 in their original form. Otherwise, you’d need to log the data first. * **weights** (*array\_like**,* *optional*) – Weights interpreted as in WLS, used for the variance of the predicted residual. * **kwargs** (*args**,*) – Some models can take additional arguments or keywords, see the predict method of the model for the details. | | Returns: | **prediction\_results** – The prediction results instance contains prediction and prediction variance and can on demand calculate confidence intervals and summary tables for the prediction of the mean and of new observations. | | Return type: | [linear\_model.PredictionResults](statsmodels.regression.linear_model.predictionresults#statsmodels.regression.linear_model.PredictionResults "statsmodels.regression.linear_model.PredictionResults") | statsmodels statsmodels.discrete.discrete_model.GeneralizedPoissonResults.f_test statsmodels.discrete.discrete\_model.GeneralizedPoissonResults.f\_test ====================================================================== `GeneralizedPoissonResults.f_test(r_matrix, cov_p=None, scale=1.0, invcov=None)` Compute the F-test for a joint linear hypothesis. This is a special case of `wald_test` that always uses the F distribution. | Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) – + array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length k row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – Default is 1.0 for no scaling. * **invcov** (*array-like**,* *optional*) – A q x q array to specify an inverse covariance matrix based on a restrictions matrix. | | Returns: | **res** – The results for the test are attributes of this results instance. | | Return type: | ContrastResults instance | #### Examples ``` >>> import numpy as np >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> A = np.identity(len(results.params)) >>> A = A[1:,:] ``` This tests that each coefficient is jointly statistically significantly different from zero. ``` >>> print(results.f_test(A)) <F test: F=array([[ 330.28533923]]), p=4.984030528700946e-10, df_denom=9, df_num=6> ``` Compare this to ``` >>> results.fvalue 330.2853392346658 >>> results.f_pvalue 4.98403096572e-10 ``` ``` >>> B = np.array(([0,0,1,-1,0,0,0],[0,0,0,0,0,1,-1])) ``` This tests that the coefficient on the 2nd and 3rd regressors are equal and jointly that the coefficient on the 5th and 6th regressors are equal. ``` >>> print(results.f_test(B)) <F test: F=array([[ 9.74046187]]), p=0.005605288531708235, df_denom=9, df_num=2> ``` Alternatively, you can specify the hypothesis tests using a string ``` >>> from statsmodels.datasets import longley >>> from statsmodels.formula.api import ols >>> dta = longley.load_pandas().data >>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' >>> results = ols(formula, dta).fit() >>> hypotheses = '(GNPDEFL = GNP), (UNEMP = 2), (YEAR/1829 = 1)' >>> f_test = results.f_test(hypotheses) >>> print(f_test) <F test: F=array([[ 144.17976065]]), p=6.322026217355609e-08, df_denom=9, df_num=3> ``` See also [`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`wald_test`](statsmodels.discrete.discrete_model.generalizedpoissonresults.wald_test#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.wald_test "statsmodels.discrete.discrete_model.GeneralizedPoissonResults.wald_test"), [`t_test`](statsmodels.discrete.discrete_model.generalizedpoissonresults.t_test#statsmodels.discrete.discrete_model.GeneralizedPoissonResults.t_test "statsmodels.discrete.discrete_model.GeneralizedPoissonResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") #### Notes The matrix `r_matrix` is assumed to be non-singular. More precisely, r\_matrix (pX pX.T) r\_matrix.T is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full.
programming_docs
statsmodels statsmodels.tsa.statespace.mlemodel.MLEResults.zvalues statsmodels.tsa.statespace.mlemodel.MLEResults.zvalues ====================================================== `MLEResults.zvalues()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEResults.zvalues) (array) The z-statistics for the coefficients. statsmodels statsmodels.regression.linear_model.GLSAR.initialize statsmodels.regression.linear\_model.GLSAR.initialize ===================================================== `GLSAR.initialize()` Initialize (possibly re-initialize) a Model instance. For instance, the design matrix of a linear model may change and some things must be recomputed. statsmodels statsmodels.discrete.discrete_model.Logit.information statsmodels.discrete.discrete\_model.Logit.information ====================================================== `Logit.information(params)` Fisher information matrix of model Returns -Hessian of loglike evaluated at params. statsmodels statsmodels.tsa.statespace.sarimax.SARIMAXResults.arfreq statsmodels.tsa.statespace.sarimax.SARIMAXResults.arfreq ======================================================== `SARIMAXResults.arfreq()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/sarimax.html#SARIMAXResults.arfreq) (array) Frequency of the roots of the reduced form autoregressive lag polynomial statsmodels statsmodels.tsa.statespace.kalman_smoother.SmootherResults.update_representation statsmodels.tsa.statespace.kalman\_smoother.SmootherResults.update\_representation ================================================================================== `SmootherResults.update_representation(model, only_options=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/kalman_smoother.html#SmootherResults.update_representation) Update the results to match a given model | Parameters: | * **model** ([Representation](statsmodels.tsa.statespace.representation.representation#statsmodels.tsa.statespace.representation.Representation "statsmodels.tsa.statespace.representation.Representation")) – The model object from which to take the updated values. * **only\_options** (*boolean**,* *optional*) – If set to true, only the smoother and filter options are updated, and the state space representation is not updated. Default is False. | #### Notes This method is rarely required except for internal usage. statsmodels statsmodels.regression.quantile_regression.QuantRegResults.cov_HC2 statsmodels.regression.quantile\_regression.QuantRegResults.cov\_HC2 ==================================================================== `QuantRegResults.cov_HC2()` See statsmodels.RegressionResults statsmodels statsmodels.regression.linear_model.RegressionResults.resid_pearson statsmodels.regression.linear\_model.RegressionResults.resid\_pearson ===================================================================== `RegressionResults.resid_pearson()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#RegressionResults.resid_pearson) Residuals, normalized to have unit variance. | Returns: | | | Return type: | An array wresid standardized by the sqrt if scale | statsmodels statsmodels.regression.linear_model.OLSResults.resid_pearson statsmodels.regression.linear\_model.OLSResults.resid\_pearson ============================================================== `OLSResults.resid_pearson()` Residuals, normalized to have unit variance. | Returns: | | | Return type: | An array wresid standardized by the sqrt if scale | statsmodels statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.score_obs statsmodels.discrete.count\_model.ZeroInflatedGeneralizedPoisson.score\_obs =========================================================================== `ZeroInflatedGeneralizedPoisson.score_obs(params)` Generic Zero Inflated model score (gradient) vector of the log-likelihood | Parameters: | **params** (*array-like*) – The parameters of the model | | Returns: | **score** – The score vector of the model, i.e. the first derivative of the loglikelihood function, evaluated at `params` | | Return type: | ndarray, 1-D | statsmodels statsmodels.tsa.statespace.structural.UnobservedComponentsResults.test_serial_correlation statsmodels.tsa.statespace.structural.UnobservedComponentsResults.test\_serial\_correlation =========================================================================================== `UnobservedComponentsResults.test_serial_correlation(method, lags=None)` Ljung-box test for no serial correlation of standardized residuals Null hypothesis is no serial correlation. | Parameters: | * **method** (*string {'ljungbox'**,**'boxpierece'}* *or* *None*) – The statistical test for serial correlation. If None, an attempt is made to select an appropriate test. * **lags** (*None**,* *int* *or* *array\_like*) – If lags is an integer then this is taken to be the largest lag that is included, the test result is reported for all smaller lag length. If lags is a list or array, then all lags are included up to the largest lag in the list, however only the tests for the lags in the list are reported. If lags is None, then the default maxlag is 12\*(nobs/100)^{1/4} | | Returns: | **output** – An array with `(test_statistic, pvalue)` for each endogenous variable and each lag. The array is then sized `(k_endog, 2, lags)`. If the method is called as `ljungbox = res.test_serial_correlation()`, then `ljungbox[i]` holds the results of the Ljung-Box test (as would be returned by `statsmodels.stats.diagnostic.acorr_ljungbox`) for the `i` th endogenous variable. | | Return type: | array | #### Notes If the first `d` loglikelihood values were burned (i.e. in the specified model, `loglikelihood_burn=d`), then this test is calculated ignoring the first `d` residuals. Output is nan for any endogenous variable which has missing values. See also [`statsmodels.stats.diagnostic.acorr_ljungbox`](statsmodels.stats.diagnostic.acorr_ljungbox#statsmodels.stats.diagnostic.acorr_ljungbox "statsmodels.stats.diagnostic.acorr_ljungbox") statsmodels statsmodels.tsa.statespace.sarimax.SARIMAXResults.cov_params_approx statsmodels.tsa.statespace.sarimax.SARIMAXResults.cov\_params\_approx ===================================================================== `SARIMAXResults.cov_params_approx()` (array) The variance / covariance matrix. Computed using the numerical Hessian approximated by complex step or finite differences methods. statsmodels statsmodels.regression.recursive_ls.RecursiveLSResults.loglikelihood_burn statsmodels.regression.recursive\_ls.RecursiveLSResults.loglikelihood\_burn =========================================================================== `RecursiveLSResults.loglikelihood_burn()` (float) The number of observations during which the likelihood is not evaluated. statsmodels statsmodels.genmod.generalized_linear_model.GLM statsmodels.genmod.generalized\_linear\_model.GLM ================================================= `class statsmodels.genmod.generalized_linear_model.GLM(endog, exog, family=None, offset=None, exposure=None, freq_weights=None, var_weights=None, missing='none', **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_linear_model.html#GLM) Generalized Linear Models class GLM inherits from statsmodels.base.model.LikelihoodModel | Parameters: | * **endog** (*array-like*) – 1d array of endogenous response variable. This array can be 1d or 2d. Binomial family models accept a 2d array with two columns. If supplied, each observation is expected to be [success, failure]. * **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 (models specified using a formula include an intercept by default). See `statsmodels.tools.add_constant`. * **family** (*family class instance*) – The default is Gaussian. To specify the binomial distribution family = sm.family.Binomial() Each family can take a link instance as an argument. See statsmodels.family.family for more information. * **offset** (*array-like* *or* *None*) – An offset to be included in the model. If provided, must be an array whose length is the number of rows in exog. * **exposure** (*array-like* *or* *None*) – Log(exposure) will be added to the linear prediction in the model. Exposure is only valid if the log link is used. If provided, it must be an array with the same length as endog. * **freq\_weights** (*array-like*) – 1d array of frequency weights. The default is None. If None is selected or a blank value, then the algorithm will replace with an array of 1’s with length equal to the endog. WARNING: Using weights is not verified yet for all possible options and results, see Notes. * **var\_weights** (*array-like*) – 1d array of variance (analytic) weights. The default is None. If None is selected or a blank value, then the algorithm will replace with an array of 1’s with length equal to the endog. WARNING: Using weights is not verified yet for all possible options and results, see Notes. * **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.’ | `df_model` *float* – `p` - 1, where `p` is the number of regressors including the intercept. `df_resid` *float* – The number of observation `n` minus the number of regressors `p`. `endog` *array* – See Parameters. `exog` *array* – See Parameters. `family` *family class instance* – A pointer to the distribution family of the model. `freq_weights` *array* – See Parameters. `var_weights` *array* – See Parameters. `mu` *array* – The estimated mean response of the transformed variable. `n_trials` *array* – See Parameters. `normalized_cov_params` *array* – `p` x `p` normalized covariance of the design / exogenous data. `scale` *float* – The estimate of the scale / dispersion. Available after fit is called. `scaletype` *str* – The scaling used for fitting the model. Available after fit is called. `weights` *array* – The value of the weights after the last iteration of fit. #### Examples ``` >>> import statsmodels.api as sm >>> data = sm.datasets.scotland.load() >>> data.exog = sm.add_constant(data.exog) ``` Instantiate a gamma family model with the default link function. ``` >>> gamma_model = sm.GLM(data.endog, data.exog, ... family=sm.families.Gamma()) ``` ``` >>> gamma_results = gamma_model.fit() >>> gamma_results.params array([-0.01776527, 0.00004962, 0.00203442, -0.00007181, 0.00011185, -0.00000015, -0.00051868, -0.00000243]) >>> gamma_results.scale 0.0035842831734919055 >>> gamma_results.deviance 0.087388516416999198 >>> gamma_results.pearson_chi2 0.086022796163805704 >>> gamma_results.llf -83.017202161073527 ``` See also [`statsmodels.genmod.families.family.Family`](statsmodels.genmod.families.family.family#statsmodels.genmod.families.family.Family "statsmodels.genmod.families.family.Family"), [Families](../glm#families), [Link Functions](../glm#links) #### Notes Only the following combinations make sense for family and link: | Family | ident | log | logit | probit | cloglog | pow | opow | nbinom | loglog | logc | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | Gaussian | x | x | x | x | x | x | x | x | x | | | inv Gaussian | x | x | | | | x | | | | | | binomial | x | x | x | x | x | x | x | | x | x | | Poission | x | x | | | | x | | | | | | neg binomial | x | x | | | | x | | x | | | | gamma | x | x | | | | x | | | | | | Tweedie | x | x | | | | x | | | | | Not all of these link functions are currently available. Endog and exog are references so that if the data they refer to are already arrays and these arrays are changed, endog and exog will change. Statsmodels supports two separte definitions of weights: frequency weights and variance weights. Frequency weights produce the same results as repeating observations by the frequencies (if those are integers). Frequency weights will keep the number of observations consistent, but the degrees of freedom will change to reflect the new weights. Variance weights (referred to in other packages as analytic weights) are used when `endog` represents an an average or mean. This relies on the assumption that that the inverse variance scales proportionally to the weight–an observation that is deemed more credible should have less variance and therefore have more weight. For the `Poisson` family–which assumes that occurences scale proportionally with time–a natural practice would be to use the amount of time as the variance weight and set `endog` to be a rate (occurrances per period of time). Similarly, using a compound Poisson family, namely `Tweedie`, makes a similar assumption about the rate (or frequency) of occurences having variance proportional to time. Both frequency and variance weights are verified for all basic results with nonrobust or heteroscedasticity robust `cov_type`. Other robust covariance types have not yet been verified, and at least the small sample correction is currently not based on the correct total frequency count. Currently, all residuals are not weighted by frequency, although they may incorporate `n_trials` for `Binomial` and `var_weights` | Residual Type | Applicable weights | | --- | --- | | Anscombe | `var_weights` | | Deviance | `var_weights` | | Pearson | `var_weights` and `n_trials` | | Reponse | `n_trials` | | Working | `n_trials` | WARNING: Loglikelihood and deviance are not valid in models where scale is equal to 1 (i.e., `Binomial`, `NegativeBinomial`, and `Poisson`). If variance weights are specified, then results such as `loglike` and `deviance` are based on a quasi-likelihood interpretation. The loglikelihood is not correctly specified in this case, and statistics based on it, such AIC or likelihood ratio tests, are not appropriate. `df_model` *float* – Model degrees of freedom is equal to p - 1, where p is the number of regressors. Note that the intercept is not reported as a degree of freedom. `df_resid` *float* – Residual degrees of freedom is equal to the number of observation n minus the number of regressors p. `endog` *array* – See above. Note that `endog` is a reference to the data so that if data is already an array and it is changed, then `endog` changes as well. `exposure` *array-like* – Include ln(exposure) in model with coefficient constrained to 1. Can only be used if the link is the logarithm function. `exog` *array* – See above. Note that `exog` is a reference to the data so that if data is already an array and it is changed, then `exog` changes as well. `freq_weights` *array* – See above. Note that `freq_weights` is a reference to the data so that if data is already an array and it is changed, then `freq_weights` changes as well. `var_weights` *array* – See above. Note that `var_weights` is a reference to the data so that if data is already an array and it is changed, then `var_weights` changes as well. `iteration` *int* – The number of iterations that fit has run. Initialized at 0. `family` *family class instance* – The distribution family of the model. Can be any family in statsmodels.families. Default is Gaussian. `mu` *array* – The mean response of the transformed variable. `mu` is the value of the inverse of the link function at lin\_pred, where lin\_pred is the linear predicted value of the WLS fit of the transformed variable. `mu` is only available after fit is called. See statsmodels.families.family.fitted of the distribution family for more information. `n_trials` *array* – See above. Note that `n_trials` is a reference to the data so that if data is already an array and it is changed, then `n_trials` changes as well. `n_trials` is the number of binomial trials and only available with that distribution. See statsmodels.families.Binomial for more information. `normalized_cov_params` *array* – The p x p normalized covariance of the design / exogenous data. This is approximately equal to (X.T X)^(-1) `offset` *array-like* – Include offset in model with coefficient constrained to 1. `scale` *float* – The estimate of the scale / dispersion of the model fit. Only available after fit is called. See GLM.fit and GLM.estimate\_scale for more information. `scaletype` *str* – The scaling used for fitting the model. This is only available after fit is called. The default is None. See GLM.fit for more information. `weights` *array* – The value of the weights after the last iteration of fit. Only available after fit is called. See statsmodels.families.family for the specific distribution weighting functions. #### Methods | | | | --- | --- | | [`estimate_scale`](statsmodels.genmod.generalized_linear_model.glm.estimate_scale#statsmodels.genmod.generalized_linear_model.GLM.estimate_scale "statsmodels.genmod.generalized_linear_model.GLM.estimate_scale")(mu) | Estimates the dispersion/scale. | | [`estimate_tweedie_power`](statsmodels.genmod.generalized_linear_model.glm.estimate_tweedie_power#statsmodels.genmod.generalized_linear_model.GLM.estimate_tweedie_power "statsmodels.genmod.generalized_linear_model.GLM.estimate_tweedie_power")(mu[, method, low, high]) | Tweedie specific function to estimate scale and the variance parameter. | | [`fit`](statsmodels.genmod.generalized_linear_model.glm.fit#statsmodels.genmod.generalized_linear_model.GLM.fit "statsmodels.genmod.generalized_linear_model.GLM.fit")([start\_params, maxiter, method, tol, …]) | Fits a generalized linear model for a given family. | | [`fit_constrained`](statsmodels.genmod.generalized_linear_model.glm.fit_constrained#statsmodels.genmod.generalized_linear_model.GLM.fit_constrained "statsmodels.genmod.generalized_linear_model.GLM.fit_constrained")(constraints[, start\_params]) | fit the model subject to linear equality constraints | | [`fit_regularized`](statsmodels.genmod.generalized_linear_model.glm.fit_regularized#statsmodels.genmod.generalized_linear_model.GLM.fit_regularized "statsmodels.genmod.generalized_linear_model.GLM.fit_regularized")([method, alpha, …]) | Return a regularized fit to a linear regression model. | | [`from_formula`](statsmodels.genmod.generalized_linear_model.glm.from_formula#statsmodels.genmod.generalized_linear_model.GLM.from_formula "statsmodels.genmod.generalized_linear_model.GLM.from_formula")(formula, data[, subset, drop\_cols]) | Create a Model from a formula and dataframe. | | [`get_distribution`](statsmodels.genmod.generalized_linear_model.glm.get_distribution#statsmodels.genmod.generalized_linear_model.GLM.get_distribution "statsmodels.genmod.generalized_linear_model.GLM.get_distribution")(params[, scale, exog, …]) | Returns a random number generator for the predictive distribution. | | [`hessian`](statsmodels.genmod.generalized_linear_model.glm.hessian#statsmodels.genmod.generalized_linear_model.GLM.hessian "statsmodels.genmod.generalized_linear_model.GLM.hessian")(params[, scale, observed]) | Hessian, second derivative of loglikelihood function | | [`hessian_factor`](statsmodels.genmod.generalized_linear_model.glm.hessian_factor#statsmodels.genmod.generalized_linear_model.GLM.hessian_factor "statsmodels.genmod.generalized_linear_model.GLM.hessian_factor")(params[, scale, observed]) | Weights for calculating Hessian | | [`information`](statsmodels.genmod.generalized_linear_model.glm.information#statsmodels.genmod.generalized_linear_model.GLM.information "statsmodels.genmod.generalized_linear_model.GLM.information")(params[, scale]) | Fisher information matrix. | | [`initialize`](statsmodels.genmod.generalized_linear_model.glm.initialize#statsmodels.genmod.generalized_linear_model.GLM.initialize "statsmodels.genmod.generalized_linear_model.GLM.initialize")() | Initialize a generalized linear model. | | [`loglike`](statsmodels.genmod.generalized_linear_model.glm.loglike#statsmodels.genmod.generalized_linear_model.GLM.loglike "statsmodels.genmod.generalized_linear_model.GLM.loglike")(params[, scale]) | Evaluate the log-likelihood for a generalized linear model. | | [`loglike_mu`](statsmodels.genmod.generalized_linear_model.glm.loglike_mu#statsmodels.genmod.generalized_linear_model.GLM.loglike_mu "statsmodels.genmod.generalized_linear_model.GLM.loglike_mu")(mu[, scale]) | Evaluate the log-likelihood for a generalized linear model. | | [`predict`](statsmodels.genmod.generalized_linear_model.glm.predict#statsmodels.genmod.generalized_linear_model.GLM.predict "statsmodels.genmod.generalized_linear_model.GLM.predict")(params[, exog, exposure, offset, linear]) | Return predicted values for a design matrix | | [`score`](statsmodels.genmod.generalized_linear_model.glm.score#statsmodels.genmod.generalized_linear_model.GLM.score "statsmodels.genmod.generalized_linear_model.GLM.score")(params[, scale]) | score, first derivative of the loglikelihood function | | [`score_factor`](statsmodels.genmod.generalized_linear_model.glm.score_factor#statsmodels.genmod.generalized_linear_model.GLM.score_factor "statsmodels.genmod.generalized_linear_model.GLM.score_factor")(params[, scale]) | weights for score for each observation | | [`score_obs`](statsmodels.genmod.generalized_linear_model.glm.score_obs#statsmodels.genmod.generalized_linear_model.GLM.score_obs "statsmodels.genmod.generalized_linear_model.GLM.score_obs")(params[, scale]) | score first derivative of the loglikelihood for each observation. | | [`score_test`](statsmodels.genmod.generalized_linear_model.glm.score_test#statsmodels.genmod.generalized_linear_model.GLM.score_test "statsmodels.genmod.generalized_linear_model.GLM.score_test")(params\_constrained[, …]) | score test for restrictions or for omitted variables | #### Attributes | | | | --- | --- | | `endog_names` | Names of endogenous variables | | `exog_names` | Names of exogenous variables |
programming_docs
statsmodels statsmodels.tsa.arima_process.arma_impulse_response statsmodels.tsa.arima\_process.arma\_impulse\_response ====================================================== `statsmodels.tsa.arima_process.arma_impulse_response(ar, ma, leads=100, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_process.html#arma_impulse_response) Get the impulse response function (MA representation) for ARMA process | Parameters: | * **ma** (*array\_like**,* *1d*) – moving average lag polynomial * **ar** (*array\_like**,* *1d*) – auto regressive lag polynomial * **leads** (*int*) – number of observations to calculate | | Returns: | **ir** – impulse response function with nobs elements | | Return type: | array, 1d | #### Notes This is the same as finding the MA representation of an ARMA(p,q). By reversing the role of ar and ma in the function arguments, the returned result is the AR representation of an ARMA(p,q), i.e ma\_representation = arma\_impulse\_response(ar, ma, leads=100) ar\_representation = arma\_impulse\_response(ma, ar, leads=100) Fully tested against matlab #### Examples AR(1) ``` >>> arma_impulse_response([1.0, -0.8], [1.], leads=10) array([ 1. , 0.8 , 0.64 , 0.512 , 0.4096 , 0.32768 , 0.262144 , 0.2097152 , 0.16777216, 0.13421773]) ``` this is the same as ``` >>> 0.8**np.arange(10) array([ 1. , 0.8 , 0.64 , 0.512 , 0.4096 , 0.32768 , 0.262144 , 0.2097152 , 0.16777216, 0.13421773]) ``` MA(2) ``` >>> arma_impulse_response([1.0], [1., 0.5, 0.2], leads=10) array([ 1. , 0.5, 0.2, 0. , 0. , 0. , 0. , 0. , 0. , 0. ]) ``` ARMA(1,2) ``` >>> arma_impulse_response([1.0, -0.8], [1., 0.5, 0.2], leads=10) array([ 1. , 1.3 , 1.24 , 0.992 , 0.7936 , 0.63488 , 0.507904 , 0.4063232 , 0.32505856, 0.26004685]) ``` statsmodels statsmodels.iolib.summary.Summary.as_latex statsmodels.iolib.summary.Summary.as\_latex =========================================== `Summary.as_latex()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/iolib/summary.html#Summary.as_latex) return tables as string | Returns: | **latex** – summary tables and extra text as string of Latex | | Return type: | string | #### Notes This currently merges tables with different number of columns. It is recommended to use `as_latex_tabular` directly on the individual tables. statsmodels statsmodels.regression.recursive_ls.RecursiveLSResults.t_test statsmodels.regression.recursive\_ls.RecursiveLSResults.t\_test =============================================================== `RecursiveLSResults.t_test(r_matrix, cov_p=None, scale=None, use_t=None)` Compute a t-test for a each linear hypothesis of the form Rb = q | Parameters: | * **r\_matrix** (*array-like**,* *str**,* *tuple*) – + array : If an array is given, a p x k 2d array or length k 1d array specifying the linear restrictions. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q). If q is given, can be either a scalar or a length p row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – An optional `scale` to use. Default is the scale specified by the model fit. * **use\_t** (*bool**,* *optional*) – If use\_t is None, then the default of the model is used. If use\_t is True, then the p-values are based on the t distribution. If use\_t is False, then the p-values are based on the normal distribution. | | Returns: | **res** – The results for the test are attributes of this results instance. The available results have the same elements as the parameter table in `summary()`. | | Return type: | ContrastResults instance | #### Examples ``` >>> import numpy as np >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> r = np.zeros_like(results.params) >>> r[5:] = [1,-1] >>> print(r) [ 0. 0. 0. 0. 0. 1. -1.] ``` r tests that the coefficients on the 5th and 6th independent variable are the same. ``` >>> T_test = results.t_test(r) >>> print(T_test) Test for Constraints ============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------ c0 -1829.2026 455.391 -4.017 0.003 -2859.368 -799.037 ============================================================================== >>> T_test.effect -1829.2025687192481 >>> T_test.sd 455.39079425193762 >>> T_test.tvalue -4.0167754636411717 >>> T_test.pvalue 0.0015163772380899498 ``` Alternatively, you can specify the hypothesis tests using a string ``` >>> from statsmodels.formula.api import ols >>> dta = sm.datasets.longley.load_pandas().data >>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' >>> results = ols(formula, dta).fit() >>> hypotheses = 'GNPDEFL = GNP, UNEMP = 2, YEAR/1829 = 1' >>> t_test = results.t_test(hypotheses) >>> print(t_test) Test for Constraints ============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------ c0 15.0977 84.937 0.178 0.863 -177.042 207.238 c1 -2.0202 0.488 -8.231 0.000 -3.125 -0.915 c2 1.0001 0.249 0.000 1.000 0.437 1.563 ============================================================================== ``` See also [`tvalues`](statsmodels.regression.recursive_ls.recursivelsresults.tvalues#statsmodels.regression.recursive_ls.RecursiveLSResults.tvalues "statsmodels.regression.recursive_ls.RecursiveLSResults.tvalues") individual t statistics [`f_test`](statsmodels.regression.recursive_ls.recursivelsresults.f_test#statsmodels.regression.recursive_ls.RecursiveLSResults.f_test "statsmodels.regression.recursive_ls.RecursiveLSResults.f_test") for F tests [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") statsmodels statsmodels.tsa.statespace.mlemodel.MLEModel.set_stability_method statsmodels.tsa.statespace.mlemodel.MLEModel.set\_stability\_method =================================================================== `MLEModel.set_stability_method(stability_method=None, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEModel.set_stability_method) Set the numerical stability method The Kalman filter is a recursive algorithm that may in some cases suffer issues with numerical stability. The stability method controls what, if any, measures are taken to promote stability. | Parameters: | * **stability\_method** (*integer**,* *optional*) – Bitmask value to set the stability method to. See notes for details. * **\*\*kwargs** – Keyword arguments may be used to influence the stability method by setting individual boolean flags. See notes for details. | #### Notes This method is rarely used. See the corresponding function in the `KalmanFilter` class for details. statsmodels statsmodels.sandbox.distributions.transformed.squaretg statsmodels.sandbox.distributions.transformed.squaretg ====================================================== `statsmodels.sandbox.distributions.transformed.squaretg = <statsmodels.sandbox.distributions.transformed.TransfTwo_gen object>` Distribution based on a non-monotonic (u- or hump-shaped transformation) the constructor can be called with a distribution class, and functions that define the non-linear transformation. and generates the distribution of the transformed random variable Note: the transformation, it’s inverse and derivatives need to be fully specified: func, funcinvplus, funcinvminus, derivplus, derivminus. Currently no numerical derivatives or inverse are calculated This can be used to generate distribution instances similar to the distributions in scipy.stats. statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.get_robustcov_results statsmodels.sandbox.regression.gmm.IVRegressionResults.get\_robustcov\_results ============================================================================== `IVRegressionResults.get_robustcov_results(cov_type='HC1', use_t=None, **kwds)` create new results instance with robust covariance as default | Parameters: | * **cov\_type** (*string*) – the type of robust sandwich estimator to use. see Notes below * **use\_t** (*bool*) – If true, then the t distribution is used for inference. If false, then the normal distribution is used. If `use_t` is None, then an appropriate default is used, which is `true` if the cov\_type is nonrobust, and `false` in all other cases. * **kwds** (*depends on cov\_type*) – Required or optional arguments for robust covariance calculation. see Notes below | | Returns: | **results** – This method creates a new results instance with the requested robust covariance as the default covariance of the parameters. Inferential statistics like p-values and hypothesis tests will be based on this covariance matrix. | | Return type: | results instance | #### Notes The following covariance types and required or optional arguments are currently available: * ‘fixed scale’ and optional keyword argument ‘scale’ which uses a predefined scale estimate with default equal to one. * ‘HC0’, ‘HC1’, ‘HC2’, ‘HC3’ and no keyword arguments: heteroscedasticity robust covariance * ‘HAC’ and keywords + `maxlag` integer (required) : number of lags to use + `kernel callable or str (optional) : kernel` currently available kernels are [‘bartlett’, ‘uniform’], default is Bartlett + `use_correction bool (optional) : If true, use small sample` correction * ‘cluster’ and required keyword `groups`, integer group indicator + `groups array_like, integer (required) :` index of clusters or groups + `use_correction bool (optional) :` If True the sandwich covariance is calculated with a small sample correction. If False the sandwich covariance is calculated without small sample correction. + `df_correction bool (optional)` If True (default), then the degrees of freedom for the inferential statistics and hypothesis tests, such as pvalues, f\_pvalue, conf\_int, and t\_test and f\_test, are based on the number of groups minus one instead of the total number of observations minus the number of explanatory variables. `df_resid` of the results instance is adjusted. If False, then `df_resid` of the results instance is not adjusted. * ‘hac-groupsum’ Driscoll and Kraay, heteroscedasticity and autocorrelation robust standard errors in panel data keywords + `time` array\_like (required) : index of time periods + `maxlag` integer (required) : number of lags to use + `kernel callable or str (optional) : kernel` currently available kernels are [‘bartlett’, ‘uniform’], default is Bartlett + `use_correction False or string in [‘hac’, ‘cluster’] (optional) :` If False the the sandwich covariance is calulated without small sample correction. If `use_correction = ‘cluster’` (default), then the same small sample correction as in the case of ‘covtype=’cluster’’ is used. + `df_correction bool (optional)` adjustment to df\_resid, see cov\_type ‘cluster’ above # TODO: we need more options here * ‘hac-panel’ heteroscedasticity and autocorrelation robust standard errors in panel data. The data needs to be sorted in this case, the time series for each panel unit or cluster need to be stacked. The membership to a timeseries of an individual or group can be either specified by group indicators or by increasing time periods. keywords + either `groups` or `time` : array\_like (required) `groups` : indicator for groups `time` : index of time periods + `maxlag` integer (required) : number of lags to use + `kernel callable or str (optional) : kernel` currently available kernels are [‘bartlett’, ‘uniform’], default is Bartlett + `use_correction False or string in [‘hac’, ‘cluster’] (optional) :` If False the sandwich covariance is calculated without small sample correction. + `df_correction bool (optional)` adjustment to df\_resid, see cov\_type ‘cluster’ above # TODO: we need more options here Reminder: `use_correction` in “hac-groupsum” and “hac-panel” is not bool, needs to be in [False, ‘hac’, ‘cluster’] TODO: Currently there is no check for extra or misspelled keywords, except in the case of cov\_type `HCx` statsmodels statsmodels.stats.inter_rater.fleiss_kappa statsmodels.stats.inter\_rater.fleiss\_kappa ============================================ `statsmodels.stats.inter_rater.fleiss_kappa(table, method='fleiss')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/inter_rater.html#fleiss_kappa) Fleiss’ and Randolph’s kappa multi-rater agreement measure | Parameters: | * **table** (*array\_like**,* *2-D*) – assumes subjects in rows, and categories in columns * **method** (*string*) – Method ‘fleiss’ returns Fleiss’ kappa which uses the sample margin to define the chance outcome. Method ‘randolph’ or ‘uniform’ (only first 4 letters are needed) returns Randolph’s (2005) multirater kappa which assumes a uniform distribution of the categories to define the chance outcome. | | Returns: | **kappa** – Fleiss’s or Randolph’s kappa statistic for inter rater agreement | | Return type: | float | #### Notes no variance or hypothesis tests yet Interrater agreement measures like Fleiss’s kappa measure agreement relative to chance agreement. Different authors have proposed ways of defining these chance agreements. Fleiss’ is based on the marginal sample distribution of categories, while Randolph uses a uniform distribution of categories as benchmark. Warrens (2010) showed that Randolph’s kappa is always larger or equal to Fleiss’ kappa. Under some commonly observed condition, Fleiss’ and Randolph’s kappa provide lower and upper bounds for two similar kappa\_like measures by Light (1971) and Hubert (1977). #### References Wikipedia <http://en.wikipedia.org/wiki/Fleiss%27_kappa> Fleiss, Joseph L. 1971. “Measuring Nominal Scale Agreement among Many Raters.” Psychological Bulletin 76 (5): 378-82. <https://doi.org/10.1037/h0031619>. Randolph, Justus J. 2005 “Free-Marginal Multirater Kappa (multirater K [free]): An Alternative to Fleiss’ Fixed-Marginal Multirater Kappa.” Presented at the Joensuu Learning and Instruction Symposium, vol. 2005 <https://eric.ed.gov/?id=ED490661> Warrens, Matthijs J. 2010. “Inequalities between Multi-Rater Kappas.” Advances in Data Analysis and Classification 4 (4): 271-86. <https://doi.org/10.1007/s11634-010-0073-4>. statsmodels statsmodels.stats.weightstats.CompareMeans.summary statsmodels.stats.weightstats.CompareMeans.summary ================================================== `CompareMeans.summary(use_t=True, alpha=0.05, usevar='pooled', value=0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/weightstats.html#CompareMeans.summary) summarize the results of the hypothesis test | Parameters: | * **use\_t** (*bool**,* *optional*) – if use\_t is True, then t test results are returned if use\_t is False, then z test results are returned * **alpha** (*float*) – significance level for the confidence interval, coverage is `1-alpha` * **usevar** (*string**,* *'pooled'* *or* *'unequal'*) – If `pooled`, then the standard deviation of the samples is assumed to be the same. If `unequal`, then the variance of Welsh ttest will be used, and the degrees of freedom are those of Satterthwaite if `use_t` is True. * **value** (*float*) – difference between the means under the Null hypothesis. | | Returns: | **smry** | | Return type: | [SimpleTable](statsmodels.iolib.table.simpletable#statsmodels.iolib.table.SimpleTable "statsmodels.iolib.table.SimpleTable") | statsmodels statsmodels.tsa.regime_switching.markov_regression.MarkovRegression statsmodels.tsa.regime\_switching.markov\_regression.MarkovRegression ===================================================================== `class statsmodels.tsa.regime_switching.markov_regression.MarkovRegression(endog, k_regimes, trend='c', exog=None, order=0, exog_tvtp=None, switching_trend=True, switching_exog=True, switching_variance=False, dates=None, freq=None, missing='none')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/regime_switching/markov_regression.html#MarkovRegression) First-order k-regime Markov switching regression model | Parameters: | * **endog** (*array\_like*) – The endogenous variable. * **k\_regimes** (*integer*) – The number of regimes. * **trend** (*{'nc'**,* *'c'**,* *'t'**,* *'ct'}*) – Whether or not to include a trend. To include an intercept, time trend, or both, set `trend=’c’`, `trend=’t’`, or `trend=’ct’`. For no trend, set `trend=’nc’`. Default is an intercept. * **exog** (*array\_like**,* *optional*) – Array of exogenous regressors, shaped nobs x k. * **order** (*integer**,* *optional*) – The order of the model describes the dependence of the likelihood on previous regimes. This depends on the model in question and should be set appropriately by subclasses. * **exog\_tvtp** (*array\_like**,* *optional*) – Array of exogenous or lagged variables to use in calculating time-varying transition probabilities (TVTP). TVTP is only used if this variable is provided. If an intercept is desired, a column of ones must be explicitly included in this array. * **switching\_trend** (*boolean* *or* *iterable**,* *optional*) – If a boolean, sets whether or not all trend coefficients are switching across regimes. If an iterable, should be of length equal to the number of trend variables, where each element is a boolean describing whether the corresponding coefficient is switching. Default is True. * **switching\_exog** (*boolean* *or* *iterable**,* *optional*) – If a boolean, sets whether or not all regression coefficients are switching across regimes. If an iterable, should be of length equal to the number of exogenous variables, where each element is a boolean describing whether the corresponding coefficient is switching. Default is True. * **switching\_variance** (*boolean**,* *optional*) – Whether or not there is regime-specific heteroskedasticity, i.e. whether or not the error term has a switching variance. Default is False. | #### Notes This model is new and API stability is not guaranteed, although changes will be made in a backwards compatible way if possible. The model can be written as: \[\begin{split}y\_t = a\_{S\_t} + x\_t' \beta\_{S\_t} + \varepsilon\_t \\ \varepsilon\_t \sim N(0, \sigma\_{S\_t}^2)\end{split}\] i.e. the model is a dynamic linear regression where the coefficients and the variance of the error term may be switching across regimes. The `trend` is accomodated by prepending columns to the `exog` array. Thus if `trend=’c’`, the passed `exog` array should not already have a column of ones. #### References Kim, Chang-Jin, and Charles R. Nelson. 1999. “State-Space Models with Regime Switching: Classical and Gibbs-Sampling Approaches with Applications”. MIT Press Books. The MIT Press. #### Methods | | | | --- | --- | | [`filter`](statsmodels.tsa.regime_switching.markov_regression.markovregression.filter#statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.filter "statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.filter")(params[, transformed, cov\_type, …]) | Apply the Hamilton filter | | [`fit`](statsmodels.tsa.regime_switching.markov_regression.markovregression.fit#statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.fit "statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.fit")([start\_params, transformed, cov\_type, …]) | Fits the model by maximum likelihood via Hamilton filter. | | [`from_formula`](statsmodels.tsa.regime_switching.markov_regression.markovregression.from_formula#statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.from_formula "statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.from_formula")(formula, data[, subset, drop\_cols]) | Create a Model from a formula and dataframe. | | [`hessian`](statsmodels.tsa.regime_switching.markov_regression.markovregression.hessian#statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.hessian "statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.hessian")(params[, transformed]) | Hessian matrix of the likelihood function, evaluated at the given parameters | | [`information`](statsmodels.tsa.regime_switching.markov_regression.markovregression.information#statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.information "statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.information")(params) | Fisher information matrix of model | | [`initial_probabilities`](statsmodels.tsa.regime_switching.markov_regression.markovregression.initial_probabilities#statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.initial_probabilities "statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.initial_probabilities")(params[, …]) | Retrieve initial probabilities | | [`initialize`](statsmodels.tsa.regime_switching.markov_regression.markovregression.initialize#statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.initialize "statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.initialize")() | Initialize (possibly re-initialize) a Model instance. | | [`initialize_known`](statsmodels.tsa.regime_switching.markov_regression.markovregression.initialize_known#statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.initialize_known "statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.initialize_known")(probabilities[, tol]) | Set initialization of regime probabilities to use known values | | [`initialize_steady_state`](statsmodels.tsa.regime_switching.markov_regression.markovregression.initialize_steady_state#statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.initialize_steady_state "statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.initialize_steady_state")() | Set initialization of regime probabilities to be steady-state values | | [`loglike`](statsmodels.tsa.regime_switching.markov_regression.markovregression.loglike#statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.loglike "statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.loglike")(params[, transformed]) | Loglikelihood evaluation | | [`loglikeobs`](statsmodels.tsa.regime_switching.markov_regression.markovregression.loglikeobs#statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.loglikeobs "statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.loglikeobs")(params[, transformed]) | Loglikelihood evaluation for each period | | [`predict`](statsmodels.tsa.regime_switching.markov_regression.markovregression.predict#statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.predict "statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.predict")(params[, start, end, probabilities, …]) | In-sample prediction and out-of-sample forecasting | | [`predict_conditional`](statsmodels.tsa.regime_switching.markov_regression.markovregression.predict_conditional#statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.predict_conditional "statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.predict_conditional")(params) | In-sample prediction, conditional on the current regime | | [`regime_transition_matrix`](statsmodels.tsa.regime_switching.markov_regression.markovregression.regime_transition_matrix#statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.regime_transition_matrix "statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.regime_transition_matrix")(params[, exog\_tvtp]) | Construct the left-stochastic transition matrix | | [`score`](statsmodels.tsa.regime_switching.markov_regression.markovregression.score#statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.score "statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.score")(params[, transformed]) | Compute the score function at params. | | [`score_obs`](statsmodels.tsa.regime_switching.markov_regression.markovregression.score_obs#statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.score_obs "statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.score_obs")(params[, transformed]) | Compute the score per observation, evaluated at params | | [`smooth`](statsmodels.tsa.regime_switching.markov_regression.markovregression.smooth#statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.smooth "statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.smooth")(params[, transformed, cov\_type, …]) | Apply the Kim smoother and Hamilton filter | | [`transform_params`](statsmodels.tsa.regime_switching.markov_regression.markovregression.transform_params#statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.transform_params "statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.transform_params")(unconstrained) | Transform unconstrained parameters used by the optimizer to constrained parameters used in likelihood evaluation | | [`untransform_params`](statsmodels.tsa.regime_switching.markov_regression.markovregression.untransform_params#statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.untransform_params "statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.untransform_params")(constrained) | Transform constrained parameters used in likelihood evaluation to unconstrained parameters used by the optimizer | #### Attributes | | | | --- | --- | | `endog_names` | Names of endogenous variables | | `exog_names` | | | `k_params` | (int) Number of parameters in the model | | `param_names` | (list of str) List of human readable parameter names (for parameters actually included in the model). | | `start_params` | (array) Starting parameters for maximum likelihood estimation. |
programming_docs
statsmodels statsmodels.stats.anova.AnovaRM.fit statsmodels.stats.anova.AnovaRM.fit =================================== `AnovaRM.fit()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/anova.html#AnovaRM.fit) estimate the model and compute the Anova table | Returns: | | | Return type: | AnovaResults instance | statsmodels statsmodels.stats.diagnostic.HetGoldfeldQuandt statsmodels.stats.diagnostic.HetGoldfeldQuandt ============================================== `class statsmodels.stats.diagnostic.HetGoldfeldQuandt` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/diagnostic.html#HetGoldfeldQuandt) test whether variance is the same in 2 subsamples | Parameters: | * **y** (*array\_like*) – endogenous variable * **x** (*array\_like*) – exogenous variable, regressors * **idx** (*integer*) – column index of variable according to which observations are sorted for the split * **split** (*None* *or* *integer* *or* *float in intervall* *(**0**,**1**)*) – index at which sample is split. If 0<split<1 then split is interpreted as fraction of the observations in the first sample * **drop** (*None**,* *float* *or* *int*) – If this is not None, then observation are dropped from the middle part of the sorted series. If 0<split<1 then split is interpreted as fraction of the number of observations to be dropped. Note: Currently, observations are dropped between split and split+drop, where split and drop are the indices (given by rounding if specified as fraction). The first sample is [0:split], the second sample is [split+drop:] * **alternative** (*string**,* *'increasing'**,* *'decreasing'* *or* *'two-sided'*) – default is increasing. This specifies the alternative for the p-value calculation. | | Returns: | * *(fval, pval) or res* * **fval** (*float*) – value of the F-statistic * **pval** (*float*) – p-value of the hypothesis that the variance in one subsample is larger than in the other subsample * **res** (*instance of result class*) – The class instance is just a storage for the intermediate and final results that are calculated | #### Notes The Null hypothesis is that the variance in the two sub-samples are the same. The alternative hypothesis, can be increasing, i.e. the variance in the second sample is larger than in the first, or decreasing or two-sided. Results are identical R, but the drop option is defined differently. (sorting by idx not tested yet) #### Methods | | | | --- | --- | | [`run`](statsmodels.stats.diagnostic.hetgoldfeldquandt.run#statsmodels.stats.diagnostic.HetGoldfeldQuandt.run "statsmodels.stats.diagnostic.HetGoldfeldQuandt.run")(y, x[, idx, split, drop, alternative, …]) | see class docstring | statsmodels statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialResults.resid statsmodels.discrete.count\_model.ZeroInflatedNegativeBinomialResults.resid =========================================================================== `ZeroInflatedNegativeBinomialResults.resid()` Residuals #### Notes The residuals for Count models are defined as \[y - p\] where \(p = \exp(X\beta)\). Any exposure and offset variables are also handled. statsmodels statsmodels.tsa.vector_ar.var_model.LagOrderResults statsmodels.tsa.vector\_ar.var\_model.LagOrderResults ===================================================== `class statsmodels.tsa.vector_ar.var_model.LagOrderResults(ics, selected_orders, vecm=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/var_model.html#LagOrderResults) Results class for choosing a model’s lag order. | Parameters: | * **ics** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")) – The keys are the strings `"aic"`, `"bic"`, `"hqic"`, and `"fpe"`. A corresponding value is a list of information criteria for various numbers of lags. * **selected\_orders** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")) – The keys are the strings `"aic"`, `"bic"`, `"hqic"`, and `"fpe"`. The corresponding value is an integer specifying the number of lags chosen according to a given criterion (key). * **vecm** (bool, default: `False`) – `True` indicates that the model is a VECM. In case of a VAR model this argument must be `False`. | #### Notes In case of a VECM the shown lags are lagged differences. #### Methods | | | | --- | --- | | [`summary`](statsmodels.tsa.vector_ar.var_model.lagorderresults.summary#statsmodels.tsa.vector_ar.var_model.LagOrderResults.summary "statsmodels.tsa.vector_ar.var_model.LagOrderResults.summary")() | | statsmodels statsmodels.sandbox.distributions.extras.SkewNorm2_gen.mean statsmodels.sandbox.distributions.extras.SkewNorm2\_gen.mean ============================================================ `SkewNorm2_gen.mean(*args, **kwds)` Mean of the distribution. | Parameters: | * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **mean** – the mean of the distribution | | Return type: | float | statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.cov_params_oim statsmodels.tsa.statespace.dynamic\_factor.DynamicFactorResults.cov\_params\_oim ================================================================================ `DynamicFactorResults.cov_params_oim()` (array) The variance / covariance matrix. Computed using the method from Harvey (1989). statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.cov_params_robust statsmodels.tsa.statespace.dynamic\_factor.DynamicFactorResults.cov\_params\_robust =================================================================================== `DynamicFactorResults.cov_params_robust()` (array) The QMLE variance / covariance matrix. Alias for `cov_params_robust_oim` statsmodels statsmodels.tsa.statespace.structural.UnobservedComponentsResults.llf statsmodels.tsa.statespace.structural.UnobservedComponentsResults.llf ===================================================================== `UnobservedComponentsResults.llf()` (float) The value of the log-likelihood function evaluated at `params`. statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.simulate statsmodels.tsa.statespace.dynamic\_factor.DynamicFactorResults.simulate ======================================================================== `DynamicFactorResults.simulate(nsimulations, measurement_shocks=None, state_shocks=None, initial_state=None)` Simulate a new time series following the state space model | Parameters: | * **nsimulations** (*int*) – The number of observations to simulate. If the model is time-invariant this can be any number. If the model is time-varying, then this number must be less than or equal to the number * **measurement\_shocks** (*array\_like**,* *optional*) – If specified, these are the shocks to the measurement equation, \(\varepsilon\_t\). If unspecified, these are automatically generated using a pseudo-random number generator. If specified, must be shaped `nsimulations` x `k_endog`, where `k_endog` is the same as in the state space model. * **state\_shocks** (*array\_like**,* *optional*) – If specified, these are the shocks to the state equation, \(\eta\_t\). If unspecified, these are automatically generated using a pseudo-random number generator. If specified, must be shaped `nsimulations` x `k_posdef` where `k_posdef` is the same as in the state space model. * **initial\_state** (*array\_like**,* *optional*) – If specified, this is the state vector at time zero, which should be shaped (`k_states` x 1), where `k_states` is the same as in the state space model. If unspecified, but the model has been initialized, then that initialization is used. If unspecified and the model has not been initialized, then a vector of zeros is used. Note that this is not included in the returned `simulated_states` array. | | Returns: | **simulated\_obs** – An (nsimulations x k\_endog) array of simulated observations. | | Return type: | array | statsmodels statsmodels.sandbox.distributions.transformed.invdnormalg statsmodels.sandbox.distributions.transformed.invdnormalg ========================================================= `statsmodels.sandbox.distributions.transformed.invdnormalg = <statsmodels.sandbox.distributions.transformed.Transf_gen object>` a class for non-linear monotonic transformation of a continuous random variable statsmodels statsmodels.tsa.statespace.varmax.VARMAX.set_smoother_output statsmodels.tsa.statespace.varmax.VARMAX.set\_smoother\_output ============================================================== `VARMAX.set_smoother_output(smoother_output=None, **kwargs)` Set the smoother output The smoother can produce several types of results. The smoother output variable controls which are calculated and returned. | Parameters: | * **smoother\_output** (*integer**,* *optional*) – Bitmask value to set the smoother output to. See notes for details. * **\*\*kwargs** – Keyword arguments may be used to influence the smoother output by setting individual boolean flags. | #### Notes This method is rarely used. See the corresponding function in the `KalmanSmoother` class for details. statsmodels statsmodels.discrete.discrete_model.ProbitResults.bse statsmodels.discrete.discrete\_model.ProbitResults.bse ====================================================== `ProbitResults.bse()` statsmodels statsmodels.discrete.discrete_model.MNLogit.cov_params_func_l1 statsmodels.discrete.discrete\_model.MNLogit.cov\_params\_func\_l1 ================================================================== `MNLogit.cov_params_func_l1(likelihood_model, xopt, retvals)` Computes cov\_params on a reduced parameter space corresponding to the nonzero parameters resulting from the l1 regularized fit. Returns a full cov\_params matrix, with entries corresponding to zero’d values set to np.nan. statsmodels statsmodels.sandbox.regression.gmm.IV2SLS.hessian statsmodels.sandbox.regression.gmm.IV2SLS.hessian ================================================= `IV2SLS.hessian(params)` The Hessian matrix of the model statsmodels statsmodels.tsa.ar_model.ARResults.remove_data statsmodels.tsa.ar\_model.ARResults.remove\_data ================================================ `ARResults.remove_data()` remove data arrays, all nobs arrays from result and model This reduces the size of the instance, so it can be pickled with less memory. Currently tested for use with predict from an unpickled results and model instance. Warning Since data and some intermediate results have been removed calculating new statistics that require them will raise exceptions. The exception will occur the first time an attribute is accessed that has been set to None. Not fully tested for time series models, tsa, and might delete too much for prediction or not all that would be possible. The lists of arrays to delete are maintained as attributes of the result and model instance, except for cached values. These lists could be changed before calling remove\_data. The attributes to remove are named in: `model._data_attr : arrays attached to both the model instance` and the results instance with the same attribute name. `result.data_in_cache : arrays that may exist as values in` result.\_cache (TODO : should privatize name) `result._data_attr_model : arrays attached to the model` instance but not to the results instance statsmodels statsmodels.genmod.families.links.Log.deriv2 statsmodels.genmod.families.links.Log.deriv2 ============================================ `Log.deriv2(p)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/links.html#Log.deriv2) Second derivative of the log transform link function | Parameters: | **p** (*array-like*) – Mean parameters | | Returns: | **g’‘(p)** – Second derivative of log transform of x | | Return type: | array | #### Notes g’‘(x) = -1/x^2 statsmodels statsmodels.sandbox.distributions.extras.ACSkewT_gen.entropy statsmodels.sandbox.distributions.extras.ACSkewT\_gen.entropy ============================================================= `ACSkewT_gen.entropy(*args, **kwds)` Differential entropy of the RV. | Parameters: | * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information). * **loc** (*array\_like**,* *optional*) – Location parameter (default=0). * **scale** (*array\_like**,* *optional* *(**continuous distributions only**)*) – Scale parameter (default=1). | #### Notes Entropy is defined base `e`: ``` >>> drv = rv_discrete(values=((0, 1), (0.5, 0.5))) >>> np.allclose(drv.entropy(), np.log(2.0)) True ``` statsmodels statsmodels.discrete.discrete_model.Probit.cdf statsmodels.discrete.discrete\_model.Probit.cdf =============================================== `Probit.cdf(X)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#Probit.cdf) Probit (Normal) cumulative distribution function | Parameters: | **X** (*array-like*) – The linear predictor of the model (XB). | | Returns: | **cdf** – The cdf evaluated at `X`. | | Return type: | ndarray | #### Notes This function is just an alias for scipy.stats.norm.cdf statsmodels statsmodels.stats.diagnostic.compare_j statsmodels.stats.diagnostic.compare\_j ======================================= `statsmodels.stats.diagnostic.compare_j = <statsmodels.sandbox.stats.diagnostic.CompareJ object>` J-Test for comparing non-nested models | Parameters: | * **results\_x** (*Result instance*) – result instance of first model * **results\_z** (*Result instance*) – result instance of second model * **attach** (*bool*) – | From description in Greene, section 8.3.3 produces correct results for Example 8.3, Greene - not checked yet #currently an exception, but I don’t have clean reload in python session check what results should be attached statsmodels statsmodels.sandbox.distributions.transformed.TransfTwo_gen.nnlf statsmodels.sandbox.distributions.transformed.TransfTwo\_gen.nnlf ================================================================= `TransfTwo_gen.nnlf(theta, x)` Return negative loglikelihood function. #### Notes This is `-sum(log pdf(x, theta), axis=0)` where `theta` are the parameters (including loc and scale). statsmodels statsmodels.sandbox.regression.gmm.IVGMM.momcond statsmodels.sandbox.regression.gmm.IVGMM.momcond ================================================ `IVGMM.momcond(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#IVGMM.momcond) statsmodels statsmodels.genmod.generalized_estimating_equations.GEEResults.plot_ceres_residuals statsmodels.genmod.generalized\_estimating\_equations.GEEResults.plot\_ceres\_residuals ======================================================================================= `GEEResults.plot_ceres_residuals(focus_exog, frac=0.66, cond_means=None, ax=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_estimating_equations.html#GEEResults.plot_ceres_residuals) Produces a CERES (Conditional Expectation Partial Residuals) plot for a fitted regression model. | Parameters: | * **focus\_exog** (*integer* *or* *string*) – The column index of results.model.exog, or the variable name, indicating the variable whose role in the regression is to be assessed. * **frac** (*float*) – Lowess tuning parameter for the adjusted model used in the CERES analysis. Not used if `cond_means` is provided. * **cond\_means** (*array-like**,* *optional*) – If provided, the columns of this array span the space of the conditional means E[exog | focus exog], where exog ranges over some or all of the columns of exog (other than the focus exog). * **ax** (*matplotlib.Axes instance**,* *optional*) – The axes on which to draw the plot. If not provided, a new axes instance is created. | | Returns: | **fig** – The figure on which the partial residual plot is drawn. | | Return type: | matplotlib.Figure instance | #### References RD Cook and R Croos-Dabrera (1998). Partial residual plots in generalized linear models. Journal of the American Statistical Association, 93:442. RD Cook (1993). Partial residual plots. Technometrics 35:4. #### Notes `cond_means` is intended to capture the behavior of E[x1 | x2], where x2 is the focus exog and x1 are all the other exog variables. If all the conditional mean relationships are linear, it is sufficient to set cond\_means equal to the focus exog. Alternatively, cond\_means may consist of one or more columns containing functional transformations of the focus exog (e.g. x2^2) that are thought to capture E[x1 | x2]. If nothing is known or suspected about the form of E[x1 | x2], set `cond_means` to None, and it will be estimated by smoothing each non-focus exog against the focus exog. The values of `frac` control these lowess smooths. If cond\_means contains only the focus exog, the results are equivalent to a partial residual plot. If the focus variable is believed to be independent of the other exog variables, `cond_means` can be set to an (empty) nx0 array. statsmodels statsmodels.stats.contingency_tables.Table.test_ordinal_association statsmodels.stats.contingency\_tables.Table.test\_ordinal\_association ====================================================================== `Table.test_ordinal_association(row_scores=None, col_scores=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table.test_ordinal_association) Assess independence between two ordinal variables. This is the ‘linear by linear’ association test, which uses weights or scores to target the test to have more power against ordered alternatives. | Parameters: | * **row\_scores** (*array-like*) – An array of numeric row scores * **col\_scores** (*array-like*) – An array of numeric column scores | | Returns: | * *A bunch with the following attributes* * **statistic** (*float*) – The test statistic. * **null\_mean** (*float*) – The expected value of the test statistic under the null hypothesis. * **null\_sd** (*float*) – The standard deviation of the test statistic under the null hypothesis. * **zscore** (*float*) – The Z-score for the test statistic. * **pvalue** (*float*) – The p-value for the test. | #### Notes The scores define the trend to which the test is most sensitive. Using the default row and column scores gives the Cochran-Armitage trend test. statsmodels statsmodels.tsa.arima_model.ARIMAResults.llf statsmodels.tsa.arima\_model.ARIMAResults.llf ============================================= `ARIMAResults.llf()` statsmodels statsmodels.regression.recursive_ls.RecursiveLSResults.get_prediction statsmodels.regression.recursive\_ls.RecursiveLSResults.get\_prediction ======================================================================= `RecursiveLSResults.get_prediction(start=None, end=None, dynamic=False, index=None, **kwargs)` In-sample prediction and out-of-sample forecasting | Parameters: | * **start** (*int**,* *str**, or* *datetime**,* *optional*) – Zero-indexed observation number at which to start forecasting, i.e., the first forecast is start. Can also be a date string to parse or a datetime type. Default is the the zeroth observation. * **end** (*int**,* *str**, or* *datetime**,* *optional*) – Zero-indexed observation number at which to end forecasting, i.e., the last forecast is end. Can also be a date string to parse or a datetime type. However, if the dates index does not have a fixed frequency, end must be an integer index if you want out of sample prediction. Default is the last observation in the sample. * **dynamic** (*boolean**,* *int**,* *str**, or* *datetime**,* *optional*) – Integer offset relative to `start` at which to begin dynamic prediction. Can also be an absolute date string to parse or a datetime type (these are not interpreted as offsets). Prior to this observation, true endogenous values will be used for prediction; starting with this observation and continuing through the end of prediction, forecasted endogenous values will be used instead. * **\*\*kwargs** – Additional arguments may required for forecasting beyond the end of the sample. See `FilterResults.predict` for more details. | | Returns: | **forecast** – Array of out of in-sample predictions and / or out-of-sample forecasts. An (npredict x k\_endog) array. | | Return type: | array |
programming_docs
statsmodels statsmodels.multivariate.factor.FactorResults.load_stderr statsmodels.multivariate.factor.FactorResults.load\_stderr ========================================================== `FactorResults.load_stderr()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/multivariate/factor.html#FactorResults.load_stderr) The standard errors of the loadings. Standard errors are only available if the model was fit using maximum likelihood. If `endog` is not provided, `nobs` must be provided to obtain standard errors. These are asymptotic standard errors. See Bai and Li (2012) for conditions under which the standard errors are valid. The standard errors are only applicable to the original, unrotated maximum likelihood solution. statsmodels statsmodels.tsa.vector_ar.irf.IRAnalysis statsmodels.tsa.vector\_ar.irf.IRAnalysis ========================================= `class statsmodels.tsa.vector_ar.irf.IRAnalysis(model, P=None, periods=10, order=None, svar=False, vecm=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/irf.html#IRAnalysis) Impulse response analysis class. Computes impulse responses, asymptotic standard errors, and produces relevant plots | Parameters: | **model** (*VAR instance*) – | #### Notes Using Lütkepohl (2005) notation #### Methods | | | | --- | --- | | [`G`](statsmodels.tsa.vector_ar.irf.iranalysis.g#statsmodels.tsa.vector_ar.irf.IRAnalysis.G "statsmodels.tsa.vector_ar.irf.IRAnalysis.G")() | | | [`H`](statsmodels.tsa.vector_ar.irf.iranalysis.h#statsmodels.tsa.vector_ar.irf.IRAnalysis.H "statsmodels.tsa.vector_ar.irf.IRAnalysis.H")() | | | [`cov`](statsmodels.tsa.vector_ar.irf.iranalysis.cov#statsmodels.tsa.vector_ar.irf.IRAnalysis.cov "statsmodels.tsa.vector_ar.irf.IRAnalysis.cov")([orth]) | Compute asymptotic standard errors for impulse response coefficients | | [`cum_effect_cov`](statsmodels.tsa.vector_ar.irf.iranalysis.cum_effect_cov#statsmodels.tsa.vector_ar.irf.IRAnalysis.cum_effect_cov "statsmodels.tsa.vector_ar.irf.IRAnalysis.cum_effect_cov")([orth]) | Compute asymptotic standard errors for cumulative impulse response coefficients | | [`cum_effect_stderr`](statsmodels.tsa.vector_ar.irf.iranalysis.cum_effect_stderr#statsmodels.tsa.vector_ar.irf.IRAnalysis.cum_effect_stderr "statsmodels.tsa.vector_ar.irf.IRAnalysis.cum_effect_stderr")([orth]) | | | [`cum_errband_mc`](statsmodels.tsa.vector_ar.irf.iranalysis.cum_errband_mc#statsmodels.tsa.vector_ar.irf.IRAnalysis.cum_errband_mc "statsmodels.tsa.vector_ar.irf.IRAnalysis.cum_errband_mc")([orth, repl, signif, seed, burn]) | IRF Monte Carlo integrated error bands of cumulative effect | | [`err_band_sz1`](statsmodels.tsa.vector_ar.irf.iranalysis.err_band_sz1#statsmodels.tsa.vector_ar.irf.IRAnalysis.err_band_sz1 "statsmodels.tsa.vector_ar.irf.IRAnalysis.err_band_sz1")([orth, svar, repl, signif, …]) | IRF Sims-Zha error band method 1. | | [`err_band_sz2`](statsmodels.tsa.vector_ar.irf.iranalysis.err_band_sz2#statsmodels.tsa.vector_ar.irf.IRAnalysis.err_band_sz2 "statsmodels.tsa.vector_ar.irf.IRAnalysis.err_band_sz2")([orth, svar, repl, signif, …]) | IRF Sims-Zha error band method 2. | | [`err_band_sz3`](statsmodels.tsa.vector_ar.irf.iranalysis.err_band_sz3#statsmodels.tsa.vector_ar.irf.IRAnalysis.err_band_sz3 "statsmodels.tsa.vector_ar.irf.IRAnalysis.err_band_sz3")([orth, svar, repl, signif, …]) | IRF Sims-Zha error band method 3. | | [`errband_mc`](statsmodels.tsa.vector_ar.irf.iranalysis.errband_mc#statsmodels.tsa.vector_ar.irf.IRAnalysis.errband_mc "statsmodels.tsa.vector_ar.irf.IRAnalysis.errband_mc")([orth, svar, repl, signif, seed, …]) | IRF Monte Carlo integrated error bands | | [`fevd_table`](statsmodels.tsa.vector_ar.irf.iranalysis.fevd_table#statsmodels.tsa.vector_ar.irf.IRAnalysis.fevd_table "statsmodels.tsa.vector_ar.irf.IRAnalysis.fevd_table")() | | | [`lr_effect_cov`](statsmodels.tsa.vector_ar.irf.iranalysis.lr_effect_cov#statsmodels.tsa.vector_ar.irf.IRAnalysis.lr_effect_cov "statsmodels.tsa.vector_ar.irf.IRAnalysis.lr_effect_cov")([orth]) | | | [`lr_effect_stderr`](statsmodels.tsa.vector_ar.irf.iranalysis.lr_effect_stderr#statsmodels.tsa.vector_ar.irf.IRAnalysis.lr_effect_stderr "statsmodels.tsa.vector_ar.irf.IRAnalysis.lr_effect_stderr")([orth]) | | | [`plot`](statsmodels.tsa.vector_ar.irf.iranalysis.plot#statsmodels.tsa.vector_ar.irf.IRAnalysis.plot "statsmodels.tsa.vector_ar.irf.IRAnalysis.plot")([orth, impulse, response, signif, …]) | Plot impulse responses | | [`plot_cum_effects`](statsmodels.tsa.vector_ar.irf.iranalysis.plot_cum_effects#statsmodels.tsa.vector_ar.irf.IRAnalysis.plot_cum_effects "statsmodels.tsa.vector_ar.irf.IRAnalysis.plot_cum_effects")([orth, impulse, response, …]) | Plot cumulative impulse response functions | | [`stderr`](statsmodels.tsa.vector_ar.irf.iranalysis.stderr#statsmodels.tsa.vector_ar.irf.IRAnalysis.stderr "statsmodels.tsa.vector_ar.irf.IRAnalysis.stderr")([orth]) | | statsmodels statsmodels.robust.robust_linear_model.RLMResults.weights statsmodels.robust.robust\_linear\_model.RLMResults.weights =========================================================== `RLMResults.weights()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/robust_linear_model.html#RLMResults.weights) statsmodels statsmodels.tsa.statespace.varmax.VARMAX.information statsmodels.tsa.statespace.varmax.VARMAX.information ==================================================== `VARMAX.information(params)` Fisher information matrix of model Returns -Hessian of loglike evaluated at params. statsmodels statsmodels.genmod.generalized_linear_model.GLMResults.t_test statsmodels.genmod.generalized\_linear\_model.GLMResults.t\_test ================================================================ `GLMResults.t_test(r_matrix, cov_p=None, scale=None, use_t=None)` Compute a t-test for a each linear hypothesis of the form Rb = q | Parameters: | * **r\_matrix** (*array-like**,* *str**,* *tuple*) – + array : If an array is given, a p x k 2d array or length k 1d array specifying the linear restrictions. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q). If q is given, can be either a scalar or a length p row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – An optional `scale` to use. Default is the scale specified by the model fit. * **use\_t** (*bool**,* *optional*) – If use\_t is None, then the default of the model is used. If use\_t is True, then the p-values are based on the t distribution. If use\_t is False, then the p-values are based on the normal distribution. | | Returns: | **res** – The results for the test are attributes of this results instance. The available results have the same elements as the parameter table in `summary()`. | | Return type: | ContrastResults instance | #### Examples ``` >>> import numpy as np >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> r = np.zeros_like(results.params) >>> r[5:] = [1,-1] >>> print(r) [ 0. 0. 0. 0. 0. 1. -1.] ``` r tests that the coefficients on the 5th and 6th independent variable are the same. ``` >>> T_test = results.t_test(r) >>> print(T_test) Test for Constraints ============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------ c0 -1829.2026 455.391 -4.017 0.003 -2859.368 -799.037 ============================================================================== >>> T_test.effect -1829.2025687192481 >>> T_test.sd 455.39079425193762 >>> T_test.tvalue -4.0167754636411717 >>> T_test.pvalue 0.0015163772380899498 ``` Alternatively, you can specify the hypothesis tests using a string ``` >>> from statsmodels.formula.api import ols >>> dta = sm.datasets.longley.load_pandas().data >>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' >>> results = ols(formula, dta).fit() >>> hypotheses = 'GNPDEFL = GNP, UNEMP = 2, YEAR/1829 = 1' >>> t_test = results.t_test(hypotheses) >>> print(t_test) Test for Constraints ============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------ c0 15.0977 84.937 0.178 0.863 -177.042 207.238 c1 -2.0202 0.488 -8.231 0.000 -3.125 -0.915 c2 1.0001 0.249 0.000 1.000 0.437 1.563 ============================================================================== ``` See also [`tvalues`](statsmodels.genmod.generalized_linear_model.glmresults.tvalues#statsmodels.genmod.generalized_linear_model.GLMResults.tvalues "statsmodels.genmod.generalized_linear_model.GLMResults.tvalues") individual t statistics [`f_test`](statsmodels.genmod.generalized_linear_model.glmresults.f_test#statsmodels.genmod.generalized_linear_model.GLMResults.f_test "statsmodels.genmod.generalized_linear_model.GLMResults.f_test") for F tests [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") statsmodels statsmodels.stats.contingency_tables.Table2x2.chi2_contribs statsmodels.stats.contingency\_tables.Table2x2.chi2\_contribs ============================================================= `Table2x2.chi2_contribs()` statsmodels statsmodels.tsa.vector_ar.var_model.VARResults.plot statsmodels.tsa.vector\_ar.var\_model.VARResults.plot ===================================================== `VARResults.plot()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/var_model.html#VARResults.plot) Plot input time series statsmodels statsmodels.tsa.statespace.mlemodel.MLEModel.transform_params statsmodels.tsa.statespace.mlemodel.MLEModel.transform\_params ============================================================== `MLEModel.transform_params(unconstrained)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEModel.transform_params) Transform unconstrained parameters used by the optimizer to constrained parameters used in likelihood evaluation | Parameters: | **unconstrained** (*array\_like*) – Array of unconstrained parameters used by the optimizer, to be transformed. | | Returns: | **constrained** – Array of constrained parameters which may be used in likelihood evalation. | | Return type: | array\_like | #### Notes This is a noop in the base class, subclasses should override where appropriate. statsmodels statsmodels.regression.mixed_linear_model.MixedLMResults.aic statsmodels.regression.mixed\_linear\_model.MixedLMResults.aic ============================================================== `MixedLMResults.aic()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/mixed_linear_model.html#MixedLMResults.aic) statsmodels statsmodels.tsa.statespace.kalman_filter.FilterResults statsmodels.tsa.statespace.kalman\_filter.FilterResults ======================================================= `class statsmodels.tsa.statespace.kalman_filter.FilterResults(model)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/kalman_filter.html#FilterResults) Results from applying the Kalman filter to a state space model. | Parameters: | **model** ([Representation](statsmodels.tsa.statespace.representation.representation#statsmodels.tsa.statespace.representation.Representation "statsmodels.tsa.statespace.representation.Representation")) – A Statespace representation | `nobs` *int* – Number of observations. `k_endog` *int* – The dimension of the observation series. `k_states` *int* – The dimension of the unobserved state process. `k_posdef` *int* – The dimension of a guaranteed positive definite covariance matrix describing the shocks in the measurement equation. `dtype` *dtype* – Datatype of representation matrices `prefix` *str* – BLAS prefix of representation matrices `shapes` *dictionary of name,tuple* – A dictionary recording the shapes of each of the representation matrices as tuples. `endog` *array* – The observation vector. `design` *array* – The design matrix, \(Z\). `obs_intercept` *array* – The intercept for the observation equation, \(d\). `obs_cov` *array* – The covariance matrix for the observation equation \(H\). `transition` *array* – The transition matrix, \(T\). `state_intercept` *array* – The intercept for the transition equation, \(c\). `selection` *array* – The selection matrix, \(R\). `state_cov` *array* – The covariance matrix for the state equation \(Q\). `missing` *array of bool* – An array of the same size as `endog`, filled with boolean values that are True if the corresponding entry in `endog` is NaN and False otherwise. `nmissing` *array of int* – An array of size `nobs`, where the ith entry is the number (between 0 and `k_endog`) of NaNs in the ith row of the `endog` array. `time_invariant` *bool* – Whether or not the representation matrices are time-invariant `initialization` *str* – Kalman filter initialization method. `initial_state` *array\_like* – The state vector used to initialize the Kalamn filter. `initial_state_cov` *array\_like* – The state covariance matrix used to initialize the Kalamn filter. `filter_method` *int* – Bitmask representing the Kalman filtering method `inversion_method` *int* – Bitmask representing the method used to invert the forecast error covariance matrix. `stability_method` *int* – Bitmask representing the methods used to promote numerical stability in the Kalman filter recursions. `conserve_memory` *int* – Bitmask representing the selected memory conservation method. `filter_timing` *int* – Whether or not to use the alternate timing convention. `tolerance` *float* – The tolerance at which the Kalman filter determines convergence to steady-state. `loglikelihood_burn` *int* – The number of initial periods during which the loglikelihood is not recorded. `converged` *bool* – Whether or not the Kalman filter converged. `period_converged` *int* – The time period in which the Kalman filter converged. `filtered_state` *array* – The filtered state vector at each time period. `filtered_state_cov` *array* – The filtered state covariance matrix at each time period. `predicted_state` *array* – The predicted state vector at each time period. `predicted_state_cov` *array* – The predicted state covariance matrix at each time period. `kalman_gain` *array* – The Kalman gain at each time period. `forecasts` *array* – The one-step-ahead forecasts of observations at each time period. `forecasts_error` *array* – The forecast errors at each time period. `forecasts_error_cov` *array* – The forecast error covariance matrices at each time period. `llf_obs` *array* – The loglikelihood values at each time period. #### Methods | | | | --- | --- | | [`predict`](statsmodels.tsa.statespace.kalman_filter.filterresults.predict#statsmodels.tsa.statespace.kalman_filter.FilterResults.predict "statsmodels.tsa.statespace.kalman_filter.FilterResults.predict")([start, end, dynamic]) | In-sample and out-of-sample prediction for state space models generally | | [`update_filter`](statsmodels.tsa.statespace.kalman_filter.filterresults.update_filter#statsmodels.tsa.statespace.kalman_filter.FilterResults.update_filter "statsmodels.tsa.statespace.kalman_filter.FilterResults.update_filter")(kalman\_filter) | Update the filter results | | [`update_representation`](statsmodels.tsa.statespace.kalman_filter.filterresults.update_representation#statsmodels.tsa.statespace.kalman_filter.FilterResults.update_representation "statsmodels.tsa.statespace.kalman_filter.FilterResults.update_representation")(model[, only\_options]) | Update the results to match a given model | #### Attributes | | | | --- | --- | | [`kalman_gain`](#statsmodels.tsa.statespace.kalman_filter.FilterResults.kalman_gain "statsmodels.tsa.statespace.kalman_filter.FilterResults.kalman_gain") | Kalman gain matrices | | `standardized_forecasts_error` | Standardized forecast errors | statsmodels statsmodels.discrete.discrete_model.MultinomialResults.initialize statsmodels.discrete.discrete\_model.MultinomialResults.initialize ================================================================== `MultinomialResults.initialize(model, params, **kwd)` statsmodels statsmodels.sandbox.distributions.extras.pdf_moments statsmodels.sandbox.distributions.extras.pdf\_moments ===================================================== `statsmodels.sandbox.distributions.extras.pdf_moments(cnt)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/distributions/extras.html#pdf_moments) Return the Gaussian expanded pdf function given the list of central moments (first one is mean). Changed so it works only if four arguments are given. Uses explicit formula, not loop. #### Notes This implements a Gram-Charlier expansion of the normal distribution where the first 2 moments coincide with those of the normal distribution but skew and kurtosis can deviate from it. In the Gram-Charlier distribution it is possible that the density becomes negative. This is the case when the deviation from the normal distribution is too large. #### References <http://en.wikipedia.org/wiki/Edgeworth_series> Johnson N.L., S. Kotz, N. Balakrishnan: Continuous Univariate Distributions, Volume 1, 2nd ed., p.30 statsmodels statsmodels.genmod.families.links.nbinom.inverse statsmodels.genmod.families.links.nbinom.inverse ================================================ `nbinom.inverse(z)` Inverse of the negative binomial transform | Parameters: | **z** (*array-like*) – The value of the inverse of the negative binomial link at `p`. | | Returns: | **p** – Mean parameters | | Return type: | array | #### Notes g^(-1)(z) = exp(z)/(alpha\*(1-exp(z))) statsmodels statsmodels.stats.power.TTestPower.power statsmodels.stats.power.TTestPower.power ======================================== `TTestPower.power(effect_size, nobs, alpha, df=None, alternative='two-sided')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/power.html#TTestPower.power) Calculate the power of a t-test for one sample or paired samples. | Parameters: | * **effect\_size** (*float*) – standardized effect size, mean divided by the standard deviation. effect size has to be positive. * **nobs** (*int* *or* *float*) – sample size, number of observations. * **alpha** (*float in interval* *(**0**,**1**)*) – significance level, e.g. 0.05, is the probability of a type I error, that is wrong rejections if the Null Hypothesis is true. * **df** (*int* *or* *float*) – degrees of freedom. By default this is None, and the df from the one sample or paired ttest is used, `df = nobs1 - 1` * **alternative** (*string**,* *'two-sided'* *(**default**)**,* *'larger'**,* *'smaller'*) – extra argument to choose whether the power is calculated for a two-sided (default) or one sided test. The one-sided test can be either ‘larger’, ‘smaller’. . | | Returns: | **power** – Power of the test, e.g. 0.8, is one minus the probability of a type II error. Power is the probability that the test correctly rejects the Null Hypothesis if the Alternative Hypothesis is true. | | Return type: | float |
programming_docs
statsmodels statsmodels.tsa.statespace.mlemodel.MLEResults.plot_diagnostics statsmodels.tsa.statespace.mlemodel.MLEResults.plot\_diagnostics ================================================================ `MLEResults.plot_diagnostics(variable=0, lags=10, fig=None, figsize=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEResults.plot_diagnostics) Diagnostic plots for standardized residuals of one endogenous variable | Parameters: | * **variable** (*integer**,* *optional*) – Index of the endogenous variable for which the diagnostic plots should be created. Default is 0. * **lags** (*integer**,* *optional*) – Number of lags to include in the correlogram. Default is 10. * **fig** (*Matplotlib Figure instance**,* *optional*) – If given, subplots are created in this figure instead of in a new figure. Note that the 2x2 grid will be created in the provided figure using `fig.add_subplot()`. * **figsize** (*tuple**,* *optional*) – If a figure is created, this argument allows specifying a size. The tuple is (width, height). | #### Notes Produces a 2x2 plot grid with the following plots (ordered clockwise from top left): 1. Standardized residuals over time 2. Histogram plus estimated density of standardized residulas, along with a Normal(0,1) density plotted for reference. 3. Normal Q-Q plot, with Normal reference line. 4. Correlogram See also [`statsmodels.graphics.gofplots.qqplot`](statsmodels.graphics.gofplots.qqplot#statsmodels.graphics.gofplots.qqplot "statsmodels.graphics.gofplots.qqplot"), [`statsmodels.graphics.tsaplots.plot_acf`](statsmodels.graphics.tsaplots.plot_acf#statsmodels.graphics.tsaplots.plot_acf "statsmodels.graphics.tsaplots.plot_acf") statsmodels statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialResults.llr statsmodels.discrete.count\_model.ZeroInflatedNegativeBinomialResults.llr ========================================================================= `ZeroInflatedNegativeBinomialResults.llr()` statsmodels statsmodels.tools.eval_measures.hqic_sigma statsmodels.tools.eval\_measures.hqic\_sigma ============================================ `statsmodels.tools.eval_measures.hqic_sigma(sigma2, nobs, df_modelwc, islog=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tools/eval_measures.html#hqic_sigma) Hannan-Quinn information criterion (HQC) | Parameters: | * **sigma2** (*float*) – estimate of the residual variance or determinant of Sigma\_hat in the multivariate case. If islog is true, then it is assumed that sigma is already log-ed, for example logdetSigma. * **nobs** (*int*) – number of observations * **df\_modelwc** (*int*) – number of parameters including constant | | Returns: | **hqic** – information criterion | | Return type: | float | #### Notes A constant has been dropped in comparison to the loglikelihood base information criteria. These should be used to compare for comparable models. #### References xxx statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.nobs statsmodels.sandbox.regression.gmm.IVRegressionResults.nobs =========================================================== `IVRegressionResults.nobs()` statsmodels statsmodels.regression.quantile_regression.QuantRegResults.mse_total statsmodels.regression.quantile\_regression.QuantRegResults.mse\_total ====================================================================== `QuantRegResults.mse_total()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/quantile_regression.html#QuantRegResults.mse_total) statsmodels statsmodels.tsa.arima_process.ArmaProcess.arma2ma statsmodels.tsa.arima\_process.ArmaProcess.arma2ma ================================================== `ArmaProcess.arma2ma(lags=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_process.html#ArmaProcess.arma2ma) statsmodels statsmodels.genmod.generalized_linear_model.GLMResults.bse statsmodels.genmod.generalized\_linear\_model.GLMResults.bse ============================================================ `GLMResults.bse()` statsmodels statsmodels.stats.proportion.multinomial_proportions_confint statsmodels.stats.proportion.multinomial\_proportions\_confint ============================================================== `statsmodels.stats.proportion.multinomial_proportions_confint(counts, alpha=0.05, method='goodman')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/proportion.html#multinomial_proportions_confint) Confidence intervals for multinomial proportions. | Parameters: | * **counts** (*array\_like of int**,* *1-D*) – Number of observations in each category. * **alpha** (*float in* *(**0**,* *1**)**,* *optional*) – Significance level, defaults to 0.05. * **method** (*{'goodman'**,* *'sison-glaz'}**,* *optional*) – Method to use to compute the confidence intervals; available methods are: + `goodman`: based on a chi-squared approximation, valid if all values in `counts` are greater or equal to 5 [[2]](#id11) + `sison-glaz`: less conservative than `goodman`, but only valid if `counts` has 7 or more categories (`len(counts) >= 7`) [[3]](#id12) | | Returns: | **confint** – Array of [lower, upper] confidence levels for each category, such that overall coverage is (approximately) `1-alpha`. | | Return type: | ndarray, 2-D | | Raises: | * [`ValueError`](https://docs.python.org/3.2/library/exceptions.html#ValueError "(in Python v3.2)") – If `alpha` is not in `(0, 1)` (bounds excluded), or if the values in `counts` are not all positive or null. * [`NotImplementedError`](https://docs.python.org/3.2/library/exceptions.html#NotImplementedError "(in Python v3.2)") – If `method` is not kown. * [`Exception`](https://docs.python.org/3.2/library/exceptions.html#Exception "(in Python v3.2)") – When `method == 'sison-glaz'`, if for some reason `c` cannot be computed; this signals a bug and should be reported. | #### Notes The `goodman` method [[2]](#id11) is based on approximating a statistic based on the multinomial as a chi-squared random variable. The usual recommendation is that this is valid if all the values in `counts` are greater than or equal to 5. There is no condition on the number of categories for this method. The `sison-glaz` method [[3]](#id12) approximates the multinomial probabilities, and evaluates that with a maximum-likelihood estimator. The first approximation is an Edgeworth expansion that converges when the number of categories goes to infinity, and the maximum-likelihood estimator converges when the number of observations (`sum(counts)`) goes to infinity. In their paper, Sison & Glaz demo their method with at least 7 categories, so `len(counts) >= 7` with all values in `counts` at or above 5 can be used as a rule of thumb for the validity of this method. This method is less conservative than the `goodman` method (i.e. it will yield confidence intervals closer to the desired significance level), but produces confidence intervals of uniform width over all categories (except when the intervals reach 0 or 1, in which case they are truncated), which makes it most useful when proportions are of similar magnitude. Aside from the original sources ([[1]](#id10), [[2]](#id11), and [[3]](#id12)), the implementation uses the formulas (though not the code) presented in [[4]](#id13) and [[5]](#id14). #### References | | | | --- | --- | | [[1]](#id5) | Levin, Bruce, “A representation for multinomial cumulative distribution functions,” The Annals of Statistics, Vol. 9, No. 5, 1981, pp. 1123-1126. | | | | | --- | --- | | [2] | *([1](#id1), [2](#id3), [3](#id6))* Goodman, L.A., “On simultaneous confidence intervals for multinomial proportions,” Technometrics, Vol. 7, No. 2, 1965, pp. 247-254. | | | | | --- | --- | | [3] | *([1](#id2), [2](#id4), [3](#id7))* Sison, Cristina P., and Joseph Glaz, “Simultaneous Confidence Intervals and Sample Size Determination for Multinomial Proportions,” Journal of the American Statistical Association, Vol. 90, No. 429, 1995, pp. 366-369. | | | | | --- | --- | | [[4]](#id8) | May, Warren L., and William D. Johnson, “A SAS® macro for constructing simultaneous confidence intervals for multinomial proportions,” Computer methods and programs in Biomedicine, Vol. 53, No. 3, 1997, pp. 153-162. | | | | | --- | --- | | [[5]](#id9) | May, Warren L., and William D. Johnson, “Constructing two-sided simultaneous confidence intervals for multinomial proportions for small counts in a large number of cells,” Journal of Statistical Software, Vol. 5, No. 6, 2000, pp. 1-24. | statsmodels statsmodels.tsa.arima_model.ARIMAResults.plot_predict statsmodels.tsa.arima\_model.ARIMAResults.plot\_predict ======================================================= `ARIMAResults.plot_predict(start=None, end=None, exog=None, dynamic=False, alpha=0.05, plot_insample=True, ax=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_model.html#ARIMAResults.plot_predict) Plot forecasts | Parameters: | * **start** (*int**,* *str**, or* *datetime*) – Zero-indexed observation number at which to start forecasting, ie., the first forecast is start. Can also be a date string to parse or a datetime type. * **end** (*int**,* *str**, or* *datetime*) – Zero-indexed observation number at which to end forecasting, ie., the first forecast is start. Can also be a date string to parse or a datetime type. However, if the dates index does not have a fixed frequency, end must be an integer index if you want out of sample prediction. * **exog** (*array-like**,* *optional*) – If the model is an ARMAX and out-of-sample forecasting is requested, exog must be given. Note that you’ll need to pass `k_ar` additional lags for any exogenous variables. E.g., if you fit an ARMAX(2, q) model and want to predict 5 steps, you need 7 observations to do this. * **dynamic** (*bool**,* *optional*) – The `dynamic` keyword affects in-sample prediction. If dynamic is False, then the in-sample lagged values are used for prediction. If `dynamic` is True, then in-sample forecasts are used in place of lagged dependent variables. The first forecasted value is `start`. * **alpha** (*float**,* *optional*) – The confidence intervals for the forecasts are (1 - alpha)% * **plot\_insample** (*bool**,* *optional*) – Whether to plot the in-sample series. Default is True. * **ax** (*matplotlib.Axes**,* *optional*) – Existing axes to plot with. | | Returns: | **fig** – The plotted Figure instance | | Return type: | matplotlib.Figure | #### Examples ``` >>> import statsmodels.api as sm >>> import matplotlib.pyplot as plt >>> import pandas as pd >>> >>> dta = sm.datasets.sunspots.load_pandas().data[['SUNACTIVITY']] >>> dta.index = pd.DatetimeIndex(start='1700', end='2009', freq='A') >>> res = sm.tsa.ARMA(dta, (3, 0)).fit() >>> fig, ax = plt.subplots() >>> ax = dta.loc['1950':].plot(ax=ax) >>> fig = res.plot_predict('1990', '2012', dynamic=True, ax=ax, ... plot_insample=False) >>> plt.show() ``` ([Source code](../plots/arma_predict_plot.py), [png](../plots/arma_predict_plot.png), [hires.png](../plots/arma_predict_plot.hires.png), [pdf](../plots/arma_predict_plot.pdf)) #### Notes This is hard-coded to only allow plotting of the forecasts in levels. It is recommended to use dates with the time-series models, as the below will probably make clear. However, if ARIMA is used without dates and/or `start` and `end` are given as indices, then these indices are in terms of the *original*, undifferenced series. Ie., given some undifferenced observations: ``` 1970Q1, 1 1970Q2, 1.5 1970Q3, 1.25 1970Q4, 2.25 1971Q1, 1.2 1971Q2, 4.1 ``` 1970Q1 is observation 0 in the original series. However, if we fit an ARIMA(p,1,q) model then we lose this first observation through differencing. Therefore, the first observation we can forecast (if using exact MLE) is index 1. In the differenced series this is index 0, but we refer to it as 1 from the original series. statsmodels statsmodels.discrete.discrete_model.MultinomialResults.t_test statsmodels.discrete.discrete\_model.MultinomialResults.t\_test =============================================================== `MultinomialResults.t_test(r_matrix, cov_p=None, scale=None, use_t=None)` Compute a t-test for a each linear hypothesis of the form Rb = q | Parameters: | * **r\_matrix** (*array-like**,* *str**,* *tuple*) – + array : If an array is given, a p x k 2d array or length k 1d array specifying the linear restrictions. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q). If q is given, can be either a scalar or a length p row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – An optional `scale` to use. Default is the scale specified by the model fit. * **use\_t** (*bool**,* *optional*) – If use\_t is None, then the default of the model is used. If use\_t is True, then the p-values are based on the t distribution. If use\_t is False, then the p-values are based on the normal distribution. | | Returns: | **res** – The results for the test are attributes of this results instance. The available results have the same elements as the parameter table in `summary()`. | | Return type: | ContrastResults instance | #### Examples ``` >>> import numpy as np >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> r = np.zeros_like(results.params) >>> r[5:] = [1,-1] >>> print(r) [ 0. 0. 0. 0. 0. 1. -1.] ``` r tests that the coefficients on the 5th and 6th independent variable are the same. ``` >>> T_test = results.t_test(r) >>> print(T_test) Test for Constraints ============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------ c0 -1829.2026 455.391 -4.017 0.003 -2859.368 -799.037 ============================================================================== >>> T_test.effect -1829.2025687192481 >>> T_test.sd 455.39079425193762 >>> T_test.tvalue -4.0167754636411717 >>> T_test.pvalue 0.0015163772380899498 ``` Alternatively, you can specify the hypothesis tests using a string ``` >>> from statsmodels.formula.api import ols >>> dta = sm.datasets.longley.load_pandas().data >>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' >>> results = ols(formula, dta).fit() >>> hypotheses = 'GNPDEFL = GNP, UNEMP = 2, YEAR/1829 = 1' >>> t_test = results.t_test(hypotheses) >>> print(t_test) Test for Constraints ============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------ c0 15.0977 84.937 0.178 0.863 -177.042 207.238 c1 -2.0202 0.488 -8.231 0.000 -3.125 -0.915 c2 1.0001 0.249 0.000 1.000 0.437 1.563 ============================================================================== ``` See also [`tvalues`](statsmodels.discrete.discrete_model.multinomialresults.tvalues#statsmodels.discrete.discrete_model.MultinomialResults.tvalues "statsmodels.discrete.discrete_model.MultinomialResults.tvalues") individual t statistics [`f_test`](statsmodels.discrete.discrete_model.multinomialresults.f_test#statsmodels.discrete.discrete_model.MultinomialResults.f_test "statsmodels.discrete.discrete_model.MultinomialResults.f_test") for F tests [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") statsmodels statsmodels.discrete.discrete_model.CountModel statsmodels.discrete.discrete\_model.CountModel =============================================== `class statsmodels.discrete.discrete_model.CountModel(endog, exog, offset=None, exposure=None, missing='none', **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#CountModel) #### Methods | | | | --- | --- | | [`cdf`](statsmodels.discrete.discrete_model.countmodel.cdf#statsmodels.discrete.discrete_model.CountModel.cdf "statsmodels.discrete.discrete_model.CountModel.cdf")(X) | The cumulative distribution function of the model. | | [`cov_params_func_l1`](statsmodels.discrete.discrete_model.countmodel.cov_params_func_l1#statsmodels.discrete.discrete_model.CountModel.cov_params_func_l1 "statsmodels.discrete.discrete_model.CountModel.cov_params_func_l1")(likelihood\_model, xopt, …) | Computes cov\_params on a reduced parameter space corresponding to the nonzero parameters resulting from the l1 regularized fit. | | [`fit`](statsmodels.discrete.discrete_model.countmodel.fit#statsmodels.discrete.discrete_model.CountModel.fit "statsmodels.discrete.discrete_model.CountModel.fit")([start\_params, method, maxiter, …]) | Fit the model using maximum likelihood. | | [`fit_regularized`](statsmodels.discrete.discrete_model.countmodel.fit_regularized#statsmodels.discrete.discrete_model.CountModel.fit_regularized "statsmodels.discrete.discrete_model.CountModel.fit_regularized")([start\_params, method, …]) | Fit the model using a regularized maximum likelihood. | | [`from_formula`](statsmodels.discrete.discrete_model.countmodel.from_formula#statsmodels.discrete.discrete_model.CountModel.from_formula "statsmodels.discrete.discrete_model.CountModel.from_formula")(formula, data[, subset, drop\_cols]) | Create a Model from a formula and dataframe. | | [`hessian`](statsmodels.discrete.discrete_model.countmodel.hessian#statsmodels.discrete.discrete_model.CountModel.hessian "statsmodels.discrete.discrete_model.CountModel.hessian")(params) | The Hessian matrix of the model | | [`information`](statsmodels.discrete.discrete_model.countmodel.information#statsmodels.discrete.discrete_model.CountModel.information "statsmodels.discrete.discrete_model.CountModel.information")(params) | Fisher information matrix of model | | [`initialize`](statsmodels.discrete.discrete_model.countmodel.initialize#statsmodels.discrete.discrete_model.CountModel.initialize "statsmodels.discrete.discrete_model.CountModel.initialize")() | Initialize is called by statsmodels.model.LikelihoodModel.\_\_init\_\_ and should contain any preprocessing that needs to be done for a model. | | [`loglike`](statsmodels.discrete.discrete_model.countmodel.loglike#statsmodels.discrete.discrete_model.CountModel.loglike "statsmodels.discrete.discrete_model.CountModel.loglike")(params) | Log-likelihood of model. | | [`pdf`](statsmodels.discrete.discrete_model.countmodel.pdf#statsmodels.discrete.discrete_model.CountModel.pdf "statsmodels.discrete.discrete_model.CountModel.pdf")(X) | The probability density (mass) function of the model. | | [`predict`](statsmodels.discrete.discrete_model.countmodel.predict#statsmodels.discrete.discrete_model.CountModel.predict "statsmodels.discrete.discrete_model.CountModel.predict")(params[, exog, exposure, offset, linear]) | Predict response variable of a count model given exogenous variables. | | [`score`](statsmodels.discrete.discrete_model.countmodel.score#statsmodels.discrete.discrete_model.CountModel.score "statsmodels.discrete.discrete_model.CountModel.score")(params) | Score vector of model. | #### Attributes | | | | --- | --- | | `endog_names` | Names of endogenous variables | | `exog_names` | Names of exogenous variables |
programming_docs
statsmodels statsmodels.nonparametric.kernel_regression.KernelCensoredReg statsmodels.nonparametric.kernel\_regression.KernelCensoredReg ============================================================== `class statsmodels.nonparametric.kernel_regression.KernelCensoredReg(endog, exog, var_type, reg_type, bw='cv_ls', censor_val=0, defaults=<statsmodels.nonparametric._kernel_base.EstimatorSettings object>)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/nonparametric/kernel_regression.html#KernelCensoredReg) Nonparametric censored regression. Calculates the condtional mean `E[y|X]` where `y = g(X) + e`, where y is left-censored. Left censored variable Y is defined as `Y = min {Y', L}` where `L` is the value at which `Y` is censored and `Y'` is the true value of the variable. | Parameters: | * **endog** (*list with one element which is array\_like*) – This is the dependent variable. * **exog** (*list*) – The training data for the independent variable(s) Each element in the list is a separate variable * **dep\_type** (*str*) – The type of the dependent variable(s) c: Continuous u: Unordered (Discrete) o: Ordered (Discrete) * **reg\_type** (*str*) – Type of regression estimator lc: Local Constant Estimator ll: Local Linear Estimator * **bw** (*array\_like*) – Either a user-specified bandwidth or the method for bandwidth selection. cv\_ls: cross-validaton least squares aic: AIC Hurvich Estimator * **censor\_val** (*float*) – Value at which the dependent variable is censored * **defaults** (*EstimatorSettings instance**,* *optional*) – The default values for the efficient bandwidth estimation | `bw` *array\_like* – The bandwidth parameters #### Methods | | | | --- | --- | | [`aic_hurvich`](statsmodels.nonparametric.kernel_regression.kernelcensoredreg.aic_hurvich#statsmodels.nonparametric.kernel_regression.KernelCensoredReg.aic_hurvich "statsmodels.nonparametric.kernel_regression.KernelCensoredReg.aic_hurvich")(bw[, func]) | Computes the AIC Hurvich criteria for the estimation of the bandwidth. | | [`censored`](statsmodels.nonparametric.kernel_regression.kernelcensoredreg.censored#statsmodels.nonparametric.kernel_regression.KernelCensoredReg.censored "statsmodels.nonparametric.kernel_regression.KernelCensoredReg.censored")(censor\_val) | | | [`cv_loo`](statsmodels.nonparametric.kernel_regression.kernelcensoredreg.cv_loo#statsmodels.nonparametric.kernel_regression.KernelCensoredReg.cv_loo "statsmodels.nonparametric.kernel_regression.KernelCensoredReg.cv_loo")(bw, func) | The cross-validation function with leave-one-out estimator | | [`fit`](statsmodels.nonparametric.kernel_regression.kernelcensoredreg.fit#statsmodels.nonparametric.kernel_regression.KernelCensoredReg.fit "statsmodels.nonparametric.kernel_regression.KernelCensoredReg.fit")([data\_predict]) | Returns the marginal effects at the data\_predict points. | | [`loo_likelihood`](statsmodels.nonparametric.kernel_regression.kernelcensoredreg.loo_likelihood#statsmodels.nonparametric.kernel_regression.KernelCensoredReg.loo_likelihood "statsmodels.nonparametric.kernel_regression.KernelCensoredReg.loo_likelihood")() | | | [`r_squared`](statsmodels.nonparametric.kernel_regression.kernelcensoredreg.r_squared#statsmodels.nonparametric.kernel_regression.KernelCensoredReg.r_squared "statsmodels.nonparametric.kernel_regression.KernelCensoredReg.r_squared")() | Returns the R-Squared for the nonparametric regression. | | [`sig_test`](statsmodels.nonparametric.kernel_regression.kernelcensoredreg.sig_test#statsmodels.nonparametric.kernel_regression.KernelCensoredReg.sig_test "statsmodels.nonparametric.kernel_regression.KernelCensoredReg.sig_test")(var\_pos[, nboot, nested\_res, pivot]) | Significance test for the variables in the regression. | statsmodels statsmodels.tsa.stattools.arma_order_select_ic statsmodels.tsa.stattools.arma\_order\_select\_ic ================================================= `statsmodels.tsa.stattools.arma_order_select_ic(y, max_ar=4, max_ma=2, ic='bic', trend='c', model_kw={}, fit_kw={})` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/stattools.html#arma_order_select_ic) Returns information criteria for many ARMA models | Parameters: | * **y** (*array-like*) – Time-series data * **max\_ar** (*int*) – Maximum number of AR lags to use. Default 4. * **max\_ma** (*int*) – Maximum number of MA lags to use. Default 2. * **ic** (*str**,* *list*) – Information criteria to report. Either a single string or a list of different criteria is possible. * **trend** (*str*) – The trend to use when fitting the ARMA models. * **model\_kw** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")) – Keyword arguments to be passed to the `ARMA` model * **fit\_kw** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")) – Keyword arguments to be passed to `ARMA.fit`. | | Returns: | **obj** – Each ic is an attribute with a DataFrame for the results. The AR order used is the row index. The ma order used is the column index. The minimum orders are available as `ic_min_order`. | | Return type: | Results object | #### Examples ``` >>> from statsmodels.tsa.arima_process import arma_generate_sample >>> import statsmodels.api as sm >>> import numpy as np ``` ``` >>> arparams = np.array([.75, -.25]) >>> maparams = np.array([.65, .35]) >>> arparams = np.r_[1, -arparams] >>> maparam = np.r_[1, maparams] >>> nobs = 250 >>> np.random.seed(2014) >>> y = arma_generate_sample(arparams, maparams, nobs) >>> res = sm.tsa.arma_order_select_ic(y, ic=['aic', 'bic'], trend='nc') >>> res.aic_min_order >>> res.bic_min_order ``` #### Notes This method can be used to tentatively identify the order of an ARMA process, provided that the time series is stationary and invertible. This function computes the full exact MLE estimate of each model and can be, therefore a little slow. An implementation using approximate estimates will be provided in the future. In the meantime, consider passing {method : ‘css’} to fit\_kw. statsmodels statsmodels.duration.hazard_regression.PHRegResults.save statsmodels.duration.hazard\_regression.PHRegResults.save ========================================================= `PHRegResults.save(fname, remove_data=False)` save a pickle of this instance | Parameters: | * **fname** (*string* *or* *filehandle*) – fname can be a string to a file path or filename, or a filehandle. * **remove\_data** (*bool*) – If False (default), then the instance is pickled without changes. If True, then all arrays with length nobs are set to None before pickling. See the remove\_data method. In some cases not all arrays will be set to None. | #### Notes If remove\_data is true and the model result does not implement a remove\_data method then this will raise an exception. statsmodels statsmodels.stats.weightstats.DescrStatsW.var_ddof statsmodels.stats.weightstats.DescrStatsW.var\_ddof =================================================== `DescrStatsW.var_ddof(ddof=0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/weightstats.html#DescrStatsW.var_ddof) variance of data given ddof | Parameters: | **ddof** (*int**,* *float*) – degrees of freedom correction, independent of attribute ddof | | Returns: | **var** – variance with denominator `sum_weights - ddof` | | Return type: | float, ndarray | statsmodels statsmodels.genmod.cov_struct.GlobalOddsRatio.summary statsmodels.genmod.cov\_struct.GlobalOddsRatio.summary ====================================================== `GlobalOddsRatio.summary()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/cov_struct.html#GlobalOddsRatio.summary) Returns a text summary of the current estimate of the dependence structure. statsmodels statsmodels.tsa.statespace.representation.FrozenRepresentation.update_representation statsmodels.tsa.statespace.representation.FrozenRepresentation.update\_representation ===================================================================================== `FrozenRepresentation.update_representation(model)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/representation.html#FrozenRepresentation.update_representation) statsmodels statsmodels.discrete.count_model.ZeroInflatedPoisson statsmodels.discrete.count\_model.ZeroInflatedPoisson ===================================================== `class statsmodels.discrete.count_model.ZeroInflatedPoisson(endog, exog, exog_infl=None, offset=None, exposure=None, inflation='logit', missing='none', **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/count_model.html#ZeroInflatedPoisson) Poisson Zero Inflated model for count data | Parameters: | * **endog** (*array-like*) – 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 `statsmodels.tools.add_constant`. * **exog\_infl** (*array\_like* *or* *None*) – Explanatory variables for the binary inflation model, i.e. for mixing probability model. If None, then a constant is used. * **offset** (*array\_like*) – Offset is added to the linear prediction with coefficient equal to 1. * **exposure** (*array\_like*) – Log(exposure) is added to the linear prediction with coefficient equal to 1. * **inflation** (*string**,* *'logit'* *or* *'probit'*) – The model for the zero inflation, either Logit (default) or Probit * **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.’ | `endog` *array* – A reference to the endogenous response variable `exog` *array* – A reference to the exogenous design. `exog_infl` *array* – A reference to the zero-inflated exogenous design. #### Methods | | | | --- | --- | | [`cdf`](statsmodels.discrete.count_model.zeroinflatedpoisson.cdf#statsmodels.discrete.count_model.ZeroInflatedPoisson.cdf "statsmodels.discrete.count_model.ZeroInflatedPoisson.cdf")(X) | The cumulative distribution function of the model. | | [`cov_params_func_l1`](statsmodels.discrete.count_model.zeroinflatedpoisson.cov_params_func_l1#statsmodels.discrete.count_model.ZeroInflatedPoisson.cov_params_func_l1 "statsmodels.discrete.count_model.ZeroInflatedPoisson.cov_params_func_l1")(likelihood\_model, xopt, …) | Computes cov\_params on a reduced parameter space corresponding to the nonzero parameters resulting from the l1 regularized fit. | | [`fit`](statsmodels.discrete.count_model.zeroinflatedpoisson.fit#statsmodels.discrete.count_model.ZeroInflatedPoisson.fit "statsmodels.discrete.count_model.ZeroInflatedPoisson.fit")([start\_params, method, maxiter, …]) | Fit the model using maximum likelihood. | | [`fit_regularized`](statsmodels.discrete.count_model.zeroinflatedpoisson.fit_regularized#statsmodels.discrete.count_model.ZeroInflatedPoisson.fit_regularized "statsmodels.discrete.count_model.ZeroInflatedPoisson.fit_regularized")([start\_params, method, …]) | Fit the model using a regularized maximum likelihood. | | [`from_formula`](statsmodels.discrete.count_model.zeroinflatedpoisson.from_formula#statsmodels.discrete.count_model.ZeroInflatedPoisson.from_formula "statsmodels.discrete.count_model.ZeroInflatedPoisson.from_formula")(formula, data[, subset, drop\_cols]) | Create a Model from a formula and dataframe. | | [`hessian`](statsmodels.discrete.count_model.zeroinflatedpoisson.hessian#statsmodels.discrete.count_model.ZeroInflatedPoisson.hessian "statsmodels.discrete.count_model.ZeroInflatedPoisson.hessian")(params) | Generic Zero Inflated model Hessian matrix of the loglikelihood | | [`information`](statsmodels.discrete.count_model.zeroinflatedpoisson.information#statsmodels.discrete.count_model.ZeroInflatedPoisson.information "statsmodels.discrete.count_model.ZeroInflatedPoisson.information")(params) | Fisher information matrix of model | | [`initialize`](statsmodels.discrete.count_model.zeroinflatedpoisson.initialize#statsmodels.discrete.count_model.ZeroInflatedPoisson.initialize "statsmodels.discrete.count_model.ZeroInflatedPoisson.initialize")() | Initialize is called by statsmodels.model.LikelihoodModel.\_\_init\_\_ and should contain any preprocessing that needs to be done for a model. | | [`loglike`](statsmodels.discrete.count_model.zeroinflatedpoisson.loglike#statsmodels.discrete.count_model.ZeroInflatedPoisson.loglike "statsmodels.discrete.count_model.ZeroInflatedPoisson.loglike")(params) | Loglikelihood of Generic Zero Inflated model | | [`loglikeobs`](statsmodels.discrete.count_model.zeroinflatedpoisson.loglikeobs#statsmodels.discrete.count_model.ZeroInflatedPoisson.loglikeobs "statsmodels.discrete.count_model.ZeroInflatedPoisson.loglikeobs")(params) | Loglikelihood for observations of Generic Zero Inflated model | | [`pdf`](statsmodels.discrete.count_model.zeroinflatedpoisson.pdf#statsmodels.discrete.count_model.ZeroInflatedPoisson.pdf "statsmodels.discrete.count_model.ZeroInflatedPoisson.pdf")(X) | The probability density (mass) function of the model. | | [`predict`](statsmodels.discrete.count_model.zeroinflatedpoisson.predict#statsmodels.discrete.count_model.ZeroInflatedPoisson.predict "statsmodels.discrete.count_model.ZeroInflatedPoisson.predict")(params[, exog, exog\_infl, exposure, …]) | Predict response variable of a count model given exogenous variables. | | [`score`](statsmodels.discrete.count_model.zeroinflatedpoisson.score#statsmodels.discrete.count_model.ZeroInflatedPoisson.score "statsmodels.discrete.count_model.ZeroInflatedPoisson.score")(params) | Score vector of model. | | [`score_obs`](statsmodels.discrete.count_model.zeroinflatedpoisson.score_obs#statsmodels.discrete.count_model.ZeroInflatedPoisson.score_obs "statsmodels.discrete.count_model.ZeroInflatedPoisson.score_obs")(params) | Generic Zero Inflated model score (gradient) vector of the log-likelihood | #### Attributes | | | | --- | --- | | `endog_names` | Names of endogenous variables | | `exog_names` | Names of exogenous variables | statsmodels statsmodels.tsa.ar_model.ARResults.hqic statsmodels.tsa.ar\_model.ARResults.hqic ======================================== `ARResults.hqic()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/ar_model.html#ARResults.hqic) statsmodels statsmodels.tsa.arima_process.lpol_fima statsmodels.tsa.arima\_process.lpol\_fima ========================================= `statsmodels.tsa.arima_process.lpol_fima(d, n=20)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_process.html#lpol_fima) MA representation of fractional integration \[(1-L)^{-d} for |d|<0.5 or |d|<1 (?)\] | Parameters: | * **d** (*float*) – fractional power * **n** (*int*) – number of terms to calculate, including lag zero | | Returns: | **ma** – coefficients of lag polynomial | | Return type: | array | statsmodels statsmodels.genmod.generalized_linear_model.GLMResults.get_prediction statsmodels.genmod.generalized\_linear\_model.GLMResults.get\_prediction ======================================================================== `GLMResults.get_prediction(exog=None, exposure=None, offset=None, transform=True, linear=False, row_labels=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_linear_model.html#GLMResults.get_prediction) compute prediction results | Parameters: | * **exog** (*array-like**,* *optional*) – The values for which you want to predict. * **transform** (*bool**,* *optional*) – If the model was fit via a formula, do you want to pass exog through the formula. Default is True. E.g., if you fit a model y ~ log(x1) + log(x2), and transform is True, then you can pass a data structure that contains x1 and x2 in their original form. Otherwise, you’d need to log the data first. * **weights** (*array\_like**,* *optional*) – Weights interpreted as in WLS, used for the variance of the predicted residual. * **kwargs** (*args**,*) – Some models can take additional arguments or keywords, see the predict method of the model for the details. | | Returns: | **prediction\_results** – The prediction results instance contains prediction and prediction variance and can on demand calculate confidence intervals and summary tables for the prediction of the mean and of new observations. | | Return type: | [generalized\_linear\_model.PredictionResults](statsmodels.genmod.generalized_linear_model.predictionresults#statsmodels.genmod.generalized_linear_model.PredictionResults "statsmodels.genmod.generalized_linear_model.PredictionResults") | statsmodels statsmodels.genmod.families.links.Logit.deriv statsmodels.genmod.families.links.Logit.deriv ============================================= `Logit.deriv(p)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/links.html#Logit.deriv) Derivative of the logit transform | Parameters: | **p** (*array-like*) – Probabilities | | Returns: | **g’(p)** – Value of the derivative of logit transform at `p` | | Return type: | array | #### Notes g’(p) = 1 / (p \* (1 - p)) Alias for `Logit`: logit = Logit() statsmodels statsmodels.discrete.discrete_model.ProbitResults.bic statsmodels.discrete.discrete\_model.ProbitResults.bic ====================================================== `ProbitResults.bic()` statsmodels statsmodels.sandbox.distributions.extras.SkewNorm2_gen.sf statsmodels.sandbox.distributions.extras.SkewNorm2\_gen.sf ========================================================== `SkewNorm2_gen.sf(x, *args, **kwds)` Survival function (1 - `cdf`) at x of the given RV. | Parameters: | * **x** (*array\_like*) – quantiles * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **sf** – Survival function evaluated at x | | Return type: | array\_like | statsmodels statsmodels.discrete.discrete_model.NegativeBinomialResults.resid statsmodels.discrete.discrete\_model.NegativeBinomialResults.resid ================================================================== `NegativeBinomialResults.resid()` Residuals #### Notes The residuals for Count models are defined as \[y - p\] where \(p = \exp(X\beta)\). Any exposure and offset variables are also handled. statsmodels statsmodels.genmod.cov_struct.CovStruct.initialize statsmodels.genmod.cov\_struct.CovStruct.initialize =================================================== `CovStruct.initialize(model)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/cov_struct.html#CovStruct.initialize) Called by GEE, used by implementations that need additional setup prior to running `fit`. | Parameters: | **model** (*GEE class*) – A reference to the parent GEE class instance. | statsmodels statsmodels.regression.quantile_regression.QuantRegResults.mse_model statsmodels.regression.quantile\_regression.QuantRegResults.mse\_model ====================================================================== `QuantRegResults.mse_model()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/quantile_regression.html#QuantRegResults.mse_model) statsmodels statsmodels.duration.hazard_regression.PHRegResults.get_distribution statsmodels.duration.hazard\_regression.PHRegResults.get\_distribution ====================================================================== `PHRegResults.get_distribution()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/duration/hazard_regression.html#PHRegResults.get_distribution) Returns a scipy distribution object corresponding to the distribution of uncensored endog (duration) values for each case. | Returns: | | | Return type: | A list of objects of type scipy.stats.distributions.rv\_discrete | #### Notes The distributions are obtained from a simple discrete estimate of the survivor function that puts all mass on the observed failure times wihtin a stratum.
programming_docs
statsmodels statsmodels.tsa.statespace.mlemodel.MLEModel.simulation_smoother statsmodels.tsa.statespace.mlemodel.MLEModel.simulation\_smoother ================================================================= `MLEModel.simulation_smoother(simulation_output=None, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEModel.simulation_smoother) Retrieve a simulation smoother for the state space model. | Parameters: | * **simulation\_output** (*int**,* *optional*) – Determines which simulation smoother output is calculated. Default is all (including state and disturbances). * **\*\*kwargs** – Additional keyword arguments, used to set the simulation output. See `set_simulation_output` for more details. | | Returns: | | | Return type: | SimulationSmoothResults | statsmodels statsmodels.regression.linear_model.RegressionResults.condition_number statsmodels.regression.linear\_model.RegressionResults.condition\_number ======================================================================== `RegressionResults.condition_number()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#RegressionResults.condition_number) Return condition number of exogenous matrix. Calculated as ratio of largest to smallest eigenvalue. statsmodels statsmodels.regression.linear_model.GLS.predict statsmodels.regression.linear\_model.GLS.predict ================================================ `GLS.predict(params, exog=None)` Return linear predicted values from a design matrix. | Parameters: | * **params** (*array-like*) – Parameters of a linear model * **exog** (*array-like**,* *optional.*) – Design / exogenous data. Model exog is used if None. | | Returns: | | | Return type: | An array of fitted values | #### Notes If the model has not yet been fit, params is not optional. statsmodels statsmodels.genmod.cov_struct.GlobalOddsRatio.observed_crude_oddsratio statsmodels.genmod.cov\_struct.GlobalOddsRatio.observed\_crude\_oddsratio ========================================================================= `GlobalOddsRatio.observed_crude_oddsratio()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/cov_struct.html#GlobalOddsRatio.observed_crude_oddsratio) To obtain the crude (global) odds ratio, first pool all binary indicators corresponding to a given pair of cut points (c,c’), then calculate the odds ratio for this 2x2 table. The crude odds ratio is the inverse variance weighted average of these odds ratios. Since the covariate effects are ignored, this OR will generally be greater than the stratified OR. statsmodels statsmodels.stats.outliers_influence.OLSInfluence.sigma2_not_obsi statsmodels.stats.outliers\_influence.OLSInfluence.sigma2\_not\_obsi ==================================================================== `OLSInfluence.sigma2_not_obsi()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/outliers_influence.html#OLSInfluence.sigma2_not_obsi) (cached attribute) error variance for all LOOO regressions This is ‘mse\_resid’ from each auxiliary regression. uses results from leave-one-observation-out loop statsmodels statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.from_formula statsmodels.tsa.regime\_switching.markov\_regression.MarkovRegression.from\_formula =================================================================================== `classmethod MarkovRegression.from_formula(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** (*extra arguments*) – These are passed to the model * **kwargs** (*extra keyword arguments*) – These are passed to the model with one exception. The `eval_env` keyword is passed to patsy. It can be either a [`patsy.EvalEnvironment`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.EvalEnvironment "(in patsy v0.5.0+dev)") 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** | | Return type: | 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 statsmodels.sandbox.distributions.extras.NormExpan_gen.entropy statsmodels.sandbox.distributions.extras.NormExpan\_gen.entropy =============================================================== `NormExpan_gen.entropy(*args, **kwds)` Differential entropy of the RV. | Parameters: | * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information). * **loc** (*array\_like**,* *optional*) – Location parameter (default=0). * **scale** (*array\_like**,* *optional* *(**continuous distributions only**)*) – Scale parameter (default=1). | #### Notes Entropy is defined base `e`: ``` >>> drv = rv_discrete(values=((0, 1), (0.5, 0.5))) >>> np.allclose(drv.entropy(), np.log(2.0)) True ``` statsmodels statsmodels.genmod.generalized_linear_model.GLMResults.bic statsmodels.genmod.generalized\_linear\_model.GLMResults.bic ============================================================ `GLMResults.bic()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_linear_model.html#GLMResults.bic) statsmodels statsmodels.discrete.discrete_model.BinaryResults.initialize statsmodels.discrete.discrete\_model.BinaryResults.initialize ============================================================= `BinaryResults.initialize(model, params, **kwd)` statsmodels statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.initialize_steady_state statsmodels.tsa.regime\_switching.markov\_regression.MarkovRegression.initialize\_steady\_state =============================================================================================== `MarkovRegression.initialize_steady_state()` Set initialization of regime probabilities to be steady-state values #### Notes Only valid if there are not time-varying transition probabilities. statsmodels statsmodels.genmod.families.family.NegativeBinomial.resid_anscombe statsmodels.genmod.families.family.NegativeBinomial.resid\_anscombe =================================================================== `NegativeBinomial.resid_anscombe(endog, mu, var_weights=1.0, scale=1.0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/family.html#NegativeBinomial.resid_anscombe) The Anscombe residuals | Parameters: | * **endog** (*array*) – The endogenous response variable * **mu** (*array*) – The inverse of the link function at the linear predicted values. * **var\_weights** (*array-like*) – 1d array of variance (analytic) weights. The default is 1. * **scale** (*float**,* *optional*) – An optional argument to divide the residuals by sqrt(scale). The default is 1. | | Returns: | **resid\_anscombe** – The Anscombe residuals as defined below. | | Return type: | array | #### Notes Anscombe residuals for Negative Binomial are the same as for Binomial upon setting \(n=-\frac{1}{\alpha}\). Due to the negative value of \(-\alpha\*Y\) the representation with the hypergeometric function \(H2F1(x) = hyp2f1(2/3.,1/3.,5/3.,x)\) is advantageous \[resid\\_anscombe\_i = \frac{3}{2} \* (Y\_i^(2/3)\*H2F1(-\alpha\*Y\_i) - \mu\_i^(2/3)\*H2F1(-\alpha\*\mu\_i)) / (\mu\_i \* (1+\alpha\*\mu\_i) \* scale^3)^(1/6) \* \sqrt(var\\_weights)\] Note that for the (unregularized) Beta function, one has \(Beta(z,a,b) = z^a/a \* H2F1(a,1-b,a+1,z)\) statsmodels statsmodels.discrete.discrete_model.Logit.cov_params_func_l1 statsmodels.discrete.discrete\_model.Logit.cov\_params\_func\_l1 ================================================================ `Logit.cov_params_func_l1(likelihood_model, xopt, retvals)` Computes cov\_params on a reduced parameter space corresponding to the nonzero parameters resulting from the l1 regularized fit. Returns a full cov\_params matrix, with entries corresponding to zero’d values set to np.nan. statsmodels statsmodels.regression.recursive_ls.RecursiveLS.untransform_params statsmodels.regression.recursive\_ls.RecursiveLS.untransform\_params ==================================================================== `RecursiveLS.untransform_params(constrained)` Transform constrained parameters used in likelihood evaluation to unconstrained parameters used by the optimizer | Parameters: | **constrained** (*array\_like*) – Array of constrained parameters used in likelihood evalution, to be transformed. | | Returns: | **unconstrained** – Array of unconstrained parameters used by the optimizer. | | Return type: | array\_like | #### Notes This is a noop in the base class, subclasses should override where appropriate. statsmodels statsmodels.tsa.vector_ar.var_model.VARResults.orth_ma_rep statsmodels.tsa.vector\_ar.var\_model.VARResults.orth\_ma\_rep ============================================================== `VARResults.orth_ma_rep(maxn=10, P=None)` Compute orthogonalized MA coefficient matrices using P matrix such that \(\Sigma\_u = PP^\prime\). P defaults to the Cholesky decomposition of \(\Sigma\_u\) | Parameters: | * **maxn** (*int*) – Number of coefficient matrices to compute * **P** (*ndarray* *(**k x k**)**,* *optional*) – Matrix such that Sigma\_u = PP’, defaults to Cholesky descomp | | Returns: | **coefs** | | Return type: | ndarray (maxn x k x k) | statsmodels statsmodels.sandbox.distributions.transformed.TransfTwo_gen.logpdf statsmodels.sandbox.distributions.transformed.TransfTwo\_gen.logpdf =================================================================== `TransfTwo_gen.logpdf(x, *args, **kwds)` Log of the probability density function at x of the given RV. This uses a more numerically accurate calculation if available. | Parameters: | * **x** (*array\_like*) – quantiles * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **logpdf** – Log of the probability density function evaluated at x | | Return type: | array\_like | statsmodels statsmodels.tsa.arima_model.ARIMAResults.summary statsmodels.tsa.arima\_model.ARIMAResults.summary ================================================= `ARIMAResults.summary(alpha=0.05)` Summarize the Model | Parameters: | **alpha** (*float**,* *optional*) – Significance level for the confidence intervals. | | Returns: | **smry** – This holds the summary table and text, which can be printed or converted to various output formats. | | Return type: | Summary instance | See also [`statsmodels.iolib.summary.Summary`](statsmodels.iolib.summary.summary#statsmodels.iolib.summary.Summary "statsmodels.iolib.summary.Summary") statsmodels statsmodels.sandbox.regression.gmm.GMMResults.conf_int statsmodels.sandbox.regression.gmm.GMMResults.conf\_int ======================================================= `GMMResults.conf_int(alpha=0.05, cols=None, method='default')` Returns the confidence interval of the fitted parameters. | Parameters: | * **alpha** (*float**,* *optional*) – The significance level for the confidence interval. ie., The default `alpha` = .05 returns a 95% confidence interval. * **cols** (*array-like**,* *optional*) – `cols` specifies which confidence intervals to return * **method** (*string*) – Not Implemented Yet Method to estimate the confidence\_interval. “Default” : uses self.bse which is based on inverse Hessian for MLE “hjjh” : “jac” : “boot-bse” “boot\_quant” “profile” | | Returns: | **conf\_int** – Each row contains [lower, upper] limits of the confidence interval for the corresponding parameter. The first column contains all lower, the second column contains all upper limits. | | Return type: | array | #### Examples ``` >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> results.conf_int() array([[-5496529.48322745, -1467987.78596704], [ -177.02903529, 207.15277984], [ -0.1115811 , 0.03994274], [ -3.12506664, -0.91539297], [ -1.5179487 , -0.54850503], [ -0.56251721, 0.460309 ], [ 798.7875153 , 2859.51541392]]) ``` ``` >>> results.conf_int(cols=(2,3)) array([[-0.1115811 , 0.03994274], [-3.12506664, -0.91539297]]) ``` #### Notes The confidence interval is based on the standard normal distribution. Models wish to use a different distribution should overwrite this method. statsmodels statsmodels.tsa.regime_switching.markov_regression.MarkovRegression.initialize_known statsmodels.tsa.regime\_switching.markov\_regression.MarkovRegression.initialize\_known ======================================================================================= `MarkovRegression.initialize_known(probabilities, tol=1e-08)` Set initialization of regime probabilities to use known values statsmodels statsmodels.imputation.mice.MICE statsmodels.imputation.mice.MICE ================================ `class statsmodels.imputation.mice.MICE(model_formula, model_class, data, n_skip=3, init_kwds=None, fit_kwds=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/imputation/mice.html#MICE) Multiple Imputation with Chained Equations. This class can be used to fit most Statsmodels models to data sets with missing values using the ‘multiple imputation with chained equations’ (MICE) approach.. | Parameters: | * **model\_formula** (*string*) – The model formula to be fit to the imputed data sets. This formula is for the ‘analysis model’. * **model\_class** (*statsmodels model*) – The model to be fit to the imputed data sets. This model class if for the ‘analysis model’. * **data** (*MICEData instance*) – MICEData object containing the data set for which missing values will be imputed * **n\_skip** (*int*) – The number of imputed datasets to skip between consecutive imputed datasets that are used for analysis. * **init\_kwds** (*dict-like*) – Dictionary of keyword arguments passed to the init method of the analysis model. * **fit\_kwds** (*dict-like*) – Dictionary of keyword arguments passed to the fit method of the analysis model. | #### Examples Run all MICE steps and obtain results: ``` >>> imp = mice.MICEData(data) >>> fml = 'y ~ x1 + x2 + x3 + x4' >>> mice = mice.MICE(fml, sm.OLS, imp) >>> results = mice.fit(10, 10) >>> print(results.summary()) ``` ``` Results: MICE ================================================================= Method: MICE Sample size: 1000 Model: OLS Scale 1.00 Dependent variable: y Num. imputations 10 ----------------------------------------------------------------- Coef. Std.Err. t P>|t| [0.025 0.975] FMI ----------------------------------------------------------------- Intercept -0.0234 0.0318 -0.7345 0.4626 -0.0858 0.0390 0.0128 x1 1.0305 0.0578 17.8342 0.0000 0.9172 1.1437 0.0309 x2 -0.0134 0.0162 -0.8282 0.4076 -0.0451 0.0183 0.0236 x3 -1.0260 0.0328 -31.2706 0.0000 -1.0903 -0.9617 0.0169 x4 -0.0253 0.0336 -0.7520 0.4521 -0.0911 0.0406 0.0269 ================================================================= ``` Obtain a sequence of fitted analysis models without combining to obtain summary: ``` >>> imp = mice.MICEData(data) >>> fml = 'y ~ x1 + x2 + x3 + x4' >>> mice = mice.MICE(fml, sm.OLS, imp) >>> results = [] >>> for k in range(10): >>> x = mice.next_sample() >>> results.append(x) ``` #### Methods | | | | --- | --- | | [`combine`](statsmodels.imputation.mice.mice.combine#statsmodels.imputation.mice.MICE.combine "statsmodels.imputation.mice.MICE.combine")() | Pools MICE imputation results. | | [`fit`](statsmodels.imputation.mice.mice.fit#statsmodels.imputation.mice.MICE.fit "statsmodels.imputation.mice.MICE.fit")([n\_burnin, n\_imputations]) | Fit a model using MICE. | | [`next_sample`](statsmodels.imputation.mice.mice.next_sample#statsmodels.imputation.mice.MICE.next_sample "statsmodels.imputation.mice.MICE.next_sample")() | Perform one complete MICE iteration. | statsmodels statsmodels.miscmodels.tmodel.TLinearModel.score_obs statsmodels.miscmodels.tmodel.TLinearModel.score\_obs ===================================================== `TLinearModel.score_obs(params, **kwds)` Jacobian/Gradient of log-likelihood evaluated at params for each observation. statsmodels statsmodels.genmod.families.links.CLogLog.deriv2 statsmodels.genmod.families.links.CLogLog.deriv2 ================================================ `CLogLog.deriv2(p)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/links.html#CLogLog.deriv2) Second derivative of the C-Log-Log ink function | Parameters: | **p** (*array-like*) – Mean parameters | | Returns: | **g’‘(p)** – The second derivative of the CLogLog link function | | Return type: | array | statsmodels statsmodels.genmod.cov_struct.CovStruct.summary statsmodels.genmod.cov\_struct.CovStruct.summary ================================================ `CovStruct.summary()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/cov_struct.html#CovStruct.summary) Returns a text summary of the current estimate of the dependence structure. statsmodels statsmodels.discrete.discrete_model.CountResults.predict statsmodels.discrete.discrete\_model.CountResults.predict ========================================================= `CountResults.predict(exog=None, transform=True, *args, **kwargs)` Call self.model.predict with self.params as the first argument. | Parameters: | * **exog** (*array-like**,* *optional*) – The values for which you want to predict. see Notes below. * **transform** (*bool**,* *optional*) – If the model was fit via a formula, do you want to pass exog through the formula. Default is True. E.g., if you fit a model y ~ log(x1) + log(x2), and transform is True, then you can pass a data structure that contains x1 and x2 in their original form. Otherwise, you’d need to log the data first. * **kwargs** (*args**,*) – Some models can take additional arguments or keywords, see the predict method of the model for the details. | | Returns: | **prediction** – See self.model.predict | | Return type: | ndarray, [pandas.Series](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html#pandas.Series "(in pandas v0.22.0)") or [pandas.DataFrame](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html#pandas.DataFrame "(in pandas v0.22.0)") | #### Notes The types of exog that are supported depends on whether a formula was used in the specification of the model. If a formula was used, then exog is processed in the same way as the original data. This transformation needs to have key access to the same variable names, and can be a pandas DataFrame or a dict like object. If no formula was used, then the provided exog needs to have the same number of columns as the original exog in the model. No transformation of the data is performed except converting it to a numpy array. Row indices as in pandas data frames are supported, and added to the returned prediction.
programming_docs
statsmodels statsmodels.tsa.arima_model.ARMA.loglike_kalman statsmodels.tsa.arima\_model.ARMA.loglike\_kalman ================================================= `ARMA.loglike_kalman(params, set_sigma2=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_model.html#ARMA.loglike_kalman) Compute exact loglikelihood for ARMA(p,q) model by the Kalman Filter. statsmodels statsmodels.duration.hazard_regression.PHReg.fit statsmodels.duration.hazard\_regression.PHReg.fit ================================================= `PHReg.fit(groups=None, **args)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/duration/hazard_regression.html#PHReg.fit) Fit a proportional hazards regression model. | Parameters: | * **groups** (*array-like*) – Labels indicating groups of observations that may be dependent. If present, the standard errors account for this dependence. Does not affect fitted values. * **a PHregResults instance.** (*Returns*) – | statsmodels statsmodels.regression.linear_model.GLSAR.fit_regularized statsmodels.regression.linear\_model.GLSAR.fit\_regularized =========================================================== `GLSAR.fit_regularized(method='elastic_net', alpha=0.0, L1_wt=1.0, start_params=None, profile_scale=False, refit=False, **kwargs)` Return a regularized fit to a linear regression model. | Parameters: | * **method** (*string*) – Only the ‘elastic\_net’ approach is currently implemented. * **alpha** (*scalar* *or* *array-like*) – The penalty weight. If a scalar, the same penalty weight applies to all variables in the model. If a vector, it must have the same length as `params`, and contains a penalty weight for each coefficient. * **L1\_wt** (*scalar*) – The fraction of the penalty given to the L1 penalty term. Must be between 0 and 1 (inclusive). If 0, the fit is a ridge fit, if 1 it is a lasso fit. * **start\_params** (*array-like*) – Starting values for `params`. * **profile\_scale** (*bool*) – If True the penalized fit is computed using the profile (concentrated) log-likelihood for the Gaussian model. Otherwise the fit uses the residual sum of squares. * **refit** (*bool*) – If True, the model is refit using only the variables that have non-zero coefficients in the regularized fit. The refitted model is not regularized. * **distributed** (*bool*) – If True, the model uses distributed methods for fitting, will raise an error if True and partitions is None. * **generator** (*function*) – generator used to partition the model, allows for handling of out of memory/parallel computing. * **partitions** (*scalar*) – The number of partitions desired for the distributed estimation. * **threshold** (*scalar* *or* *array-like*) – The threshold below which coefficients are zeroed out, only used for distributed estimation | | Returns: | | | Return type: | A RegularizedResults instance. | #### Notes The elastic net approach closely follows that implemented in the glmnet package in R. The penalty is a combination of L1 and L2 penalties. The function that is minimized is: \[0.5\*RSS/n + alpha\*((1-L1\\_wt)\*|params|\_2^2/2 + L1\\_wt\*|params|\_1)\] where RSS is the usual regression sum of squares, n is the sample size, and \(|\*|\_1\) and \(|\*|\_2\) are the L1 and L2 norms. For WLS and GLS, the RSS is calculated using the whitened endog and exog data. Post-estimation results are based on the same data used to select variables, hence may be subject to overfitting biases. The elastic\_net method uses the following keyword arguments: `maxiter : int` Maximum number of iterations `cnvrg_tol : float` Convergence threshold for line searches `zero_tol : float` Coefficients below this threshold are treated as zero. #### References Friedman, Hastie, Tibshirani (2008). Regularization paths for generalized linear models via coordinate descent. Journal of Statistical Software 33(1), 1-22 Feb 2010. statsmodels statsmodels.discrete.discrete_model.LogitResults.llr statsmodels.discrete.discrete\_model.LogitResults.llr ===================================================== `LogitResults.llr()` statsmodels statsmodels.discrete.discrete_model.ProbitResults.summary2 statsmodels.discrete.discrete\_model.ProbitResults.summary2 =========================================================== `ProbitResults.summary2(yname=None, xname=None, title=None, alpha=0.05, float_format='%.4f')` Experimental function to summarize regression results | Parameters: | * **xname** (*List of strings of length equal to the number of parameters*) – Names of the independent variables (optional) * **yname** (*string*) – Name of the dependent variable (optional) * **title** (*string**,* *optional*) – Title for the top table. If not None, then this replaces the default title * **alpha** (*float*) – significance level for the confidence intervals * **float\_format** (*string*) – print format for floats in parameters summary | | Returns: | **smry** – this holds the summary tables and text, which can be printed or converted to various output formats. | | Return type: | Summary instance | See also [`statsmodels.iolib.summary.Summary`](statsmodels.iolib.summary.summary#statsmodels.iolib.summary.Summary "statsmodels.iolib.summary.Summary") class to hold summary results statsmodels statsmodels.sandbox.distributions.extras.SkewNorm_gen.cdf statsmodels.sandbox.distributions.extras.SkewNorm\_gen.cdf ========================================================== `SkewNorm_gen.cdf(x, *args, **kwds)` Cumulative distribution function of the given RV. | Parameters: | * **x** (*array\_like*) – quantiles * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **cdf** – Cumulative distribution function evaluated at `x` | | Return type: | ndarray | statsmodels statsmodels.tsa.statespace.sarimax.SARIMAXResults.plot_diagnostics statsmodels.tsa.statespace.sarimax.SARIMAXResults.plot\_diagnostics =================================================================== `SARIMAXResults.plot_diagnostics(variable=0, lags=10, fig=None, figsize=None)` Diagnostic plots for standardized residuals of one endogenous variable | Parameters: | * **variable** (*integer**,* *optional*) – Index of the endogenous variable for which the diagnostic plots should be created. Default is 0. * **lags** (*integer**,* *optional*) – Number of lags to include in the correlogram. Default is 10. * **fig** (*Matplotlib Figure instance**,* *optional*) – If given, subplots are created in this figure instead of in a new figure. Note that the 2x2 grid will be created in the provided figure using `fig.add_subplot()`. * **figsize** (*tuple**,* *optional*) – If a figure is created, this argument allows specifying a size. The tuple is (width, height). | #### Notes Produces a 2x2 plot grid with the following plots (ordered clockwise from top left): 1. Standardized residuals over time 2. Histogram plus estimated density of standardized residulas, along with a Normal(0,1) density plotted for reference. 3. Normal Q-Q plot, with Normal reference line. 4. Correlogram See also [`statsmodels.graphics.gofplots.qqplot`](statsmodels.graphics.gofplots.qqplot#statsmodels.graphics.gofplots.qqplot "statsmodels.graphics.gofplots.qqplot"), [`statsmodels.graphics.tsaplots.plot_acf`](statsmodels.graphics.tsaplots.plot_acf#statsmodels.graphics.tsaplots.plot_acf "statsmodels.graphics.tsaplots.plot_acf") statsmodels statsmodels.sandbox.regression.gmm.IVGMMResults.fittedvalues statsmodels.sandbox.regression.gmm.IVGMMResults.fittedvalues ============================================================ `IVGMMResults.fittedvalues()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#IVGMMResults.fittedvalues) statsmodels statsmodels.iolib.table.SimpleTable.as_csv statsmodels.iolib.table.SimpleTable.as\_csv =========================================== `SimpleTable.as_csv(**fmt_dict)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/iolib/table.html#SimpleTable.as_csv) Return string, the table in CSV format. Currently only supports comma separator. statsmodels statsmodels.regression.quantile_regression.QuantRegResults.prsquared statsmodels.regression.quantile\_regression.QuantRegResults.prsquared ===================================================================== `QuantRegResults.prsquared()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/quantile_regression.html#QuantRegResults.prsquared) statsmodels statsmodels.discrete.count_model.GenericZeroInflated.loglike statsmodels.discrete.count\_model.GenericZeroInflated.loglike ============================================================= `GenericZeroInflated.loglike(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/count_model.html#GenericZeroInflated.loglike) Loglikelihood of Generic Zero Inflated model | Parameters: | **params** (*array-like*) – The parameters of the model. | | Returns: | **loglike** – The log-likelihood function of the model evaluated at `params`. See notes. | | Return type: | float | #### Notes \[\ln L=\sum\_{y\_{i}=0}\ln(w\_{i}+(1-w\_{i})\*P\_{main\\_model})+ \sum\_{y\_{i}>0}(\ln(1-w\_{i})+L\_{main\\_model}) where P - pdf of main model, L - loglike function of main model.\] statsmodels statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialP.loglikeobs statsmodels.discrete.count\_model.ZeroInflatedNegativeBinomialP.loglikeobs ========================================================================== `ZeroInflatedNegativeBinomialP.loglikeobs(params)` Loglikelihood for observations of Generic Zero Inflated model | Parameters: | **params** (*array-like*) – The parameters of the model. | | Returns: | **loglike** – The log likelihood for each observation of the model evaluated at `params`. See Notes | | Return type: | ndarray | #### Notes \[\ln L=\ln(w\_{i}+(1-w\_{i})\*P\_{main\\_model})+ \ln(1-w\_{i})+L\_{main\\_model} where P - pdf of main model, L - loglike function of main model.\] for observations \(i=1,...,n\) statsmodels statsmodels.discrete.discrete_model.MultinomialModel.fit statsmodels.discrete.discrete\_model.MultinomialModel.fit ========================================================= `MultinomialModel.fit(start_params=None, method='newton', maxiter=35, full_output=1, disp=1, callback=None, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#MultinomialModel.fit) Fit the model using maximum likelihood. The rest of the docstring is from statsmodels.base.model.LikelihoodModel.fit Fit method for likelihood based models | Parameters: | * **start\_params** (*array-like**,* *optional*) – Initial guess of the solution for the loglikelihood maximization. The default is an array of zeros. * **method** (*str**,* *optional*) – The `method` determines which solver from `scipy.optimize` is used, and it can be chosen from among the following strings: + ’newton’ for Newton-Raphson, ‘nm’ for Nelder-Mead + ’bfgs’ for Broyden-Fletcher-Goldfarb-Shanno (BFGS) + ’lbfgs’ for limited-memory BFGS with optional box constraints + ’powell’ for modified Powell’s method + ’cg’ for conjugate gradient + ’ncg’ for Newton-conjugate gradient + ’basinhopping’ for global basin-hopping solver + ’minimize’ for generic wrapper of scipy minimize (BFGS by default)The explicit arguments in `fit` are passed to the solver, with the exception of the basin-hopping solver. Each solver has several optional arguments that are not the same across solvers. See the notes section below (or scipy.optimize) for the available arguments and for the list of explicit arguments that the basin-hopping solver supports. * **maxiter** (*int**,* *optional*) – The maximum number of iterations to perform. * **full\_output** (*bool**,* *optional*) – Set to True to have all available output in the Results object’s mle\_retvals attribute. The output is dependent on the solver. See LikelihoodModelResults notes section for more information. * **disp** (*bool**,* *optional*) – Set to True to print convergence messages. * **fargs** (*tuple**,* *optional*) – Extra arguments passed to the likelihood function, i.e., loglike(x,\*args) * **callback** (*callable callback**(**xk**)**,* *optional*) – Called after each iteration, as callback(xk), where xk is the current parameter vector. * **retall** (*bool**,* *optional*) – Set to True to return list of solutions at each iteration. Available in Results object’s mle\_retvals attribute. * **skip\_hessian** (*bool**,* *optional*) – If False (default), then the negative inverse hessian is calculated after the optimization. If True, then the hessian will not be calculated. However, it will be available in methods that use the hessian in the optimization (currently only with `“newton”`). * **kwargs** (*keywords*) – All kwargs are passed to the chosen solver with one exception. The following keyword controls what happens after the fit: ``` warn_convergence : bool, optional If True, checks the model for the converged flag. If the converged flag is False, a ConvergenceWarning is issued. ``` | #### Notes The ‘basinhopping’ solver ignores `maxiter`, `retall`, `full_output` explicit arguments. Optional arguments for solvers (see returned Results.mle\_settings): ``` 'newton' tol : float Relative error in params acceptable for convergence. 'nm' -- Nelder Mead xtol : float Relative error in params acceptable for convergence ftol : float Relative error in loglike(params) acceptable for convergence maxfun : int Maximum number of function evaluations to make. 'bfgs' gtol : float Stop when norm of gradient is less than gtol. norm : float Order of norm (np.Inf is max, -np.Inf is min) epsilon If fprime is approximated, use this value for the step size. Only relevant if LikelihoodModel.score is None. 'lbfgs' m : int This many terms are used for the Hessian approximation. factr : float A stop condition that is a variant of relative error. pgtol : float A stop condition that uses the projected gradient. epsilon If fprime is approximated, use this value for the step size. Only relevant if LikelihoodModel.score is None. maxfun : int Maximum number of function evaluations to make. bounds : sequence (min, max) pairs for each element in x, defining the bounds on that parameter. Use None for one of min or max when there is no bound in that direction. 'cg' gtol : float Stop when norm of gradient is less than gtol. norm : float Order of norm (np.Inf is max, -np.Inf is min) epsilon : float If fprime is approximated, use this value for the step size. Can be scalar or vector. Only relevant if Likelihoodmodel.score is None. 'ncg' fhess_p : callable f'(x,*args) Function which computes the Hessian of f times an arbitrary vector, p. Should only be supplied if LikelihoodModel.hessian is None. avextol : float Stop when the average relative error in the minimizer falls below this amount. epsilon : float or ndarray If fhess is approximated, use this value for the step size. Only relevant if Likelihoodmodel.hessian is None. 'powell' xtol : float Line-search error tolerance ftol : float Relative error in loglike(params) for acceptable for convergence. maxfun : int Maximum number of function evaluations to make. start_direc : ndarray Initial direction set. 'basinhopping' niter : integer The number of basin hopping iterations. niter_success : integer Stop the run if the global minimum candidate remains the same for this number of iterations. T : float The "temperature" parameter for the accept or reject criterion. Higher "temperatures" mean that larger jumps in function value will be accepted. For best results `T` should be comparable to the separation (in function value) between local minima. stepsize : float Initial step size for use in the random displacement. interval : integer The interval for how often to update the `stepsize`. minimizer : dict Extra keyword arguments to be passed to the minimizer `scipy.optimize.minimize()`, for example 'method' - the minimization method (e.g. 'L-BFGS-B'), or 'tol' - the tolerance for termination. Other arguments are mapped from explicit argument of `fit`: - `args` <- `fargs` - `jac` <- `score` - `hess` <- `hess` 'minimize' min_method : str, optional Name of minimization method to use. Any method specific arguments can be passed directly. For a list of methods and their arguments, see documentation of `scipy.optimize.minimize`. If no method is specified, then BFGS is used. ``` statsmodels statsmodels.genmod.families.links.Link statsmodels.genmod.families.links.Link ====================================== `class statsmodels.genmod.families.links.Link` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/links.html#Link) A generic link function for one-parameter exponential family. `Link` does nothing, but lays out the methods expected of any subclass. #### Methods | | | | --- | --- | | [`deriv`](statsmodels.genmod.families.links.link.deriv#statsmodels.genmod.families.links.Link.deriv "statsmodels.genmod.families.links.Link.deriv")(p) | Derivative of the link function g’(p). | | [`deriv2`](statsmodels.genmod.families.links.link.deriv2#statsmodels.genmod.families.links.Link.deriv2 "statsmodels.genmod.families.links.Link.deriv2")(p) | Second derivative of the link function g’‘(p) | | [`inverse`](statsmodels.genmod.families.links.link.inverse#statsmodels.genmod.families.links.Link.inverse "statsmodels.genmod.families.links.Link.inverse")(z) | Inverse of the link function. | | [`inverse_deriv`](statsmodels.genmod.families.links.link.inverse_deriv#statsmodels.genmod.families.links.Link.inverse_deriv "statsmodels.genmod.families.links.Link.inverse_deriv")(z) | Derivative of the inverse link function g^(-1)(z). | statsmodels statsmodels.discrete.discrete_model.DiscreteModel.hessian statsmodels.discrete.discrete\_model.DiscreteModel.hessian ========================================================== `DiscreteModel.hessian(params)` The Hessian matrix of the model statsmodels statsmodels.tsa.statespace.structural.UnobservedComponentsResults statsmodels.tsa.statespace.structural.UnobservedComponentsResults ================================================================= `class statsmodels.tsa.statespace.structural.UnobservedComponentsResults(model, params, filter_results, cov_type='opg', **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/structural.html#UnobservedComponentsResults) Class to hold results from fitting an unobserved components model. | Parameters: | **model** (*UnobservedComponents instance*) – The fitted model instance | `specification` *dictionary* – Dictionary including all attributes from the unobserved components model instance. See also [`statsmodels.tsa.statespace.kalman_filter.FilterResults`](statsmodels.tsa.statespace.kalman_filter.filterresults#statsmodels.tsa.statespace.kalman_filter.FilterResults "statsmodels.tsa.statespace.kalman_filter.FilterResults"), [`statsmodels.tsa.statespace.mlemodel.MLEResults`](statsmodels.tsa.statespace.mlemodel.mleresults#statsmodels.tsa.statespace.mlemodel.MLEResults "statsmodels.tsa.statespace.mlemodel.MLEResults") #### Methods | | | | --- | --- | | [`aic`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.aic#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.aic "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.aic")() | (float) Akaike Information Criterion | | [`bic`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.bic#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.bic "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.bic")() | (float) Bayes Information Criterion | | [`bse`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.bse#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.bse "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.bse")() | | | [`conf_int`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.conf_int#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.conf_int "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.conf_int")([alpha, cols, method]) | Returns the confidence interval of the fitted parameters. | | [`cov_params`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.cov_params#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.cov_params "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.cov_params")([r\_matrix, column, scale, cov\_p, …]) | Returns the variance/covariance matrix. | | [`cov_params_approx`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.cov_params_approx#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.cov_params_approx "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.cov_params_approx")() | (array) The variance / covariance matrix. | | [`cov_params_oim`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.cov_params_oim#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.cov_params_oim "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.cov_params_oim")() | (array) The variance / covariance matrix. | | [`cov_params_opg`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.cov_params_opg#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.cov_params_opg "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.cov_params_opg")() | (array) The variance / covariance matrix. | | [`cov_params_robust`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.cov_params_robust#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.cov_params_robust "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.cov_params_robust")() | (array) The QMLE variance / covariance matrix. | | [`cov_params_robust_approx`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.cov_params_robust_approx#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.cov_params_robust_approx "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.cov_params_robust_approx")() | (array) The QMLE variance / covariance matrix. | | [`cov_params_robust_oim`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.cov_params_robust_oim#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.cov_params_robust_oim "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.cov_params_robust_oim")() | (array) The QMLE variance / covariance matrix. | | [`f_test`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.f_test#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.f_test "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.f_test")(r\_matrix[, cov\_p, scale, invcov]) | Compute the F-test for a joint linear hypothesis. | | [`fittedvalues`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.fittedvalues#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.fittedvalues "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.fittedvalues")() | (array) The predicted values of the model. | | [`forecast`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.forecast#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.forecast "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.forecast")([steps]) | Out-of-sample forecasts | | [`get_forecast`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.get_forecast#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.get_forecast "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.get_forecast")([steps]) | Out-of-sample forecasts | | [`get_prediction`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.get_prediction#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.get_prediction "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.get_prediction")([start, end, dynamic, index, …]) | In-sample prediction and out-of-sample forecasting | | [`hqic`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.hqic#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.hqic "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.hqic")() | (float) Hannan-Quinn Information Criterion | | [`impulse_responses`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.impulse_responses#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.impulse_responses "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.impulse_responses")([steps, impulse, …]) | Impulse response function | | [`info_criteria`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.info_criteria#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.info_criteria "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.info_criteria")(criteria[, method]) | Information criteria | | [`initialize`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.initialize#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.initialize "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.initialize")(model, params, \*\*kwd) | | | [`llf`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.llf#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.llf "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.llf")() | (float) The value of the log-likelihood function evaluated at `params`. | | [`llf_obs`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.llf_obs#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.llf_obs "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.llf_obs")() | (float) The value of the log-likelihood function evaluated at `params`. | | [`load`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.load#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.load "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.load")(fname) | load a pickle, (class method) | | [`loglikelihood_burn`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.loglikelihood_burn#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.loglikelihood_burn "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.loglikelihood_burn")() | (float) The number of observations during which the likelihood is not evaluated. | | [`normalized_cov_params`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.normalized_cov_params#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.normalized_cov_params "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.normalized_cov_params")() | | | [`plot_components`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.plot_components#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.plot_components "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.plot_components")([which, alpha, observed, …]) | Plot the estimated components of the model. | | [`plot_diagnostics`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.plot_diagnostics#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.plot_diagnostics "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.plot_diagnostics")([variable, lags, fig, figsize]) | Diagnostic plots for standardized residuals of one endogenous variable | | [`predict`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.predict#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.predict "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.predict")([start, end, dynamic]) | In-sample prediction and out-of-sample forecasting | | [`pvalues`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.pvalues#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.pvalues "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.pvalues")() | (array) The p-values associated with the z-statistics of the coefficients. | | [`remove_data`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.remove_data#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.remove_data "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.remove_data")() | remove data arrays, all nobs arrays from result and model | | [`resid`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.resid#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.resid "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.resid")() | (array) The model residuals. | | [`save`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.save#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.save "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.save")(fname[, remove\_data]) | save a pickle of this instance | | [`simulate`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.simulate#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.simulate "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.simulate")(nsimulations[, measurement\_shocks, …]) | Simulate a new time series following the state space model | | [`summary`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.summary#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.summary "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.summary")([alpha, start]) | Summarize the Model | | [`t_test`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.t_test#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.t_test "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.t_test")(r\_matrix[, cov\_p, scale, use\_t]) | Compute a t-test for a each linear hypothesis of the form Rb = q | | [`t_test_pairwise`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.t_test_pairwise#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.t_test_pairwise "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.t_test_pairwise")(term\_name[, method, alpha, …]) | perform pairwise t\_test with multiple testing corrected p-values | | [`test_heteroskedasticity`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.test_heteroskedasticity#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.test_heteroskedasticity "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.test_heteroskedasticity")(method[, …]) | Test for heteroskedasticity of standardized residuals | | [`test_normality`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.test_normality#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.test_normality "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.test_normality")(method) | Test for normality of standardized residuals. | | [`test_serial_correlation`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.test_serial_correlation#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.test_serial_correlation "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.test_serial_correlation")(method[, lags]) | Ljung-box test for no serial correlation of standardized residuals | | [`tvalues`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.tvalues#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.tvalues "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.tvalues")() | Return the t-statistic for a given parameter estimate. | | [`wald_test`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.wald_test#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.wald_test "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.wald_test")(r\_matrix[, cov\_p, scale, invcov, …]) | Compute a Wald-test for a joint linear hypothesis. | | [`wald_test_terms`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.wald_test_terms#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.wald_test_terms "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.wald_test_terms")([skip\_single, …]) | Compute a sequence of Wald tests for terms over multiple columns | | [`zvalues`](statsmodels.tsa.statespace.structural.unobservedcomponentsresults.zvalues#statsmodels.tsa.statespace.structural.UnobservedComponentsResults.zvalues "statsmodels.tsa.statespace.structural.UnobservedComponentsResults.zvalues")() | (array) The z-statistics for the coefficients. | #### Attributes | | | | --- | --- | | `autoregressive` | Estimates of unobserved autoregressive component | | `cycle` | Estimates of unobserved cycle component | | `freq_seasonal` | Estimates of unobserved frequency domain seasonal component(s) | | `level` | Estimates of unobserved level component | | `regression_coefficients` | Estimates of unobserved regression coefficients | | `seasonal` | Estimates of unobserved seasonal component | | `trend` | Estimates of of unobserved trend component | | `use_t` | |
programming_docs
statsmodels statsmodels.tsa.vector_ar.var_model.VARProcess.is_stable statsmodels.tsa.vector\_ar.var\_model.VARProcess.is\_stable =========================================================== `VARProcess.is_stable(verbose=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/var_model.html#VARProcess.is_stable) Determine stability based on model coefficients | Parameters: | **verbose** (*bool*) – Print eigenvalues of the VAR(1) companion | #### Notes Checks if det(I - Az) = 0 for any mod(z) <= 1, so all the eigenvalues of the companion matrix must lie outside the unit circle statsmodels statsmodels.discrete.discrete_model.GeneralizedPoissonResults.get_margeff statsmodels.discrete.discrete\_model.GeneralizedPoissonResults.get\_margeff =========================================================================== `GeneralizedPoissonResults.get_margeff(at='overall', method='dydx', atexog=None, dummy=False, count=False)` Get marginal effects of the fitted model. | Parameters: | * **at** (*str**,* *optional*) – Options are: + ’overall’, The average of the marginal effects at each observation. + ’mean’, The marginal effects at the mean of each regressor. + ’median’, The marginal effects at the median of each regressor. + ’zero’, The marginal effects at zero for each regressor. + ’all’, The marginal effects at each observation. If `at` is all only margeff will be available from the returned object.Note that if `exog` is specified, then marginal effects for all variables not specified by `exog` are calculated using the `at` option. * **method** (*str**,* *optional*) – Options are: + ’dydx’ - dy/dx - No transformation is made and marginal effects are returned. This is the default. + ’eyex’ - estimate elasticities of variables in `exog` – d(lny)/d(lnx) + ’dyex’ - estimate semielasticity – dy/d(lnx) + ’eydx’ - estimate semeilasticity – d(lny)/dxNote that tranformations are done after each observation is calculated. Semi-elasticities for binary variables are computed using the midpoint method. ‘dyex’ and ‘eyex’ do not make sense for discrete variables. * **atexog** (*array-like**,* *optional*) – Optionally, you can provide the exogenous variables over which to get the marginal effects. This should be a dictionary with the key as the zero-indexed column number and the value of the dictionary. Default is None for all independent variables less the constant. * **dummy** (*bool**,* *optional*) – If False, treats binary variables (if present) as continuous. This is the default. Else if True, treats binary variables as changing from 0 to 1. Note that any variable that is either 0 or 1 is treated as binary. Each binary variable is treated separately for now. * **count** (*bool**,* *optional*) – If False, treats count variables (if present) as continuous. This is the default. Else if True, the marginal effect is the change in probabilities when each observation is increased by one. | | Returns: | **DiscreteMargins** – Returns an object that holds the marginal effects, standard errors, confidence intervals, etc. See `statsmodels.discrete.discrete_margins.DiscreteMargins` for more information. | | Return type: | marginal effects instance | #### Notes When using after Poisson, returns the expected number of events per period, assuming that the model is loglinear. statsmodels statsmodels.tsa.statespace.structural.UnobservedComponentsResults.remove_data statsmodels.tsa.statespace.structural.UnobservedComponentsResults.remove\_data ============================================================================== `UnobservedComponentsResults.remove_data()` remove data arrays, all nobs arrays from result and model This reduces the size of the instance, so it can be pickled with less memory. Currently tested for use with predict from an unpickled results and model instance. Warning Since data and some intermediate results have been removed calculating new statistics that require them will raise exceptions. The exception will occur the first time an attribute is accessed that has been set to None. Not fully tested for time series models, tsa, and might delete too much for prediction or not all that would be possible. The lists of arrays to delete are maintained as attributes of the result and model instance, except for cached values. These lists could be changed before calling remove\_data. The attributes to remove are named in: `model._data_attr : arrays attached to both the model instance` and the results instance with the same attribute name. `result.data_in_cache : arrays that may exist as values in` result.\_cache (TODO : should privatize name) `result._data_attr_model : arrays attached to the model` instance but not to the results instance statsmodels statsmodels.tsa.statespace.varmax.VARMAX.prepare_data statsmodels.tsa.statespace.varmax.VARMAX.prepare\_data ====================================================== `VARMAX.prepare_data()` Prepare data for use in the state space representation statsmodels statsmodels.sandbox.stats.multicomp.GroupsStats.groupdemean statsmodels.sandbox.stats.multicomp.GroupsStats.groupdemean =========================================================== `GroupsStats.groupdemean()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/multicomp.html#GroupsStats.groupdemean) statsmodels statsmodels.tsa.statespace.varmax.VARMAXResults.remove_data statsmodels.tsa.statespace.varmax.VARMAXResults.remove\_data ============================================================ `VARMAXResults.remove_data()` remove data arrays, all nobs arrays from result and model This reduces the size of the instance, so it can be pickled with less memory. Currently tested for use with predict from an unpickled results and model instance. Warning Since data and some intermediate results have been removed calculating new statistics that require them will raise exceptions. The exception will occur the first time an attribute is accessed that has been set to None. Not fully tested for time series models, tsa, and might delete too much for prediction or not all that would be possible. The lists of arrays to delete are maintained as attributes of the result and model instance, except for cached values. These lists could be changed before calling remove\_data. The attributes to remove are named in: `model._data_attr : arrays attached to both the model instance` and the results instance with the same attribute name. `result.data_in_cache : arrays that may exist as values in` result.\_cache (TODO : should privatize name) `result._data_attr_model : arrays attached to the model` instance but not to the results instance statsmodels statsmodels.tools.eval_measures.medianabs statsmodels.tools.eval\_measures.medianabs ========================================== `statsmodels.tools.eval_measures.medianabs(x1, x2, axis=0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tools/eval_measures.html#medianabs) median absolute error | Parameters: | * **x2** (*x1**,*) – The performance measure depends on the difference between these two arrays. * **axis** (*int*) – axis along which the summary statistic is calculated | | Returns: | **medianabs** – median absolute difference along given axis. | | Return type: | ndarray or float | #### Notes If `x1` and `x2` have different shapes, then they need to broadcast. This uses `numpy.asanyarray` to convert the input. Whether this is the desired result or not depends on the array subclass. statsmodels statsmodels.iolib.table.SimpleTable.as_latex_tabular statsmodels.iolib.table.SimpleTable.as\_latex\_tabular ====================================================== `SimpleTable.as_latex_tabular(center=True, **fmt_dict)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/iolib/table.html#SimpleTable.as_latex_tabular) Return string, the table as a LaTeX tabular environment. Note: will require the booktabs package. statsmodels statsmodels.tsa.regime_switching.markov_autoregression.MarkovAutoregression.initialize_steady_state statsmodels.tsa.regime\_switching.markov\_autoregression.MarkovAutoregression.initialize\_steady\_state ======================================================================================================= `MarkovAutoregression.initialize_steady_state()` Set initialization of regime probabilities to be steady-state values #### Notes Only valid if there are not time-varying transition probabilities. statsmodels statsmodels.stats.power.TTestPower statsmodels.stats.power.TTestPower ================================== `class statsmodels.stats.power.TTestPower(**kwds)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/power.html#TTestPower) Statistical Power calculations for one sample or paired sample t-test #### Methods | | | | --- | --- | | [`plot_power`](statsmodels.stats.power.ttestpower.plot_power#statsmodels.stats.power.TTestPower.plot_power "statsmodels.stats.power.TTestPower.plot_power")([dep\_var, nobs, effect\_size, …]) | plot power with number of observations or effect size on x-axis | | [`power`](statsmodels.stats.power.ttestpower.power#statsmodels.stats.power.TTestPower.power "statsmodels.stats.power.TTestPower.power")(effect\_size, nobs, alpha[, df, …]) | Calculate the power of a t-test for one sample or paired samples. | | [`solve_power`](statsmodels.stats.power.ttestpower.solve_power#statsmodels.stats.power.TTestPower.solve_power "statsmodels.stats.power.TTestPower.solve_power")([effect\_size, nobs, alpha, …]) | solve for any one parameter of the power of a one sample t-test | statsmodels statsmodels.regression.linear_model.OLSResults.rsquared statsmodels.regression.linear\_model.OLSResults.rsquared ======================================================== `OLSResults.rsquared()` statsmodels statsmodels.discrete.discrete_model.LogitResults.t_test statsmodels.discrete.discrete\_model.LogitResults.t\_test ========================================================= `LogitResults.t_test(r_matrix, cov_p=None, scale=None, use_t=None)` Compute a t-test for a each linear hypothesis of the form Rb = q | Parameters: | * **r\_matrix** (*array-like**,* *str**,* *tuple*) – + array : If an array is given, a p x k 2d array or length k 1d array specifying the linear restrictions. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q). If q is given, can be either a scalar or a length p row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – An optional `scale` to use. Default is the scale specified by the model fit. * **use\_t** (*bool**,* *optional*) – If use\_t is None, then the default of the model is used. If use\_t is True, then the p-values are based on the t distribution. If use\_t is False, then the p-values are based on the normal distribution. | | Returns: | **res** – The results for the test are attributes of this results instance. The available results have the same elements as the parameter table in `summary()`. | | Return type: | ContrastResults instance | #### Examples ``` >>> import numpy as np >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> r = np.zeros_like(results.params) >>> r[5:] = [1,-1] >>> print(r) [ 0. 0. 0. 0. 0. 1. -1.] ``` r tests that the coefficients on the 5th and 6th independent variable are the same. ``` >>> T_test = results.t_test(r) >>> print(T_test) Test for Constraints ============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------ c0 -1829.2026 455.391 -4.017 0.003 -2859.368 -799.037 ============================================================================== >>> T_test.effect -1829.2025687192481 >>> T_test.sd 455.39079425193762 >>> T_test.tvalue -4.0167754636411717 >>> T_test.pvalue 0.0015163772380899498 ``` Alternatively, you can specify the hypothesis tests using a string ``` >>> from statsmodels.formula.api import ols >>> dta = sm.datasets.longley.load_pandas().data >>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' >>> results = ols(formula, dta).fit() >>> hypotheses = 'GNPDEFL = GNP, UNEMP = 2, YEAR/1829 = 1' >>> t_test = results.t_test(hypotheses) >>> print(t_test) Test for Constraints ============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------ c0 15.0977 84.937 0.178 0.863 -177.042 207.238 c1 -2.0202 0.488 -8.231 0.000 -3.125 -0.915 c2 1.0001 0.249 0.000 1.000 0.437 1.563 ============================================================================== ``` See also [`tvalues`](statsmodels.discrete.discrete_model.logitresults.tvalues#statsmodels.discrete.discrete_model.LogitResults.tvalues "statsmodels.discrete.discrete_model.LogitResults.tvalues") individual t statistics [`f_test`](statsmodels.discrete.discrete_model.logitresults.f_test#statsmodels.discrete.discrete_model.LogitResults.f_test "statsmodels.discrete.discrete_model.LogitResults.f_test") for F tests [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") statsmodels statsmodels.graphics.plot_grids.scatter_ellipse statsmodels.graphics.plot\_grids.scatter\_ellipse ================================================= `statsmodels.graphics.plot_grids.scatter_ellipse(data, level=0.9, varnames=None, ell_kwds=None, plot_kwds=None, add_titles=False, keep_ticks=False, fig=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/graphics/plot_grids.html#scatter_ellipse) Create a grid of scatter plots with confidence ellipses. ell\_kwds, plot\_kdes not used yet looks ok with 5 or 6 variables, too crowded with 8, too empty with 1 | Parameters: | * **data** (*array\_like*) – Input data. * **level** (*scalar**,* *optional*) – Default is 0.9. * **varnames** (*list of str**,* *optional*) – Variable names. Used for y-axis labels, and if `add_titles` is True also for titles. If not given, integers 1..data.shape[1] are used. * **ell\_kwds** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")*,* *optional*) – UNUSED * **plot\_kwds** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")*,* *optional*) – UNUSED * **add\_titles** (*bool**,* *optional*) – Whether or not to add titles to each subplot. Default is False. Titles are constructed from `varnames`. * **keep\_ticks** (*bool**,* *optional*) – If False (default), remove all axis ticks. * **fig** (*Matplotlib figure instance**,* *optional*) – If given, this figure is simply returned. Otherwise a new figure is created. | | Returns: | **fig** – If `fig` is None, the created figure. Otherwise `fig` itself. | | Return type: | Matplotlib figure instance | statsmodels statsmodels.discrete.discrete_model.BinaryResults.prsquared statsmodels.discrete.discrete\_model.BinaryResults.prsquared ============================================================ `BinaryResults.prsquared()` statsmodels statsmodels.genmod.cov_struct.Autoregressive.initialize statsmodels.genmod.cov\_struct.Autoregressive.initialize ======================================================== `Autoregressive.initialize(model)` Called by GEE, used by implementations that need additional setup prior to running `fit`. | Parameters: | **model** (*GEE class*) – A reference to the parent GEE class instance. | statsmodels statsmodels.duration.hazard_regression.PHRegResults.llf statsmodels.duration.hazard\_regression.PHRegResults.llf ======================================================== `PHRegResults.llf()` statsmodels statsmodels.regression.quantile_regression.QuantRegResults.compare_lr_test statsmodels.regression.quantile\_regression.QuantRegResults.compare\_lr\_test ============================================================================= `QuantRegResults.compare_lr_test(restricted, large_sample=False)` Likelihood ratio test to test whether restricted model is correct | Parameters: | * **restricted** (*Result instance*) – The restricted model is assumed to be nested in the current model. The result instance of the restricted model is required to have two attributes, residual sum of squares, `ssr`, residual degrees of freedom, `df_resid`. * **large\_sample** (*bool*) – Flag indicating whether to use a heteroskedasticity robust version of the LR test, which is a modified LM test. | | Returns: | * **lr\_stat** (*float*) – likelihood ratio, chisquare distributed with df\_diff degrees of freedom * **p\_value** (*float*) – p-value of the test statistic * **df\_diff** (*int*) – degrees of freedom of the restriction, i.e. difference in df between models | #### Notes The exact likelihood ratio is valid for homoskedastic data, and is defined as \[D=-2\log\left(\frac{\mathcal{L}\_{null}} {\mathcal{L}\_{alternative}}\right)\] where \(\mathcal{L}\) is the likelihood of the model. With \(D\) distributed as chisquare with df equal to difference in number of parameters or equivalently difference in residual degrees of freedom. The large sample version of the likelihood ratio is defined as \[D=n s^{\prime}S^{-1}s\] where \(s=n^{-1}\sum\_{i=1}^{n} s\_{i}\) \[s\_{i} = x\_{i,alternative} \epsilon\_{i,null}\] is the average score of the model evaluated using the residuals from null model and the regressors from the alternative model and \(S\) is the covariance of the scores, \(s\_{i}\). The covariance of the scores is estimated using the same estimator as in the alternative model. This test compares the loglikelihood of the two models. This may not be a valid test, if there is unspecified heteroscedasticity or correlation. This method will issue a warning if this is detected but still return the results without taking unspecified heteroscedasticity or correlation into account. This test compares the loglikelihood of the two models. This may not be a valid test, if there is unspecified heteroscedasticity or correlation. This method will issue a warning if this is detected but still return the results without taking unspecified heteroscedasticity or correlation into account. is the average score of the model evaluated using the residuals from null model and the regressors from the alternative model and \(S\) is the covariance of the scores, \(s\_{i}\). The covariance of the scores is estimated using the same estimator as in the alternative model. TODO: put into separate function, needs tests statsmodels statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialP.pdf statsmodels.discrete.count\_model.ZeroInflatedNegativeBinomialP.pdf =================================================================== `ZeroInflatedNegativeBinomialP.pdf(X)` The probability density (mass) function of the model. statsmodels statsmodels.tsa.statespace.mlemodel.MLEModel.initialize_stationary statsmodels.tsa.statespace.mlemodel.MLEModel.initialize\_stationary =================================================================== `MLEModel.initialize_stationary()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEModel.initialize_stationary)
programming_docs
statsmodels statsmodels.genmod.families.links.cauchy.inverse_deriv statsmodels.genmod.families.links.cauchy.inverse\_deriv ======================================================= `cauchy.inverse_deriv(z)` Derivative of the inverse of the CDF transformation link function | Parameters: | **z** (*array*) – The inverse of the link function at `p` | | Returns: | **g^(-1)’(z)** – The value of the derivative of the inverse of the logit function | | Return type: | array | statsmodels statsmodels.tsa.statespace.mlemodel.MLEResults.save statsmodels.tsa.statespace.mlemodel.MLEResults.save =================================================== `MLEResults.save(fname, remove_data=False)` save a pickle of this instance | Parameters: | * **fname** (*string* *or* *filehandle*) – fname can be a string to a file path or filename, or a filehandle. * **remove\_data** (*bool*) – If False (default), then the instance is pickled without changes. If True, then all arrays with length nobs are set to None before pickling. See the remove\_data method. In some cases not all arrays will be set to None. | #### Notes If remove\_data is true and the model result does not implement a remove\_data method then this will raise an exception. statsmodels statsmodels.sandbox.regression.gmm.NonlinearIVGMM.calc_weightmatrix statsmodels.sandbox.regression.gmm.NonlinearIVGMM.calc\_weightmatrix ==================================================================== `NonlinearIVGMM.calc_weightmatrix(moms, weights_method='cov', wargs=(), params=None)` calculate omega or the weighting matrix | Parameters: | * **moms** (*array*) – moment conditions (nobs x nmoms) for all observations evaluated at a parameter value * **weights\_method** (*string 'cov'*) – If method=’cov’ is cov then the matrix is calculated as simple covariance of the moment conditions. see fit method for available aoptions for the weight and covariance matrix * **wargs** (*tuple* *or* [dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")) – parameters that are required by some kernel methods to estimate the long-run covariance. Not used yet. | | Returns: | **w** – estimate for the weighting matrix or covariance of the moment condition | | Return type: | array (nmoms, nmoms) | #### Notes currently a constant cutoff window is used TODO: implement long-run cov estimators, kernel-based Newey-West Andrews Andrews-Moy???? #### References Greene Hansen, Bruce statsmodels statsmodels.discrete.count_model.GenericZeroInflated.initialize statsmodels.discrete.count\_model.GenericZeroInflated.initialize ================================================================ `GenericZeroInflated.initialize()` Initialize is called by statsmodels.model.LikelihoodModel.\_\_init\_\_ and should contain any preprocessing that needs to be done for a model. statsmodels statsmodels.stats.contingency_tables.SquareTable.test_ordinal_association statsmodels.stats.contingency\_tables.SquareTable.test\_ordinal\_association ============================================================================ `SquareTable.test_ordinal_association(row_scores=None, col_scores=None)` Assess independence between two ordinal variables. This is the ‘linear by linear’ association test, which uses weights or scores to target the test to have more power against ordered alternatives. | Parameters: | * **row\_scores** (*array-like*) – An array of numeric row scores * **col\_scores** (*array-like*) – An array of numeric column scores | | Returns: | * *A bunch with the following attributes* * **statistic** (*float*) – The test statistic. * **null\_mean** (*float*) – The expected value of the test statistic under the null hypothesis. * **null\_sd** (*float*) – The standard deviation of the test statistic under the null hypothesis. * **zscore** (*float*) – The Z-score for the test statistic. * **pvalue** (*float*) – The p-value for the test. | #### Notes The scores define the trend to which the test is most sensitive. Using the default row and column scores gives the Cochran-Armitage trend test. statsmodels statsmodels.regression.linear_model.RegressionResults.cov_HC1 statsmodels.regression.linear\_model.RegressionResults.cov\_HC1 =============================================================== `RegressionResults.cov_HC1()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#RegressionResults.cov_HC1) See statsmodels.RegressionResults statsmodels statsmodels.miscmodels.tmodel.TLinearModel.from_formula statsmodels.miscmodels.tmodel.TLinearModel.from\_formula ======================================================== `classmethod TLinearModel.from_formula(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** (*extra arguments*) – These are passed to the model * **kwargs** (*extra keyword arguments*) – These are passed to the model with one exception. The `eval_env` keyword is passed to patsy. It can be either a [`patsy.EvalEnvironment`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.EvalEnvironment "(in patsy v0.5.0+dev)") 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** | | Return type: | 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 statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.pdf statsmodels.discrete.count\_model.ZeroInflatedGeneralizedPoisson.pdf ==================================================================== `ZeroInflatedGeneralizedPoisson.pdf(X)` The probability density (mass) function of the model. statsmodels statsmodels.sandbox.distributions.transformed.TransfTwo_gen.var statsmodels.sandbox.distributions.transformed.TransfTwo\_gen.var ================================================================ `TransfTwo_gen.var(*args, **kwds)` Variance of the distribution. | Parameters: | * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **var** – the variance of the distribution | | Return type: | float | statsmodels statsmodels.tsa.statespace.mlemodel.MLEResults.predict statsmodels.tsa.statespace.mlemodel.MLEResults.predict ====================================================== `MLEResults.predict(start=None, end=None, dynamic=False, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEResults.predict) In-sample prediction and out-of-sample forecasting | Parameters: | * **start** (*int**,* *str**, or* *datetime**,* *optional*) – Zero-indexed observation number at which to start forecasting, i.e., the first forecast is start. Can also be a date string to parse or a datetime type. Default is the the zeroth observation. * **end** (*int**,* *str**, or* *datetime**,* *optional*) – Zero-indexed observation number at which to end forecasting, i.e., the last forecast is end. Can also be a date string to parse or a datetime type. However, if the dates index does not have a fixed frequency, end must be an integer index if you want out of sample prediction. Default is the last observation in the sample. * **dynamic** (*boolean**,* *int**,* *str**, or* *datetime**,* *optional*) – Integer offset relative to `start` at which to begin dynamic prediction. Can also be an absolute date string to parse or a datetime type (these are not interpreted as offsets). Prior to this observation, true endogenous values will be used for prediction; starting with this observation and continuing through the end of prediction, forecasted endogenous values will be used instead. * **\*\*kwargs** – Additional arguments may required for forecasting beyond the end of the sample. See `FilterResults.predict` for more details. | | Returns: | **forecast** – Array of out of in-sample predictions and / or out-of-sample forecasts. An (npredict x k\_endog) array. | | Return type: | array | statsmodels statsmodels.genmod.families.family.Poisson.deviance statsmodels.genmod.families.family.Poisson.deviance =================================================== `Poisson.deviance(endog, mu, var_weights=1.0, freq_weights=1.0, scale=1.0)` The deviance function evaluated at (endog, mu, var\_weights, freq\_weights, scale) for the distribution. Deviance is usually defined as twice the loglikelihood ratio. | Parameters: | * **endog** (*array-like*) – The endogenous response variable * **mu** (*array-like*) – The inverse of the link function at the linear predicted values. * **var\_weights** (*array-like*) – 1d array of variance (analytic) weights. The default is 1. * **freq\_weights** (*array-like*) – 1d array of frequency weights. The default is 1. * **scale** (*float**,* *optional*) – An optional scale argument. The default is 1. | | Returns: | **Deviance** – The value of deviance function defined below. | | Return type: | array | #### Notes Deviance is defined \[D = 2\sum\_i (freq\\_weights\_i \* var\\_weights \* (llf(endog\_i, endog\_i) - llf(endog\_i, \mu\_i)))\] where y is the endogenous variable. The deviance functions are analytically defined for each family. Internally, we calculate deviance as: \[D = \sum\_i freq\\_weights\_i \* var\\_weights \* resid\\_dev\_i / scale\] statsmodels statsmodels.discrete.discrete_model.CountResults.conf_int statsmodels.discrete.discrete\_model.CountResults.conf\_int =========================================================== `CountResults.conf_int(alpha=0.05, cols=None, method='default')` Returns the confidence interval of the fitted parameters. | Parameters: | * **alpha** (*float**,* *optional*) – The significance level for the confidence interval. ie., The default `alpha` = .05 returns a 95% confidence interval. * **cols** (*array-like**,* *optional*) – `cols` specifies which confidence intervals to return * **method** (*string*) – Not Implemented Yet Method to estimate the confidence\_interval. “Default” : uses self.bse which is based on inverse Hessian for MLE “hjjh” : “jac” : “boot-bse” “boot\_quant” “profile” | | Returns: | **conf\_int** – Each row contains [lower, upper] limits of the confidence interval for the corresponding parameter. The first column contains all lower, the second column contains all upper limits. | | Return type: | array | #### Examples ``` >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> results.conf_int() array([[-5496529.48322745, -1467987.78596704], [ -177.02903529, 207.15277984], [ -0.1115811 , 0.03994274], [ -3.12506664, -0.91539297], [ -1.5179487 , -0.54850503], [ -0.56251721, 0.460309 ], [ 798.7875153 , 2859.51541392]]) ``` ``` >>> results.conf_int(cols=(2,3)) array([[-0.1115811 , 0.03994274], [-3.12506664, -0.91539297]]) ``` #### Notes The confidence interval is based on the standard normal distribution. Models wish to use a different distribution should overwrite this method. statsmodels statsmodels.discrete.discrete_model.CountResults.normalized_cov_params statsmodels.discrete.discrete\_model.CountResults.normalized\_cov\_params ========================================================================= `CountResults.normalized_cov_params()` statsmodels statsmodels.stats.outliers_influence.OLSInfluence.det_cov_params_not_obsi statsmodels.stats.outliers\_influence.OLSInfluence.det\_cov\_params\_not\_obsi ============================================================================== `OLSInfluence.det_cov_params_not_obsi()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/outliers_influence.html#OLSInfluence.det_cov_params_not_obsi) (cached attribute) determinant of cov\_params of all LOOO regressions uses results from leave-one-observation-out loop statsmodels statsmodels.tsa.arima_model.ARMAResults.remove_data statsmodels.tsa.arima\_model.ARMAResults.remove\_data ===================================================== `ARMAResults.remove_data()` remove data arrays, all nobs arrays from result and model This reduces the size of the instance, so it can be pickled with less memory. Currently tested for use with predict from an unpickled results and model instance. Warning Since data and some intermediate results have been removed calculating new statistics that require them will raise exceptions. The exception will occur the first time an attribute is accessed that has been set to None. Not fully tested for time series models, tsa, and might delete too much for prediction or not all that would be possible. The lists of arrays to delete are maintained as attributes of the result and model instance, except for cached values. These lists could be changed before calling remove\_data. The attributes to remove are named in: `model._data_attr : arrays attached to both the model instance` and the results instance with the same attribute name. `result.data_in_cache : arrays that may exist as values in` result.\_cache (TODO : should privatize name) `result._data_attr_model : arrays attached to the model` instance but not to the results instance statsmodels statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.set_conserve_memory statsmodels.tsa.statespace.kalman\_smoother.KalmanSmoother.set\_conserve\_memory ================================================================================ `KalmanSmoother.set_conserve_memory(conserve_memory=None, **kwargs)` Set the memory conservation method By default, the Kalman filter computes a number of intermediate matrices at each iteration. The memory conservation options control which of those matrices are stored. | Parameters: | * **conserve\_memory** (*integer**,* *optional*) – Bitmask value to set the memory conservation method to. See notes for details. * **\*\*kwargs** – Keyword arguments may be used to influence the memory conservation method by setting individual boolean flags. See notes for details. | #### Notes The memory conservation method is defined by a collection of boolean flags, and is internally stored as a bitmask. The methods available are: MEMORY\_STORE\_ALL = 0 Store all intermediate matrices. This is the default value. MEMORY\_NO\_FORECAST = 0x01 Do not store the forecast, forecast error, or forecast error covariance matrices. If this option is used, the `predict` method from the results class is unavailable. MEMORY\_NO\_PREDICTED = 0x02 Do not store the predicted state or predicted state covariance matrices. MEMORY\_NO\_FILTERED = 0x04 Do not store the filtered state or filtered state covariance matrices. MEMORY\_NO\_LIKELIHOOD = 0x08 Do not store the vector of loglikelihood values for each observation. Only the sum of the loglikelihood values is stored. MEMORY\_NO\_GAIN = 0x10 Do not store the Kalman gain matrices. MEMORY\_NO\_SMOOTHING = 0x20 Do not store temporary variables related to Klaman smoothing. If this option is used, smoothing is unavailable. MEMORY\_NO\_SMOOTHING = 0x20 Do not store standardized forecast errors. MEMORY\_CONSERVE Do not store any intermediate matrices. Note that if using a Scipy version less than 0.16, the options MEMORY\_NO\_GAIN, MEMORY\_NO\_SMOOTHING, and MEMORY\_NO\_STD\_FORECAST have no effect. If the bitmask is set directly via the `conserve_memory` argument, then the full method must be provided. If keyword arguments are used to set individual boolean flags, then the lowercase of the method must be used as an argument name, and the value is the desired value of the boolean flag (True or False). Note that the memory conservation method may also be specified by directly modifying the class attributes which are defined similarly to the keyword arguments. The default memory conservation method is `MEMORY_STORE_ALL`, so that all intermediate matrices are stored. #### Examples ``` >>> mod = sm.tsa.statespace.SARIMAX(range(10)) >>> mod.ssm..conserve_memory 0 >>> mod.ssm.memory_no_predicted False >>> mod.ssm.memory_no_predicted = True >>> mod.ssm.conserve_memory 2 >>> mod.ssm.set_conserve_memory(memory_no_filtered=True, ... memory_no_forecast=True) >>> mod.ssm.conserve_memory 7 ``` statsmodels statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.llf_obs statsmodels.tsa.statespace.dynamic\_factor.DynamicFactorResults.llf\_obs ======================================================================== `DynamicFactorResults.llf_obs()` (float) The value of the log-likelihood function evaluated at `params`. statsmodels statsmodels.tsa.statespace.varmax.VARMAX.update statsmodels.tsa.statespace.varmax.VARMAX.update =============================================== `VARMAX.update(params, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/varmax.html#VARMAX.update) Update the parameters of the model | Parameters: | * **params** (*array\_like*) – Array of new parameters. * **transformed** (*boolean**,* *optional*) – Whether or not `params` is already transformed. If set to False, `transform_params` is called. Default is True. | | Returns: | **params** – Array of parameters. | | Return type: | array\_like | #### Notes Since Model is a base class, this method should be overridden by subclasses to perform actual updating steps. statsmodels statsmodels.sandbox.regression.anova_nistcertified.anova_ols statsmodels.sandbox.regression.anova\_nistcertified.anova\_ols ============================================================== `statsmodels.sandbox.regression.anova_nistcertified.anova_ols(y, x)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/anova_nistcertified.html#anova_ols) statsmodels statsmodels.regression.linear_model.WLS.hessian_factor statsmodels.regression.linear\_model.WLS.hessian\_factor ======================================================== `WLS.hessian_factor(params, scale=None, observed=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#WLS.hessian_factor) Weights for calculating Hessian | Parameters: | * **params** (*ndarray*) – parameter at which Hessian is evaluated * **scale** (*None* *or* *float*) – If scale is None, then the default scale will be calculated. Default scale is defined by `self.scaletype` and set in fit. If scale is not None, then it is used as a fixed scale. * **observed** (*bool*) – If True, then the observed Hessian is returned. If false then the expected information matrix is returned. | | Returns: | **hessian\_factor** – A 1d weight vector used in the calculation of the Hessian. The hessian is obtained by `(exog.T * hessian_factor).dot(exog)` | | Return type: | ndarray, 1d |
programming_docs
statsmodels statsmodels.sandbox.stats.multicomp.distance_st_range statsmodels.sandbox.stats.multicomp.distance\_st\_range ======================================================= `statsmodels.sandbox.stats.multicomp.distance_st_range(mean_all, nobs_all, var_all, df=None, triu=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/multicomp.html#distance_st_range) pairwise distance matrix, outsourced from tukeyhsd CHANGED: meandiffs are with sign, studentized range uses abs q\_crit added for testing TODO: error in variance calculation when nobs\_all is scalar, missing 1/n statsmodels statsmodels.tsa.statespace.structural.UnobservedComponentsResults.normalized_cov_params statsmodels.tsa.statespace.structural.UnobservedComponentsResults.normalized\_cov\_params ========================================================================================= `UnobservedComponentsResults.normalized_cov_params()` statsmodels statsmodels.sandbox.regression.gmm.LinearIVGMM.get_error statsmodels.sandbox.regression.gmm.LinearIVGMM.get\_error ========================================================= `LinearIVGMM.get_error(params)` statsmodels statsmodels.tsa.arima_model.ARMA.geterrors statsmodels.tsa.arima\_model.ARMA.geterrors =========================================== `ARMA.geterrors(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_model.html#ARMA.geterrors) Get the errors of the ARMA process. | Parameters: | * **params** (*array-like*) – The fitted ARMA parameters * **order** (*array-like*) – 3 item iterable, with the number of AR, MA, and exogenous parameters, including the trend | statsmodels statsmodels.discrete.discrete_model.LogitResults.predict statsmodels.discrete.discrete\_model.LogitResults.predict ========================================================= `LogitResults.predict(exog=None, transform=True, *args, **kwargs)` Call self.model.predict with self.params as the first argument. | Parameters: | * **exog** (*array-like**,* *optional*) – The values for which you want to predict. see Notes below. * **transform** (*bool**,* *optional*) – If the model was fit via a formula, do you want to pass exog through the formula. Default is True. E.g., if you fit a model y ~ log(x1) + log(x2), and transform is True, then you can pass a data structure that contains x1 and x2 in their original form. Otherwise, you’d need to log the data first. * **kwargs** (*args**,*) – Some models can take additional arguments or keywords, see the predict method of the model for the details. | | Returns: | **prediction** – See self.model.predict | | Return type: | ndarray, [pandas.Series](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html#pandas.Series "(in pandas v0.22.0)") or [pandas.DataFrame](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html#pandas.DataFrame "(in pandas v0.22.0)") | #### Notes The types of exog that are supported depends on whether a formula was used in the specification of the model. If a formula was used, then exog is processed in the same way as the original data. This transformation needs to have key access to the same variable names, and can be a pandas DataFrame or a dict like object. If no formula was used, then the provided exog needs to have the same number of columns as the original exog in the model. No transformation of the data is performed except converting it to a numpy array. Row indices as in pandas data frames are supported, and added to the returned prediction. statsmodels statsmodels.regression.linear_model.OLSResults.cov_HC1 statsmodels.regression.linear\_model.OLSResults.cov\_HC1 ======================================================== `OLSResults.cov_HC1()` See statsmodels.RegressionResults statsmodels statsmodels.genmod.generalized_estimating_equations.GEE.from_formula statsmodels.genmod.generalized\_estimating\_equations.GEE.from\_formula ======================================================================= `classmethod GEE.from_formula(formula, groups, data, subset=None, time=None, offset=None, exposure=None, *args, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_estimating_equations.html#GEE.from_formula) 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** (*extra arguments*) – These are passed to the model * **kwargs** (*extra keyword arguments*) – These are passed to the model with one exception. The `eval_env` keyword is passed to patsy. It can be either a [`patsy.EvalEnvironment`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.EvalEnvironment "(in patsy v0.5.0+dev)") 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** | | Return type: | 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 statsmodels.tsa.arima_model.ARMAResults.hqic statsmodels.tsa.arima\_model.ARMAResults.hqic ============================================= `ARMAResults.hqic()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_model.html#ARMAResults.hqic) statsmodels statsmodels.genmod.generalized_estimating_equations.GEEResults.fittedvalues statsmodels.genmod.generalized\_estimating\_equations.GEEResults.fittedvalues ============================================================================= `GEEResults.fittedvalues()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_estimating_equations.html#GEEResults.fittedvalues) Returns the fitted values from the model. statsmodels statsmodels.sandbox.regression.gmm.GMMResults.wald_test_terms statsmodels.sandbox.regression.gmm.GMMResults.wald\_test\_terms =============================================================== `GMMResults.wald_test_terms(skip_single=False, extra_constraints=None, combine_terms=None)` Compute a sequence of Wald tests for terms over multiple columns This computes joined Wald tests for the hypothesis that all coefficients corresponding to a `term` are zero. `Terms` are defined by the underlying formula or by string matching. | Parameters: | * **skip\_single** (*boolean*) – If true, then terms that consist only of a single column and, therefore, refers only to a single parameter is skipped. If false, then all terms are included. * **extra\_constraints** (*ndarray*) – not tested yet * **combine\_terms** (*None* *or* *list of strings*) – Each string in this list is matched to the name of the terms or the name of the exogenous variables. All columns whose name includes that string are combined in one joint test. | | Returns: | **test\_result** – The result instance contains `table` which is a pandas DataFrame with the test results: test statistic, degrees of freedom and pvalues. | | Return type: | result instance | #### Examples ``` >>> res_ols = ols("np.log(Days+1) ~ C(Duration, Sum)*C(Weight, Sum)", data).fit() >>> res_ols.wald_test_terms() <class 'statsmodels.stats.contrast.WaldTestResults'> F P>F df constraint df denom Intercept 279.754525 2.37985521351e-22 1 51 C(Duration, Sum) 5.367071 0.0245738436636 1 51 C(Weight, Sum) 12.432445 3.99943118767e-05 2 51 C(Duration, Sum):C(Weight, Sum) 0.176002 0.83912310946 2 51 ``` ``` >>> res_poi = Poisson.from_formula("Days ~ C(Weight) * C(Duration)", data).fit(cov_type='HC0') >>> wt = res_poi.wald_test_terms(skip_single=False, combine_terms=['Duration', 'Weight']) >>> print(wt) chi2 P>chi2 df constraint Intercept 15.695625 7.43960374424e-05 1 C(Weight) 16.132616 0.000313940174705 2 C(Duration) 1.009147 0.315107378931 1 C(Weight):C(Duration) 0.216694 0.897315972824 2 Duration 11.187849 0.010752286833 3 Weight 30.263368 4.32586407145e-06 4 ``` statsmodels statsmodels.tsa.statespace.structural.UnobservedComponentsResults.save statsmodels.tsa.statespace.structural.UnobservedComponentsResults.save ====================================================================== `UnobservedComponentsResults.save(fname, remove_data=False)` save a pickle of this instance | Parameters: | * **fname** (*string* *or* *filehandle*) – fname can be a string to a file path or filename, or a filehandle. * **remove\_data** (*bool*) – If False (default), then the instance is pickled without changes. If True, then all arrays with length nobs are set to None before pickling. See the remove\_data method. In some cases not all arrays will be set to None. | #### Notes If remove\_data is true and the model result does not implement a remove\_data method then this will raise an exception. statsmodels statsmodels.genmod.generalized_linear_model.GLMResults.deviance statsmodels.genmod.generalized\_linear\_model.GLMResults.deviance ================================================================= `GLMResults.deviance()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_linear_model.html#GLMResults.deviance) statsmodels statsmodels.genmod.cov_struct.Independence.covariance_matrix statsmodels.genmod.cov\_struct.Independence.covariance\_matrix ============================================================== `Independence.covariance_matrix(expval, index)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/cov_struct.html#Independence.covariance_matrix) Returns the working covariance or correlation matrix for a given cluster of data. | Parameters: | * **endog\_expval** (*array-like*) – The expected values of endog for the cluster for which the covariance or correlation matrix will be returned * **index** (*integer*) – The index of the cluster for which the covariane or correlation matrix will be returned | | Returns: | * **M** (*matrix*) – The covariance or correlation matrix of endog * **is\_cor** (*bool*) – True if M is a correlation matrix, False if M is a covariance matrix | statsmodels statsmodels.sandbox.distributions.transformed.ExpTransf_gen.sf statsmodels.sandbox.distributions.transformed.ExpTransf\_gen.sf =============================================================== `ExpTransf_gen.sf(x, *args, **kwds)` Survival function (1 - `cdf`) at x of the given RV. | Parameters: | * **x** (*array\_like*) – quantiles * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **sf** – Survival function evaluated at x | | Return type: | array\_like | statsmodels statsmodels.regression.mixed_linear_model.MixedLMResults.bsejac statsmodels.regression.mixed\_linear\_model.MixedLMResults.bsejac ================================================================= `MixedLMResults.bsejac()` standard deviation of parameter estimates based on covjac statsmodels statsmodels.sandbox.regression.gmm.GMM.fit statsmodels.sandbox.regression.gmm.GMM.fit ========================================== `GMM.fit(start_params=None, maxiter=10, inv_weights=None, weights_method='cov', wargs=(), has_optimal_weights=True, optim_method='bfgs', optim_args=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#GMM.fit) Estimate parameters using GMM and return GMMResults TODO: weight and covariance arguments still need to be made consistent with similar options in other models, see RegressionResult.get\_robustcov\_results | Parameters: | * **start\_params** (*array* *(**optional**)*) – starting value for parameters ub minimization. If None then fitstart method is called for the starting values. * **maxiter** (*int* *or* *'cue'*) – Number of iterations in iterated GMM. The onestep estimate can be obtained with maxiter=0 or 1. If maxiter is large, then the iteration will stop either at maxiter or on convergence of the parameters (TODO: no options for convergence criteria yet.) If `maxiter == ‘cue’`, the the continuously updated GMM is calculated which updates the weight matrix during the minimization of the GMM objective function. The CUE estimation uses the onestep parameters as starting values. * **inv\_weights** (*None* *or* *ndarray*) – inverse of the starting weighting matrix. If inv\_weights are not given then the method `start_weights` is used which depends on the subclass, for IV subclasses `inv_weights = z’z` where `z` are the instruments, otherwise an identity matrix is used. * **weights\_method** (*string**,* *defines method for robust*) – Options here are similar to `statsmodels.stats.robust_covariance` default is heteroscedasticity consistent, HC0 currently available methods are + `cov` : HC0, optionally with degrees of freedom correction + `hac` : + `iid` : untested, only for Z\*u case, IV cases with u as error indep of Z + `ac` : not available yet + `cluster` : not connected yet + others from robust\_covariance * **wargs`** (*tuple* *or* [dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")*,*) – required and optional arguments for weights\_method + `centered` : bool, indicates whether moments are centered for the calculation of the weights and covariance matrix, applies to all weight\_methods + `ddof` : int degrees of freedom correction, applies currently only to `cov` + `maxlag` : int number of lags to include in HAC calculation , applies only to `hac` + others not yet, e.g. groups for cluster robust * **has\_optimal\_weights** (*If true**,* *then the calculation of the covariance*) – matrix assumes that we have optimal GMM with \(W = S^{-1}\). Default is True. TODO: do we want to have a different default after `onestep`? * **optim\_method** (*string**,* *default is 'bfgs'*) – numerical optimization method. Currently not all optimizers that are available in LikelihoodModels are connected. * **optim\_args** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")) – keyword arguments for the numerical optimizer. | | Returns: | **results** – this is also attached as attribute results | | Return type: | instance of GMMResults | #### Notes Warning: One-step estimation, `maxiter` either 0 or 1, still has problems (at least compared to Stata’s gmm). By default it uses a heteroscedasticity robust covariance matrix, but uses the assumption that the weight matrix is optimal. See options for cov\_params in the results instance. The same options as for weight matrix also apply to the calculation of the estimate of the covariance matrix of the parameter estimates. statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.cov_HC0 statsmodels.sandbox.regression.gmm.IVRegressionResults.cov\_HC0 =============================================================== `IVRegressionResults.cov_HC0()` See statsmodels.RegressionResults statsmodels statsmodels.tsa.statespace.structural.UnobservedComponents.initialize_known statsmodels.tsa.statespace.structural.UnobservedComponents.initialize\_known ============================================================================ `UnobservedComponents.initialize_known(initial_state, initial_state_cov)` statsmodels statsmodels.tsa.statespace.sarimax.SARIMAXResults.cov_params_opg statsmodels.tsa.statespace.sarimax.SARIMAXResults.cov\_params\_opg ================================================================== `SARIMAXResults.cov_params_opg()` (array) The variance / covariance matrix. Computed using the outer product of gradients method. statsmodels statsmodels.imputation.mice.MICEData.perturb_params statsmodels.imputation.mice.MICEData.perturb\_params ==================================================== `MICEData.perturb_params(vname)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/imputation/mice.html#MICEData.perturb_params) statsmodels statsmodels.discrete.discrete_model.MultinomialModel.loglike statsmodels.discrete.discrete\_model.MultinomialModel.loglike ============================================================= `MultinomialModel.loglike(params)` Log-likelihood of model. statsmodels statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialP.loglike statsmodels.discrete.count\_model.ZeroInflatedNegativeBinomialP.loglike ======================================================================= `ZeroInflatedNegativeBinomialP.loglike(params)` Loglikelihood of Generic Zero Inflated model | Parameters: | **params** (*array-like*) – The parameters of the model. | | Returns: | **loglike** – The log-likelihood function of the model evaluated at `params`. See notes. | | Return type: | float | #### Notes \[\ln L=\sum\_{y\_{i}=0}\ln(w\_{i}+(1-w\_{i})\*P\_{main\\_model})+ \sum\_{y\_{i}>0}(\ln(1-w\_{i})+L\_{main\\_model}) where P - pdf of main model, L - loglike function of main model.\] statsmodels statsmodels.discrete.count_model.ZeroInflatedPoissonResults.prsquared statsmodels.discrete.count\_model.ZeroInflatedPoissonResults.prsquared ====================================================================== `ZeroInflatedPoissonResults.prsquared()` statsmodels statsmodels.regression.recursive_ls.RecursiveLSResults.test_normality statsmodels.regression.recursive\_ls.RecursiveLSResults.test\_normality ======================================================================= `RecursiveLSResults.test_normality(method)` Test for normality of standardized residuals. Null hypothesis is normality. | Parameters: | **method** (*string {'jarquebera'}* *or* *None*) – The statistical test for normality. Must be ‘jarquebera’ for Jarque-Bera normality test. If None, an attempt is made to select an appropriate test. | #### Notes If the first `d` loglikelihood values were burned (i.e. in the specified model, `loglikelihood_burn=d`), then this test is calculated ignoring the first `d` residuals. In the case of missing data, the maintained hypothesis is that the data are missing completely at random. This test is then run on the standardized residuals excluding those corresponding to missing observations. See also [`statsmodels.stats.stattools.jarque_bera`](statsmodels.stats.stattools.jarque_bera#statsmodels.stats.stattools.jarque_bera "statsmodels.stats.stattools.jarque_bera") statsmodels statsmodels.regression.linear_model.OLSResults.get_influence statsmodels.regression.linear\_model.OLSResults.get\_influence ============================================================== `OLSResults.get_influence()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#OLSResults.get_influence) get an instance of Influence with influence and outlier measures | Returns: | **infl** – the instance has methods to calculate the main influence and outlier measures for the OLS regression | | Return type: | Influence instance | See also [`statsmodels.stats.outliers_influence.OLSInfluence`](statsmodels.stats.outliers_influence.olsinfluence#statsmodels.stats.outliers_influence.OLSInfluence "statsmodels.stats.outliers_influence.OLSInfluence")
programming_docs
statsmodels statsmodels.tsa.statespace.sarimax.SARIMAX.fit statsmodels.tsa.statespace.sarimax.SARIMAX.fit ============================================== `SARIMAX.fit(start_params=None, transformed=True, cov_type='opg', cov_kwds=None, method='lbfgs', maxiter=50, full_output=1, disp=5, callback=None, return_params=False, optim_score=None, optim_complex_step=None, optim_hessian=None, flags=None, **kwargs)` Fits the model by maximum likelihood via Kalman filter. | Parameters: | * **start\_params** (*array\_like**,* *optional*) – Initial guess of the solution for the loglikelihood maximization. If None, the default is given by Model.start\_params. * **transformed** (*boolean**,* *optional*) – Whether or not `start_params` is already transformed. Default is True. * **cov\_type** (*str**,* *optional*) – The `cov_type` keyword governs the method for calculating the covariance matrix of parameter estimates. Can be one of: + ’opg’ for the outer product of gradient estimator + ’oim’ for the observed information matrix estimator, calculated using the method of Harvey (1989) + ’approx’ for the observed information matrix estimator, calculated using a numerical approximation of the Hessian matrix. + ’robust’ for an approximate (quasi-maximum likelihood) covariance matrix that may be valid even in the presense of some misspecifications. Intermediate calculations use the ‘oim’ method. + ’robust\_approx’ is the same as ‘robust’ except that the intermediate calculations use the ‘approx’ method. + ’none’ for no covariance matrix calculation. * **cov\_kwds** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)") *or* *None**,* *optional*) – A dictionary of arguments affecting covariance matrix computation. **opg, oim, approx, robust, robust\_approx** + ’approx\_complex\_step’ : boolean, optional - If True, numerical approximations are computed using complex-step methods. If False, numerical approximations are computed using finite difference methods. Default is True. + ’approx\_centered’ : boolean, optional - If True, numerical approximations computed using finite difference methods use a centered approximation. Default is False. * **method** (*str**,* *optional*) – The `method` determines which solver from `scipy.optimize` is used, and it can be chosen from among the following strings: + ’newton’ for Newton-Raphson, ‘nm’ for Nelder-Mead + ’bfgs’ for Broyden-Fletcher-Goldfarb-Shanno (BFGS) + ’lbfgs’ for limited-memory BFGS with optional box constraints + ’powell’ for modified Powell’s method + ’cg’ for conjugate gradient + ’ncg’ for Newton-conjugate gradient + ’basinhopping’ for global basin-hopping solverThe explicit arguments in `fit` are passed to the solver, with the exception of the basin-hopping solver. Each solver has several optional arguments that are not the same across solvers. See the notes section below (or scipy.optimize) for the available arguments and for the list of explicit arguments that the basin-hopping solver supports. * **maxiter** (*int**,* *optional*) – The maximum number of iterations to perform. * **full\_output** (*boolean**,* *optional*) – Set to True to have all available output in the Results object’s mle\_retvals attribute. The output is dependent on the solver. See LikelihoodModelResults notes section for more information. * **disp** (*boolean**,* *optional*) – Set to True to print convergence messages. * **callback** (*callable callback**(**xk**)**,* *optional*) – Called after each iteration, as callback(xk), where xk is the current parameter vector. * **return\_params** (*boolean**,* *optional*) – Whether or not to return only the array of maximizing parameters. Default is False. * **optim\_score** (*{'harvey'**,* *'approx'}* *or* *None**,* *optional*) – The method by which the score vector is calculated. ‘harvey’ uses the method from Harvey (1989), ‘approx’ uses either finite difference or complex step differentiation depending upon the value of `optim_complex_step`, and None uses the built-in gradient approximation of the optimizer. Default is None. This keyword is only relevant if the optimization method uses the score. * **optim\_complex\_step** (*bool**,* *optional*) – Whether or not to use complex step differentiation when approximating the score; if False, finite difference approximation is used. Default is True. This keyword is only relevant if `optim_score` is set to ‘harvey’ or ‘approx’. * **optim\_hessian** (*{'opg'**,**'oim'**,**'approx'}**,* *optional*) – The method by which the Hessian is numerically approximated. ‘opg’ uses outer product of gradients, ‘oim’ uses the information matrix formula from Harvey (1989), and ‘approx’ uses numerical approximation. This keyword is only relevant if the optimization method uses the Hessian matrix. * **\*\*kwargs** – Additional keyword arguments to pass to the optimizer. | | Returns: | | | Return type: | [MLEResults](statsmodels.tsa.statespace.mlemodel.mleresults#statsmodels.tsa.statespace.mlemodel.MLEResults "statsmodels.tsa.statespace.mlemodel.MLEResults") | See also [`statsmodels.base.model.LikelihoodModel.fit`](http://www.statsmodels.org/stable/dev/generated/statsmodels.base.model.LikelihoodModel.fit.html#statsmodels.base.model.LikelihoodModel.fit "statsmodels.base.model.LikelihoodModel.fit"), `MLEResults` statsmodels statsmodels.sandbox.stats.multicomp.get_tukeyQcrit statsmodels.sandbox.stats.multicomp.get\_tukeyQcrit =================================================== `statsmodels.sandbox.stats.multicomp.get_tukeyQcrit(k, df, alpha=0.05)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/multicomp.html#get_tukeyQcrit) return critical values for Tukey’s HSD (Q) | Parameters: | * **k** (*int in {2**,* *..**,* *10}*) – number of tests * **df** (*int*) – degrees of freedom of error term * **alpha** (*{0.05**,* *0.01}*) – type 1 error, 1-confidence level | not enough error checking for limitations statsmodels statsmodels.genmod.families.family.Binomial.loglike_obs statsmodels.genmod.families.family.Binomial.loglike\_obs ======================================================== `Binomial.loglike_obs(endog, mu, var_weights=1.0, scale=1.0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/family.html#Binomial.loglike_obs) The log-likelihood function for each observation in terms of the fitted mean response for the Binomial distribution. | Parameters: | * **endog** (*array*) – Usually the endogenous response variable. * **mu** (*array*) – Usually but not always the fitted mean response variable. * **var\_weights** (*array-like*) – 1d array of variance (analytic) weights. The default is 1. * **scale** (*float*) – The scale parameter. The default is 1. | | Returns: | **ll\_i** – The value of the loglikelihood evaluated at (endog, mu, var\_weights, scale) as defined below. | | Return type: | float | #### Notes If the endogenous variable is binary: \[ll\_i = \sum\_i (y\_i \* \log(\mu\_i/(1-\mu\_i)) + \log(1-\mu\_i)) \* var\\_weights\_i\] If the endogenous variable is binomial: \[ll\_i = \sum\_i var\\_weights\_i \* (\ln \Gamma(n+1) - \ln \Gamma(y\_i + 1) - \ln \Gamma(n\_i - y\_i +1) + y\_i \* \log(\mu\_i / (n\_i - \mu\_i)) + n \* \log(1 - \mu\_i/n\_i))\] where \(y\_i = Y\_i \* n\_i\) with \(Y\_i\) and \(n\_i\) as defined in Binomial initialize. This simply makes \(y\_i\) the original number of successes. statsmodels statsmodels.tsa.ar_model.ARResults.t_test_pairwise statsmodels.tsa.ar\_model.ARResults.t\_test\_pairwise ===================================================== `ARResults.t_test_pairwise(term_name, method='hs', alpha=0.05, factor_labels=None)` perform pairwise t\_test with multiple testing corrected p-values This uses the formula design\_info encoding contrast matrix and should work for all encodings of a main effect. | Parameters: | * **result** (*result instance*) – The results of an estimated model with a categorical main effect. * **term\_name** (*str*) – name of the term for which pairwise comparisons are computed. Term names for categorical effects are created by patsy and correspond to the main part of the exog names. * **method** (*str* *or* *list of strings*) – multiple testing p-value correction, default is ‘hs’, see stats.multipletesting * **alpha** (*float*) – significance level for multiple testing reject decision. * **factor\_labels** (*None**,* *list of str*) – Labels for the factor levels used for pairwise labels. If not provided, then the labels from the formula design\_info are used. | | Returns: | **results** – The results are stored as attributes, the main attributes are the following two. Other attributes are added for debugging purposes or as background information.* result\_frame : pandas DataFrame with t\_test results and multiple testing corrected p-values. * contrasts : matrix of constraints of the null hypothesis in the t\_test. | | Return type: | instance of a simple Results class | #### Notes Status: experimental. Currently only checked for treatment coding with and without specified reference level. Currently there are no multiple testing corrected confidence intervals available. #### Examples ``` >>> res = ols("np.log(Days+1) ~ C(Weight) + C(Duration)", data).fit() >>> pw = res.t_test_pairwise("C(Weight)") >>> pw.result_frame coef std err t P>|t| Conf. Int. Low 2-1 0.632315 0.230003 2.749157 8.028083e-03 0.171563 3-1 1.302555 0.230003 5.663201 5.331513e-07 0.841803 3-2 0.670240 0.230003 2.914044 5.119126e-03 0.209488 Conf. Int. Upp. pvalue-hs reject-hs 2-1 1.093067 0.010212 True 3-1 1.763307 0.000002 True 3-2 1.130992 0.010212 True ``` statsmodels statsmodels.tsa.arima_model.ARMA.hessian statsmodels.tsa.arima\_model.ARMA.hessian ========================================= `ARMA.hessian(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_model.html#ARMA.hessian) Compute the Hessian at params, #### Notes This is a numerical approximation. statsmodels statsmodels.tsa.statespace.varmax.VARMAX.set_inversion_method statsmodels.tsa.statespace.varmax.VARMAX.set\_inversion\_method =============================================================== `VARMAX.set_inversion_method(inversion_method=None, **kwargs)` Set the inversion method The Kalman filter may contain one matrix inversion: that of the forecast error covariance matrix. The inversion method controls how and if that inverse is performed. | Parameters: | * **inversion\_method** (*integer**,* *optional*) – Bitmask value to set the inversion method to. See notes for details. * **\*\*kwargs** – Keyword arguments may be used to influence the inversion method by setting individual boolean flags. See notes for details. | #### Notes This method is rarely used. See the corresponding function in the `KalmanFilter` class for details. statsmodels statsmodels.robust.norms.RobustNorm.psi_deriv statsmodels.robust.norms.RobustNorm.psi\_deriv ============================================== `RobustNorm.psi_deriv(z)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/robust/norms.html#RobustNorm.psi_deriv) Deriative of psi. Used to obtain robust covariance matrix. See statsmodels.rlm for more information. Abstract method: psi\_derive = psi’ statsmodels statsmodels.stats.weightstats.ttest_ind statsmodels.stats.weightstats.ttest\_ind ======================================== `statsmodels.stats.weightstats.ttest_ind(x1, x2, alternative='two-sided', usevar='pooled', weights=(None, None), value=0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/weightstats.html#ttest_ind) ttest independent sample convenience function that uses the classes and throws away the intermediate results, compared to scipy stats: drops axis option, adds alternative, usevar, and weights option | Parameters: | * **x2** (*x1**,*) – two independent samples, see notes for 2-D case * **alternative** (*string*) – The alternative hypothesis, H1, has to be one of the following ’two-sided’: H1: difference in means not equal to value (default) ‘larger’ : H1: difference in means larger than value ‘smaller’ : H1: difference in means smaller than value * **usevar** (*string**,* *'pooled'* *or* *'unequal'*) – If `pooled`, then the standard deviation of the samples is assumed to be the same. If `unequal`, then Welsh ttest with Satterthwait degrees of freedom is used * **weights** (*tuple of None* *or* *ndarrays*) – Case weights for the two samples. For details on weights see `DescrStatsW` * **value** (*float*) – difference between the means under the Null hypothesis. | | Returns: | * **tstat** (*float*) – test statisic * **pvalue** (*float*) – pvalue of the t-test * **df** (*int or float*) – degrees of freedom used in the t-test | statsmodels statsmodels.tsa.statespace.structural.UnobservedComponents.initialize_statespace statsmodels.tsa.statespace.structural.UnobservedComponents.initialize\_statespace ================================================================================= `UnobservedComponents.initialize_statespace(**kwargs)` Initialize the state space representation | Parameters: | **\*\*kwargs** – Additional keyword arguments to pass to the state space class constructor. | statsmodels statsmodels.genmod.families.links.Power.inverse statsmodels.genmod.families.links.Power.inverse =============================================== `Power.inverse(z)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/links.html#Power.inverse) Inverse of the power transform link function | Parameters: | **z** (*array-like*) – Value of the transformed mean parameters at `p` | | Returns: | **`p`** – Mean parameters | | Return type: | array | #### Notes g^(-1)(z`) = `z`**(1/`power`) statsmodels statsmodels.tsa.statespace.varmax.VARMAXResults.cov_params statsmodels.tsa.statespace.varmax.VARMAXResults.cov\_params =========================================================== `VARMAXResults.cov_params(r_matrix=None, column=None, scale=None, cov_p=None, other=None)` Returns the variance/covariance matrix. The variance/covariance matrix can be of a linear contrast of the estimates of params or all params multiplied by scale which will usually be an estimate of sigma^2. Scale is assumed to be a scalar. | Parameters: | * **r\_matrix** (*array-like*) – Can be 1d, or 2d. Can be used alone or with other. * **column** (*array-like**,* *optional*) – Must be used on its own. Can be 0d or 1d see below. * **scale** (*float**,* *optional*) – Can be specified or not. Default is None, which means that the scale argument is taken from the model. * **other** (*array-like**,* *optional*) – Can be used when r\_matrix is specified. | | Returns: | **cov** – covariance matrix of the parameter estimates or of linear combination of parameter estimates. See Notes. | | Return type: | ndarray | #### Notes (The below are assumed to be in matrix notation.) If no argument is specified returns the covariance matrix of a model `(scale)*(X.T X)^(-1)` If contrast is specified it pre and post-multiplies as follows `(scale) * r_matrix (X.T X)^(-1) r_matrix.T` If contrast and other are specified returns `(scale) * r_matrix (X.T X)^(-1) other.T` If column is specified returns `(scale) * (X.T X)^(-1)[column,column]` if column is 0d OR `(scale) * (X.T X)^(-1)[column][:,column]` if column is 1d statsmodels statsmodels.miscmodels.count.PoissonGMLE statsmodels.miscmodels.count.PoissonGMLE ======================================== `class statsmodels.miscmodels.count.PoissonGMLE(endog, exog=None, loglike=None, score=None, hessian=None, missing='none', extra_params_names=None, **kwds)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/miscmodels/count.html#PoissonGMLE) Maximum Likelihood Estimation of Poisson Model This is an example for generic MLE which has the same statistical model as discretemod.Poisson. Except for defining the negative log-likelihood method, all methods and results are generic. Gradients and Hessian and all resulting statistics are based on numerical differentiation. #### Methods | | | | --- | --- | | [`expandparams`](statsmodels.miscmodels.count.poissongmle.expandparams#statsmodels.miscmodels.count.PoissonGMLE.expandparams "statsmodels.miscmodels.count.PoissonGMLE.expandparams")(params) | expand to full parameter array when some parameters are fixed | | [`fit`](statsmodels.miscmodels.count.poissongmle.fit#statsmodels.miscmodels.count.PoissonGMLE.fit "statsmodels.miscmodels.count.PoissonGMLE.fit")([start\_params, method, maxiter, …]) | Fit the model using maximum likelihood. | | [`from_formula`](statsmodels.miscmodels.count.poissongmle.from_formula#statsmodels.miscmodels.count.PoissonGMLE.from_formula "statsmodels.miscmodels.count.PoissonGMLE.from_formula")(formula, data[, subset, drop\_cols]) | Create a Model from a formula and dataframe. | | [`hessian`](statsmodels.miscmodels.count.poissongmle.hessian#statsmodels.miscmodels.count.PoissonGMLE.hessian "statsmodels.miscmodels.count.PoissonGMLE.hessian")(params) | Hessian of log-likelihood evaluated at params | | [`hessian_factor`](statsmodels.miscmodels.count.poissongmle.hessian_factor#statsmodels.miscmodels.count.PoissonGMLE.hessian_factor "statsmodels.miscmodels.count.PoissonGMLE.hessian_factor")(params[, scale, observed]) | Weights for calculating Hessian | | [`information`](statsmodels.miscmodels.count.poissongmle.information#statsmodels.miscmodels.count.PoissonGMLE.information "statsmodels.miscmodels.count.PoissonGMLE.information")(params) | Fisher information matrix of model | | [`initialize`](statsmodels.miscmodels.count.poissongmle.initialize#statsmodels.miscmodels.count.PoissonGMLE.initialize "statsmodels.miscmodels.count.PoissonGMLE.initialize")() | Initialize (possibly re-initialize) a Model instance. | | [`loglike`](statsmodels.miscmodels.count.poissongmle.loglike#statsmodels.miscmodels.count.PoissonGMLE.loglike "statsmodels.miscmodels.count.PoissonGMLE.loglike")(params) | Log-likelihood of model. | | [`loglikeobs`](statsmodels.miscmodels.count.poissongmle.loglikeobs#statsmodels.miscmodels.count.PoissonGMLE.loglikeobs "statsmodels.miscmodels.count.PoissonGMLE.loglikeobs")(params) | | | [`nloglike`](statsmodels.miscmodels.count.poissongmle.nloglike#statsmodels.miscmodels.count.PoissonGMLE.nloglike "statsmodels.miscmodels.count.PoissonGMLE.nloglike")(params) | | | [`nloglikeobs`](statsmodels.miscmodels.count.poissongmle.nloglikeobs#statsmodels.miscmodels.count.PoissonGMLE.nloglikeobs "statsmodels.miscmodels.count.PoissonGMLE.nloglikeobs")(params) | Loglikelihood of Poisson model | | [`predict`](statsmodels.miscmodels.count.poissongmle.predict#statsmodels.miscmodels.count.PoissonGMLE.predict "statsmodels.miscmodels.count.PoissonGMLE.predict")(params[, exog]) | After a model has been fit predict returns the fitted values. | | [`predict_distribution`](statsmodels.miscmodels.count.poissongmle.predict_distribution#statsmodels.miscmodels.count.PoissonGMLE.predict_distribution "statsmodels.miscmodels.count.PoissonGMLE.predict_distribution")(exog) | return frozen scipy.stats distribution with mu at estimated prediction | | [`reduceparams`](statsmodels.miscmodels.count.poissongmle.reduceparams#statsmodels.miscmodels.count.PoissonGMLE.reduceparams "statsmodels.miscmodels.count.PoissonGMLE.reduceparams")(params) | | | [`score`](statsmodels.miscmodels.count.poissongmle.score#statsmodels.miscmodels.count.PoissonGMLE.score "statsmodels.miscmodels.count.PoissonGMLE.score")(params) | Gradient of log-likelihood evaluated at params | | [`score_obs`](statsmodels.miscmodels.count.poissongmle.score_obs#statsmodels.miscmodels.count.PoissonGMLE.score_obs "statsmodels.miscmodels.count.PoissonGMLE.score_obs")(params, \*\*kwds) | Jacobian/Gradient of log-likelihood evaluated at params for each observation. | #### Attributes | | | | --- | --- | | `endog_names` | Names of endogenous variables | | `exog_names` | Names of exogenous variables |
programming_docs
statsmodels statsmodels.discrete.discrete_model.DiscreteResults.tvalues statsmodels.discrete.discrete\_model.DiscreteResults.tvalues ============================================================ `DiscreteResults.tvalues()` Return the t-statistic for a given parameter estimate. statsmodels statsmodels.stats.power.GofChisquarePower statsmodels.stats.power.GofChisquarePower ========================================= `class statsmodels.stats.power.GofChisquarePower(**kwds)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/power.html#GofChisquarePower) Statistical Power calculations for one sample chisquare test #### Methods | | | | --- | --- | | [`plot_power`](statsmodels.stats.power.gofchisquarepower.plot_power#statsmodels.stats.power.GofChisquarePower.plot_power "statsmodels.stats.power.GofChisquarePower.plot_power")([dep\_var, nobs, effect\_size, …]) | plot power with number of observations or effect size on x-axis | | [`power`](statsmodels.stats.power.gofchisquarepower.power#statsmodels.stats.power.GofChisquarePower.power "statsmodels.stats.power.GofChisquarePower.power")(effect\_size, nobs, alpha, n\_bins[, ddof]) | Calculate the power of a chisquare test for one sample | | [`solve_power`](statsmodels.stats.power.gofchisquarepower.solve_power#statsmodels.stats.power.GofChisquarePower.solve_power "statsmodels.stats.power.GofChisquarePower.solve_power")([effect\_size, nobs, alpha, …]) | solve for any one parameter of the power of a one sample chisquare-test | statsmodels statsmodels.discrete.discrete_model.NegativeBinomialP.hessian statsmodels.discrete.discrete\_model.NegativeBinomialP.hessian ============================================================== `NegativeBinomialP.hessian(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#NegativeBinomialP.hessian) Generalized Negative Binomial (NB-P) model hessian maxtrix of the log-likelihood | Parameters: | **params** (*array-like*) – The parameters of the model | | Returns: | **hessian** – The hessian matrix of the model. | | Return type: | ndarray, 2-D | statsmodels statsmodels.tsa.statespace.tools.constrain_stationary_multivariate statsmodels.tsa.statespace.tools.constrain\_stationary\_multivariate ==================================================================== `statsmodels.tsa.statespace.tools.constrain_stationary_multivariate(unconstrained, variance, transform_variance=False, prefix=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/tools.html#constrain_stationary_multivariate) Transform unconstrained parameters used by the optimizer to constrained parameters used in likelihood evaluation for a vector autoregression. | Parameters: | * **unconstrained** (*array* *or* *list*) – Arbitrary matrices to be transformed to stationary coefficient matrices of the VAR. If a list, should be a list of length `order`, where each element is an array sized `k_endog` x `k_endog`. If an array, should be the matrices horizontally concatenated and sized `k_endog` x `k_endog * order`. * **error\_variance** (*array*) – The variance / covariance matrix of the error term. Should be sized `k_endog` x `k_endog`. This is used as input in the algorithm even if is not transformed by it (when `transform_variance` is False). The error term variance is required input when transformation is used either to force an autoregressive component to be stationary or to force a moving average component to be invertible. * **transform\_variance** (*boolean**,* *optional*) – Whether or not to transform the error variance term. This option is not typically used, and the default is False. * **prefix** (*{'s'**,**'d'**,**'c'**,**'z'}**,* *optional*) – The appropriate BLAS prefix to use for the passed datatypes. Only use if absolutely sure that the prefix is correct or an error will result. | | Returns: | **constrained** – Transformed coefficient matrices leading to a stationary VAR representation. Will match the type of the passed `unconstrained` variable (so if a list was passed, a list will be returned). | | Return type: | array or list | #### Notes In the notation of [[1]](#id4), the arguments `(variance, unconstrained)` are written as \((\Sigma, A\_1, \dots, A\_p)\), where \(p\) is the order of the vector autoregression, and is here determined by the length of the `unconstrained` argument. There are two steps in the constraining algorithm. First, \((A\_1, \dots, A\_p)\) are transformed into \((P\_1, \dots, P\_p)\) via Lemma 2.2 of [[1]](#id4). Second, \((\Sigma, P\_1, \dots, P\_p)\) are transformed into \((\Sigma, \phi\_1, \dots, \phi\_p)\) via Lemmas 2.1 and 2.3 of [[1]](#id4). If `transform_variance=True`, then only Lemma 2.1 is applied in the second step. While this function can be used even in the univariate case, it is much slower, so in that case `constrain_stationary_univariate` is preferred. #### References | | | | --- | --- | | [1] | *([1](#id1), [2](#id2), [3](#id3))* Ansley, Craig F., and Robert Kohn. 1986. “A Note on Reparameterizing a Vector Autoregressive Moving Average Model to Enforce Stationarity.” Journal of Statistical Computation and Simulation 24 (2): 99-106. | | | | | --- | --- | | [\*] | Ansley, Craig F, and Paul Newbold. 1979. “Multivariate Partial Autocorrelations.” In Proceedings of the Business and Economic Statistics Section, 349-53. American Statistical Association | statsmodels statsmodels.sandbox.distributions.extras.NormExpan_gen.cdf statsmodels.sandbox.distributions.extras.NormExpan\_gen.cdf =========================================================== `NormExpan_gen.cdf(x, *args, **kwds)` Cumulative distribution function of the given RV. | Parameters: | * **x** (*array\_like*) – quantiles * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **cdf** – Cumulative distribution function evaluated at `x` | | Return type: | ndarray | statsmodels statsmodels.genmod.families.family.Gamma.resid_dev statsmodels.genmod.families.family.Gamma.resid\_dev =================================================== `Gamma.resid_dev(endog, mu, var_weights=1.0, scale=1.0)` The deviance residuals | Parameters: | * **endog** (*array-like*) – The endogenous response variable * **mu** (*array-like*) – The inverse of the link function at the linear predicted values. * **var\_weights** (*array-like*) – 1d array of variance (analytic) weights. The default is 1. * **scale** (*float**,* *optional*) – An optional scale argument. The default is 1. | | Returns: | **resid\_dev** – Deviance residuals as defined below. | | Return type: | float | #### Notes The deviance residuals are defined by the contribution D\_i of observation i to the deviance as \[resid\\_dev\_i = sign(y\_i-\mu\_i) \sqrt{D\_i}\] D\_i is calculated from the \_resid\_dev method in each family. Distribution-specific documentation of the calculation is available there. statsmodels statsmodels.sandbox.tsa.fftarma.ArmaFft.filter statsmodels.sandbox.tsa.fftarma.ArmaFft.filter ============================================== `ArmaFft.filter(x)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/tsa/fftarma.html#ArmaFft.filter) filter a timeseries with the ARMA filter padding with zero is missing, in example I needed the padding to get initial conditions identical to direct filter Initial filtered observations differ from filter2 and signal.lfilter, but at end they are the same. See also `tsa.filters.fftconvolve` statsmodels statsmodels.robust.scale.hubers_scale statsmodels.robust.scale.hubers\_scale ====================================== `statsmodels.robust.scale.hubers_scale = <statsmodels.robust.scale.HuberScale object>` Huber’s scaling for fitting robust linear models. Huber’s scale is intended to be used as the scale estimate in the IRLS algorithm and is slightly different than the `Huber` class. | Parameters: | * **d** (*float**,* *optional*) – d is the tuning constant for Huber’s scale. Default is 2.5 * **tol** (*float**,* *optional*) – The convergence tolerance * **maxiter** (*int**,* *optiona*) – The maximum number of iterations. The default is 30. | `statsmodels.robust.scale.call()` Return’s Huber’s scale computed as below #### Notes Huber’s scale is the iterative solution to scale\_(i+1)\*\*2 = 1/(n\*h)\*sum(chi(r/sigma\_i)\*sigma\_i\*\*2 where the Huber function is chi(x) = (x\*\*2)/2 for |x| < d chi(x) = (d\*\*2)/2 for |x| >= d and the Huber constant h = (n-p)/n\*(d\*\*2 + (1-d\*\*2)\* scipy.stats.norm.cdf(d) - .5 - d\*sqrt(2\*pi)\*exp(-0.5\*d\*\*2) statsmodels statsmodels.sandbox.regression.gmm.IVGMM.fitgmm_cu statsmodels.sandbox.regression.gmm.IVGMM.fitgmm\_cu =================================================== `IVGMM.fitgmm_cu(start, optim_method='bfgs', optim_args=None)` estimate parameters using continuously updating GMM | Parameters: | **start** (*array\_like*) – starting values for minimization | | Returns: | **paramest** – estimated parameters | | Return type: | array | #### Notes todo: add fixed parameter option, not here ??? uses scipy.optimize.fmin statsmodels statsmodels.miscmodels.tmodel.TLinearModel.nloglikeobs statsmodels.miscmodels.tmodel.TLinearModel.nloglikeobs ====================================================== `TLinearModel.nloglikeobs(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/miscmodels/tmodel.html#TLinearModel.nloglikeobs) Loglikelihood of linear model with t distributed errors. | Parameters: | **params** (*array*) – The parameters of the model. The last 2 parameters are degrees of freedom and scale. | | Returns: | **loglike** – The log likelihood of the model evaluated at `params` for each observation defined by self.endog and self.exog. | | Return type: | array | #### Notes \[\ln L=\sum\_{i=1}^{n}\left[-\lambda\_{i}+y\_{i}x\_{i}^{\prime}\beta-\ln y\_{i}!\right]\] The t distribution is the standard t distribution and not a standardized t distribution, which means that the scale parameter is not equal to the standard deviation. self.fixed\_params and self.expandparams can be used to fix some parameters. (I doubt this has been tested in this model.) statsmodels statsmodels.regression.quantile_regression.QuantRegResults.resid statsmodels.regression.quantile\_regression.QuantRegResults.resid ================================================================= `QuantRegResults.resid()` statsmodels statsmodels.regression.recursive_ls.RecursiveLS.simulation_smoother statsmodels.regression.recursive\_ls.RecursiveLS.simulation\_smoother ===================================================================== `RecursiveLS.simulation_smoother(simulation_output=None, **kwargs)` Retrieve a simulation smoother for the state space model. | Parameters: | * **simulation\_output** (*int**,* *optional*) – Determines which simulation smoother output is calculated. Default is all (including state and disturbances). * **\*\*kwargs** – Additional keyword arguments, used to set the simulation output. See `set_simulation_output` for more details. | | Returns: | | | Return type: | SimulationSmoothResults | statsmodels statsmodels.discrete.discrete_model.NegativeBinomialResults.f_test statsmodels.discrete.discrete\_model.NegativeBinomialResults.f\_test ==================================================================== `NegativeBinomialResults.f_test(r_matrix, cov_p=None, scale=1.0, invcov=None)` Compute the F-test for a joint linear hypothesis. This is a special case of `wald_test` that always uses the F distribution. | Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) – + array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length k row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – Default is 1.0 for no scaling. * **invcov** (*array-like**,* *optional*) – A q x q array to specify an inverse covariance matrix based on a restrictions matrix. | | Returns: | **res** – The results for the test are attributes of this results instance. | | Return type: | ContrastResults instance | #### Examples ``` >>> import numpy as np >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> A = np.identity(len(results.params)) >>> A = A[1:,:] ``` This tests that each coefficient is jointly statistically significantly different from zero. ``` >>> print(results.f_test(A)) <F test: F=array([[ 330.28533923]]), p=4.984030528700946e-10, df_denom=9, df_num=6> ``` Compare this to ``` >>> results.fvalue 330.2853392346658 >>> results.f_pvalue 4.98403096572e-10 ``` ``` >>> B = np.array(([0,0,1,-1,0,0,0],[0,0,0,0,0,1,-1])) ``` This tests that the coefficient on the 2nd and 3rd regressors are equal and jointly that the coefficient on the 5th and 6th regressors are equal. ``` >>> print(results.f_test(B)) <F test: F=array([[ 9.74046187]]), p=0.005605288531708235, df_denom=9, df_num=2> ``` Alternatively, you can specify the hypothesis tests using a string ``` >>> from statsmodels.datasets import longley >>> from statsmodels.formula.api import ols >>> dta = longley.load_pandas().data >>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' >>> results = ols(formula, dta).fit() >>> hypotheses = '(GNPDEFL = GNP), (UNEMP = 2), (YEAR/1829 = 1)' >>> f_test = results.f_test(hypotheses) >>> print(f_test) <F test: F=array([[ 144.17976065]]), p=6.322026217355609e-08, df_denom=9, df_num=3> ``` See also [`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`wald_test`](statsmodels.discrete.discrete_model.negativebinomialresults.wald_test#statsmodels.discrete.discrete_model.NegativeBinomialResults.wald_test "statsmodels.discrete.discrete_model.NegativeBinomialResults.wald_test"), [`t_test`](statsmodels.discrete.discrete_model.negativebinomialresults.t_test#statsmodels.discrete.discrete_model.NegativeBinomialResults.t_test "statsmodels.discrete.discrete_model.NegativeBinomialResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") #### Notes The matrix `r_matrix` is assumed to be non-singular. More precisely, r\_matrix (pX pX.T) r\_matrix.T is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full. statsmodels statsmodels.stats.contingency_tables.StratifiedTable.from_data statsmodels.stats.contingency\_tables.StratifiedTable.from\_data ================================================================ `classmethod StratifiedTable.from_data(var1, var2, strata, data)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#StratifiedTable.from_data) Construct a StratifiedTable object from data. | Parameters: | * **var1** (*int* *or* *string*) – The column index or name of `data` specifying the variable defining the rows of the contingency table. The variable must have only two distinct values. * **var2** (*int* *or* *string*) – The column index or name of `data` specifying the variable defining the columns of the contingency table. The variable must have only two distinct values. * **strata** (*int* *or* *string*) – The column index or name of `data` specifying the variable defining the strata. * **data** (*array-like*) – The raw data. A cross-table for analysis is constructed from the first two columns. | | Returns: | | | Return type: | A StratifiedTable instance. | statsmodels statsmodels.tsa.statespace.sarimax.SARIMAX.update statsmodels.tsa.statespace.sarimax.SARIMAX.update ================================================= `SARIMAX.update(params, transformed=True, complex_step=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/sarimax.html#SARIMAX.update) Update the parameters of the model Updates the representation matrices to fill in the new parameter values. | Parameters: | * **params** (*array\_like*) – Array of new parameters. * **transformed** (*boolean**,* *optional*) – Whether or not `params` is already transformed. If set to False, `transform_params` is called. Default is True.. | | Returns: | **params** – Array of parameters. | | Return type: | array\_like | statsmodels statsmodels.tsa.stattools.coint statsmodels.tsa.stattools.coint =============================== `statsmodels.tsa.stattools.coint(y0, y1, trend='c', method='aeg', maxlag=None, autolag='aic', return_results=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/stattools.html#coint) Test for no-cointegration of a univariate equation The null hypothesis is no cointegration. Variables in y0 and y1 are assumed to be integrated of order 1, I(1). This uses the augmented Engle-Granger two-step cointegration test. Constant or trend is included in 1st stage regression, i.e. in cointegrating equation. **Warning:** The autolag default has changed compared to statsmodels 0.8. In 0.8 autolag was always None, no the keyword is used and defaults to ‘aic’. Use `autolag=None` to avoid the lag search. | Parameters: | * **y1** (*array\_like**,* *1d*) – first element in cointegrating vector * **y2** (*array\_like*) – remaining elements in cointegrating vector * **trend** (*str {'c'**,* *'ct'}*) – trend term included in regression for cointegrating equation + ’c’ : constant + ’ct’ : constant and linear trend + also available quadratic trend ‘ctt’, and no constant ‘nc’ * **method** (*string*) – currently only ‘aeg’ for augmented Engle-Granger test is available. default might change. * **maxlag** (*None* *or* *int*) – keyword for `adfuller`, largest or given number of lags * **autolag** (*string*) – keyword for `adfuller`, lag selection criterion. + if None, then maxlag lags are used without lag search + if ‘AIC’ (default) or ‘BIC’, then the number of lags is chosen to minimize the corresponding information criterion + ’t-stat’ based choice of maxlag. Starts with maxlag and drops a lag until the t-statistic on the last lag length is significant using a 5%-sized test * **return\_results** (*bool*) – for future compatibility, currently only tuple available. If True, then a results instance is returned. Otherwise, a tuple with the test outcome is returned. Set `return_results=False` to avoid future changes in return. | | Returns: | * **coint\_t** (*float*) – t-statistic of unit-root test on residuals * **pvalue** (*float*) – MacKinnon’s approximate, asymptotic p-value based on MacKinnon (1994) * **crit\_value** (*dict*) – Critical values for the test statistic at the 1 %, 5 %, and 10 % levels based on regression curve. This depends on the number of observations. | #### Notes The Null hypothesis is that there is no cointegration, the alternative hypothesis is that there is cointegrating relationship. If the pvalue is small, below a critical size, then we can reject the hypothesis that there is no cointegrating relationship. P-values and critical values are obtained through regression surface approximation from MacKinnon 1994 and 2010. If the two series are almost perfectly collinear, then computing the test is numerically unstable. However, the two series will be cointegrated under the maintained assumption that they are integrated. In this case the t-statistic will be set to -inf and the pvalue to zero. TODO: We could handle gaps in data by dropping rows with nans in the auxiliary regressions. Not implemented yet, currently assumes no nans and no gaps in time series. #### References MacKinnon, J.G. 1994 “Approximate Asymptotic Distribution Functions for Unit-Root and Cointegration Tests.” Journal of Business & Economics Statistics, 12.2, 167-76. MacKinnon, J.G. 2010. “Critical Values for Cointegration Tests.” Queen’s University, Dept of Economics Working Papers 1227. <http://ideas.repec.org/p/qed/wpaper/1227.html>
programming_docs
statsmodels statsmodels.sandbox.distributions.transformed.TransfTwo_gen.pdf statsmodels.sandbox.distributions.transformed.TransfTwo\_gen.pdf ================================================================ `TransfTwo_gen.pdf(x, *args, **kwds)` Probability density function at x of the given RV. | Parameters: | * **x** (*array\_like*) – quantiles * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **pdf** – Probability density function evaluated at x | | Return type: | ndarray | statsmodels statsmodels.tsa.vector_ar.irf.IRAnalysis.fevd_table statsmodels.tsa.vector\_ar.irf.IRAnalysis.fevd\_table ===================================================== `IRAnalysis.fevd_table()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/irf.html#IRAnalysis.fevd_table) statsmodels statsmodels.regression.linear_model.RegressionResults.cov_params statsmodels.regression.linear\_model.RegressionResults.cov\_params ================================================================== `RegressionResults.cov_params(r_matrix=None, column=None, scale=None, cov_p=None, other=None)` Returns the variance/covariance matrix. The variance/covariance matrix can be of a linear contrast of the estimates of params or all params multiplied by scale which will usually be an estimate of sigma^2. Scale is assumed to be a scalar. | Parameters: | * **r\_matrix** (*array-like*) – Can be 1d, or 2d. Can be used alone or with other. * **column** (*array-like**,* *optional*) – Must be used on its own. Can be 0d or 1d see below. * **scale** (*float**,* *optional*) – Can be specified or not. Default is None, which means that the scale argument is taken from the model. * **other** (*array-like**,* *optional*) – Can be used when r\_matrix is specified. | | Returns: | **cov** – covariance matrix of the parameter estimates or of linear combination of parameter estimates. See Notes. | | Return type: | ndarray | #### Notes (The below are assumed to be in matrix notation.) If no argument is specified returns the covariance matrix of a model `(scale)*(X.T X)^(-1)` If contrast is specified it pre and post-multiplies as follows `(scale) * r_matrix (X.T X)^(-1) r_matrix.T` If contrast and other are specified returns `(scale) * r_matrix (X.T X)^(-1) other.T` If column is specified returns `(scale) * (X.T X)^(-1)[column,column]` if column is 0d OR `(scale) * (X.T X)^(-1)[column][:,column]` if column is 1d statsmodels statsmodels.regression.quantile_regression.QuantRegResults.resid_pearson statsmodels.regression.quantile\_regression.QuantRegResults.resid\_pearson ========================================================================== `QuantRegResults.resid_pearson()` Residuals, normalized to have unit variance. | Returns: | | | Return type: | An array wresid standardized by the sqrt if scale | statsmodels statsmodels.sandbox.distributions.extras.ACSkewT_gen.logsf statsmodels.sandbox.distributions.extras.ACSkewT\_gen.logsf =========================================================== `ACSkewT_gen.logsf(x, *args, **kwds)` Log of the survival function of the given RV. Returns the log of the “survival function,” defined as (1 - `cdf`), evaluated at `x`. | Parameters: | * **x** (*array\_like*) – quantiles * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **logsf** – Log of the survival function evaluated at `x`. | | Return type: | ndarray | statsmodels statsmodels.tsa.statespace.sarimax.SARIMAXResults.wald_test statsmodels.tsa.statespace.sarimax.SARIMAXResults.wald\_test ============================================================ `SARIMAXResults.wald_test(r_matrix, cov_p=None, scale=1.0, invcov=None, use_f=None)` Compute a Wald-test for a joint linear hypothesis. | Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) – + array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length p row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – Default is 1.0 for no scaling. * **invcov** (*array-like**,* *optional*) – A q x q array to specify an inverse covariance matrix based on a restrictions matrix. * **use\_f** (*bool*) – If True, then the F-distribution is used. If False, then the asymptotic distribution, chisquare is used. If use\_f is None, then the F distribution is used if the model specifies that use\_t is True. The test statistic is proportionally adjusted for the distribution by the number of constraints in the hypothesis. | | Returns: | **res** – The results for the test are attributes of this results instance. | | Return type: | ContrastResults instance | See also [`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`f_test`](statsmodels.tsa.statespace.sarimax.sarimaxresults.f_test#statsmodels.tsa.statespace.sarimax.SARIMAXResults.f_test "statsmodels.tsa.statespace.sarimax.SARIMAXResults.f_test"), [`t_test`](statsmodels.tsa.statespace.sarimax.sarimaxresults.t_test#statsmodels.tsa.statespace.sarimax.SARIMAXResults.t_test "statsmodels.tsa.statespace.sarimax.SARIMAXResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") #### Notes The matrix `r_matrix` is assumed to be non-singular. More precisely, r\_matrix (pX pX.T) r\_matrix.T is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full. statsmodels statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.simulate statsmodels.tsa.statespace.kalman\_smoother.KalmanSmoother.simulate =================================================================== `KalmanSmoother.simulate(nsimulations, measurement_shocks=None, state_shocks=None, initial_state=None)` Simulate a new time series following the state space model | Parameters: | * **nsimulations** (*int*) – The number of observations to simulate. If the model is time-invariant this can be any number. If the model is time-varying, then this number must be less than or equal to the number * **measurement\_shocks** (*array\_like**,* *optional*) – If specified, these are the shocks to the measurement equation, \(\varepsilon\_t\). If unspecified, these are automatically generated using a pseudo-random number generator. If specified, must be shaped `nsimulations` x `k_endog`, where `k_endog` is the same as in the state space model. * **state\_shocks** (*array\_like**,* *optional*) – If specified, these are the shocks to the state equation, \(\eta\_t\). If unspecified, these are automatically generated using a pseudo-random number generator. If specified, must be shaped `nsimulations` x `k_posdef` where `k_posdef` is the same as in the state space model. * **initial\_state** (*array\_like**,* *optional*) – If specified, this is the state vector at time zero, which should be shaped (`k_states` x 1), where `k_states` is the same as in the state space model. If unspecified, but the model has been initialized, then that initialization is used. If unspecified and the model has not been initialized, then a vector of zeros is used. Note that this is not included in the returned `simulated_states` array. | | Returns: | * **simulated\_obs** (*array*) – An (nsimulations x k\_endog) array of simulated observations. * **simulated\_states** (*array*) – An (nsimulations x k\_states) array of simulated states. | statsmodels statsmodels.discrete.discrete_model.NegativeBinomialResults.remove_data statsmodels.discrete.discrete\_model.NegativeBinomialResults.remove\_data ========================================================================= `NegativeBinomialResults.remove_data()` remove data arrays, all nobs arrays from result and model This reduces the size of the instance, so it can be pickled with less memory. Currently tested for use with predict from an unpickled results and model instance. Warning Since data and some intermediate results have been removed calculating new statistics that require them will raise exceptions. The exception will occur the first time an attribute is accessed that has been set to None. Not fully tested for time series models, tsa, and might delete too much for prediction or not all that would be possible. The lists of arrays to delete are maintained as attributes of the result and model instance, except for cached values. These lists could be changed before calling remove\_data. The attributes to remove are named in: `model._data_attr : arrays attached to both the model instance` and the results instance with the same attribute name. `result.data_in_cache : arrays that may exist as values in` result.\_cache (TODO : should privatize name) `result._data_attr_model : arrays attached to the model` instance but not to the results instance statsmodels statsmodels.sandbox.regression.gmm.GMMResults.pvalues statsmodels.sandbox.regression.gmm.GMMResults.pvalues ===================================================== `GMMResults.pvalues()` statsmodels statsmodels.stats.sandwich_covariance.se_cov statsmodels.stats.sandwich\_covariance.se\_cov ============================================== `statsmodels.stats.sandwich_covariance.se_cov(cov)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/moment_helpers.html#se_cov) get standard deviation from covariance matrix just a shorthand function np.sqrt(np.diag(cov)) | Parameters: | **cov** (*array\_like**,* *square*) – covariance matrix | | Returns: | **std** – standard deviation from diagonal of cov | | Return type: | ndarray | statsmodels statsmodels.discrete.discrete_model.GeneralizedPoissonResults.initialize statsmodels.discrete.discrete\_model.GeneralizedPoissonResults.initialize ========================================================================= `GeneralizedPoissonResults.initialize(model, params, **kwd)` statsmodels statsmodels.regression.linear_model.RegressionResults.remove_data statsmodels.regression.linear\_model.RegressionResults.remove\_data =================================================================== `RegressionResults.remove_data()` remove data arrays, all nobs arrays from result and model This reduces the size of the instance, so it can be pickled with less memory. Currently tested for use with predict from an unpickled results and model instance. Warning Since data and some intermediate results have been removed calculating new statistics that require them will raise exceptions. The exception will occur the first time an attribute is accessed that has been set to None. Not fully tested for time series models, tsa, and might delete too much for prediction or not all that would be possible. The lists of arrays to delete are maintained as attributes of the result and model instance, except for cached values. These lists could be changed before calling remove\_data. The attributes to remove are named in: `model._data_attr : arrays attached to both the model instance` and the results instance with the same attribute name. `result.data_in_cache : arrays that may exist as values in` result.\_cache (TODO : should privatize name) `result._data_attr_model : arrays attached to the model` instance but not to the results instance statsmodels statsmodels.graphics.functional.banddepth statsmodels.graphics.functional.banddepth ========================================= `statsmodels.graphics.functional.banddepth(data, method='MBD')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/graphics/functional.html#banddepth) Calculate the band depth for a set of functional curves. Band depth is an order statistic for functional data (see `fboxplot`), with a higher band depth indicating larger “centrality”. In analog to scalar data, the functional curve with highest band depth is called the median curve, and the band made up from the first N/2 of N curves is the 50% central region. | Parameters: | * **data** (*ndarray*) – The vectors of functions to create a functional boxplot from. The first axis is the function index, the second axis the one along which the function is defined. So `data[0, :]` is the first functional curve. * **method** (*{'MBD'**,* *'BD2'}**,* *optional*) – Whether to use the original band depth (with J=2) of [[1]](#id4) or the modified band depth. See Notes for details. | | Returns: | **depth** – Depth values for functional curves. | | Return type: | ndarray | #### Notes Functional band depth as an order statistic for functional data was proposed in [[1]](#id4) and applied to functional boxplots and bagplots in [[2]](#id5). The method ‘BD2’ checks for each curve whether it lies completely inside bands constructed from two curves. All permutations of two curves in the set of curves are used, and the band depth is normalized to one. Due to the complete curve having to fall within the band, this method yields a lot of ties. The method ‘MBD’ is similar to ‘BD2’, but checks the fraction of the curve falling within the bands. It therefore generates very few ties. #### References | | | | --- | --- | | [1] | *([1](#id1), [2](#id2))* S. Lopez-Pintado and J. Romo, “On the Concept of Depth for Functional Data”, Journal of the American Statistical Association, vol. 104, pp. 718-734, 2009. | | | | | --- | --- | | [[2]](#id3) | Y. Sun and M.G. Genton, “Functional Boxplots”, Journal of Computational and Graphical Statistics, vol. 20, pp. 1-19, 2011. | statsmodels statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.information statsmodels.discrete.count\_model.ZeroInflatedGeneralizedPoisson.information ============================================================================ `ZeroInflatedGeneralizedPoisson.information(params)` Fisher information matrix of model Returns -Hessian of loglike evaluated at params. statsmodels statsmodels.tsa.vector_ar.irf.IRAnalysis.H statsmodels.tsa.vector\_ar.irf.IRAnalysis.H =========================================== `IRAnalysis.H()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/irf.html#IRAnalysis.H) statsmodels statsmodels.discrete.discrete_model.DiscreteResults.t_test statsmodels.discrete.discrete\_model.DiscreteResults.t\_test ============================================================ `DiscreteResults.t_test(r_matrix, cov_p=None, scale=None, use_t=None)` Compute a t-test for a each linear hypothesis of the form Rb = q | Parameters: | * **r\_matrix** (*array-like**,* *str**,* *tuple*) – + array : If an array is given, a p x k 2d array or length k 1d array specifying the linear restrictions. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q). If q is given, can be either a scalar or a length p row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – An optional `scale` to use. Default is the scale specified by the model fit. * **use\_t** (*bool**,* *optional*) – If use\_t is None, then the default of the model is used. If use\_t is True, then the p-values are based on the t distribution. If use\_t is False, then the p-values are based on the normal distribution. | | Returns: | **res** – The results for the test are attributes of this results instance. The available results have the same elements as the parameter table in `summary()`. | | Return type: | ContrastResults instance | #### Examples ``` >>> import numpy as np >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> r = np.zeros_like(results.params) >>> r[5:] = [1,-1] >>> print(r) [ 0. 0. 0. 0. 0. 1. -1.] ``` r tests that the coefficients on the 5th and 6th independent variable are the same. ``` >>> T_test = results.t_test(r) >>> print(T_test) Test for Constraints ============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------ c0 -1829.2026 455.391 -4.017 0.003 -2859.368 -799.037 ============================================================================== >>> T_test.effect -1829.2025687192481 >>> T_test.sd 455.39079425193762 >>> T_test.tvalue -4.0167754636411717 >>> T_test.pvalue 0.0015163772380899498 ``` Alternatively, you can specify the hypothesis tests using a string ``` >>> from statsmodels.formula.api import ols >>> dta = sm.datasets.longley.load_pandas().data >>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' >>> results = ols(formula, dta).fit() >>> hypotheses = 'GNPDEFL = GNP, UNEMP = 2, YEAR/1829 = 1' >>> t_test = results.t_test(hypotheses) >>> print(t_test) Test for Constraints ============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------ c0 15.0977 84.937 0.178 0.863 -177.042 207.238 c1 -2.0202 0.488 -8.231 0.000 -3.125 -0.915 c2 1.0001 0.249 0.000 1.000 0.437 1.563 ============================================================================== ``` See also [`tvalues`](statsmodels.discrete.discrete_model.discreteresults.tvalues#statsmodels.discrete.discrete_model.DiscreteResults.tvalues "statsmodels.discrete.discrete_model.DiscreteResults.tvalues") individual t statistics [`f_test`](statsmodels.discrete.discrete_model.discreteresults.f_test#statsmodels.discrete.discrete_model.DiscreteResults.f_test "statsmodels.discrete.discrete_model.DiscreteResults.f_test") for F tests [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") statsmodels statsmodels.sandbox.stats.multicomp.qcrit statsmodels.sandbox.stats.multicomp.qcrit ========================================= `statsmodels.sandbox.stats.multicomp.qcrit = '\n 2 3 4 5 6 7 8 9 10\n5 3.64 5.70 4.60 6.98 5.22 7.80 5.67 8.42 6.03 8.91 6.33 9.32 6.58 9.67 6.80 9.97 6.99 10.24\n6 3.46 5.24 4.34 6.33 4.90 7.03 5.30 7.56 5.63 7.97 5.90 8.32 6.12 8.61 6.32 8.87 6.49 9.10\n7 3.34 4.95 4.16 5.92 4.68 6.54 5.06 7.01 5.36 7.37 5.61 7.68 5.82 7.94 6.00 8.17 6.16 8.37\n8 3.26 4.75 4.04 5.64 4.53 6.20 4.89 6.62 5.17 6.96 5.40 7.24 5.60 7.47 5.77 7.68 5.92 7.86\n9 3.20 4.60 3.95 5.43 4.41 5.96 4.76 6.35 5.02 6.66 5.24 6.91 5.43 7.13 5.59 7.33 5.74 7.49\n10 3.15 4.48 3.88 5.27 4.33 5.77 4.65 6.14 4.91 6.43 5.12 6.67 5.30 6.87 5.46 7.05 5.60 7.21\n11 3.11 4.39 3.82 5.15 4.26 5.62 4.57 5.97 4.82 6.25 5.03 6.48 5.20 6.67 5.35 6.84 5.49 6.99\n12 3.08 4.32 3.77 5.05 4.20 5.50 4.51 5.84 4.75 6.10 4.95 6.32 5.12 6.51 5.27 6.67 5.39 6.81\n13 3.06 4.26 3.73 4.96 4.15 5.40 4.45 5.73 4.69 5.98 4.88 6.19 5.05 6.37 5.19 6.53 5.32 6.67\n14 3.03 4.21 3.70 4.89 4.11 5.32 4.41 5.63 4.64 5.88 4.83 6.08 4.99 6.26 5.13 6.41 5.25 6.54\n15 3.01 4.17 3.67 4.84 4.08 5.25 4.37 5.56 4.59 5.80 4.78 5.99 4.94 6.16 5.08 6.31 5.20 6.44\n16 3.00 4.13 3.65 4.79 4.05 5.19 4.33 5.49 4.56 5.72 4.74 5.92 4.90 6.08 5.03 6.22 5.15 6.35\n17 2.98 4.10 3.63 4.74 4.02 5.14 4.30 5.43 4.52 5.66 4.70 5.85 4.86 6.01 4.99 6.15 5.11 6.27\n18 2.97 4.07 3.61 4.70 4.00 5.09 4.28 5.38 4.49 5.60 4.67 5.79 4.82 5.94 4.96 6.08 5.07 6.20\n19 2.96 4.05 3.59 4.67 3.98 5.05 4.25 5.33 4.47 5.55 4.65 5.73 4.79 5.89 4.92 6.02 5.04 6.14\n20 2.95 4.02 3.58 4.64 3.96 5.02 4.23 5.29 4.45 5.51 4.62 5.69 4.77 5.84 4.90 5.97 5.01 6.09\n24 2.92 3.96 3.53 4.55 3.90 4.91 4.17 5.17 4.37 5.37 4.54 5.54 4.68 5.69 4.81 5.81 4.92 5.92\n30 2.89 3.89 3.49 4.45 3.85 4.80 4.10 5.05 4.30 5.24 4.46 5.40 4.60 5.54 4.72 5.65 4.82 5.76\n40 2.86 3.82 3.44 4.37 3.79 4.70 4.04 4.93 4.23 5.11 4.39 5.26 4.52 5.39 4.63 5.50 4.73 5.60\n60 2.83 3.76 3.40 4.28 3.74 4.59 3.98 4.82 4.16 4.99 4.31 5.13 4.44 5.25 4.55 5.36 4.65 5.45\n120 2.80 3.70 3.36 4.20 3.68 4.50 3.92 4.71 4.10 4.87 4.24 5.01 4.36 5.12 4.47 5.21 4.56 5.30\ninfinity 2.77 3.64 3.31 4.12 3.63 4.40 3.86 4.60 4.03 4.76 4.17 4.88 4.29 4.99 4.39 5.08 4.47 5.16\n'` str(object=’‘) -> str str(bytes\_or\_buffer[, encoding[, errors]]) -> str Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.\_\_str\_\_() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to ‘strict’.
programming_docs
statsmodels statsmodels.tsa.statespace.mlemodel.MLEModel.predict statsmodels.tsa.statespace.mlemodel.MLEModel.predict ==================================================== `MLEModel.predict(params, exog=None, *args, **kwargs)` After a model has been fit predict returns the fitted values. This is a placeholder intended to be overwritten by individual models. statsmodels statsmodels.discrete.discrete_model.GeneralizedPoisson.predict statsmodels.discrete.discrete\_model.GeneralizedPoisson.predict =============================================================== `GeneralizedPoisson.predict(params, exog=None, exposure=None, offset=None, which='mean')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#GeneralizedPoisson.predict) Predict response variable of a count model given exogenous variables. #### Notes If exposure is specified, then it will be logged by the method. The user does not need to log it first. statsmodels statsmodels.discrete.count_model.ZeroInflatedNegativeBinomialResults.pvalues statsmodels.discrete.count\_model.ZeroInflatedNegativeBinomialResults.pvalues ============================================================================= `ZeroInflatedNegativeBinomialResults.pvalues()` statsmodels statsmodels.tsa.statespace.sarimax.SARIMAXResults.bic statsmodels.tsa.statespace.sarimax.SARIMAXResults.bic ===================================================== `SARIMAXResults.bic()` (float) Bayes Information Criterion statsmodels statsmodels.tsa.vector_ar.var_model.VARResults.plot_forecast statsmodels.tsa.vector\_ar.var\_model.VARResults.plot\_forecast =============================================================== `VARResults.plot_forecast(steps, alpha=0.05, plot_stderr=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/var_model.html#VARResults.plot_forecast) Plot forecast statsmodels statsmodels.sandbox.distributions.transformed.Transf_gen statsmodels.sandbox.distributions.transformed.Transf\_gen ========================================================= `class statsmodels.sandbox.distributions.transformed.Transf_gen(kls, func, funcinv, *args, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/distributions/transformed.html#Transf_gen) a class for non-linear monotonic transformation of a continuous random variable #### Methods | | | | --- | --- | | [`cdf`](statsmodels.sandbox.distributions.transformed.transf_gen.cdf#statsmodels.sandbox.distributions.transformed.Transf_gen.cdf "statsmodels.sandbox.distributions.transformed.Transf_gen.cdf")(x, \*args, \*\*kwds) | Cumulative distribution function of the given RV. | | [`entropy`](statsmodels.sandbox.distributions.transformed.transf_gen.entropy#statsmodels.sandbox.distributions.transformed.Transf_gen.entropy "statsmodels.sandbox.distributions.transformed.Transf_gen.entropy")(\*args, \*\*kwds) | Differential entropy of the RV. | | [`expect`](statsmodels.sandbox.distributions.transformed.transf_gen.expect#statsmodels.sandbox.distributions.transformed.Transf_gen.expect "statsmodels.sandbox.distributions.transformed.Transf_gen.expect")([func, args, loc, scale, lb, ub, …]) | Calculate expected value of a function with respect to the distribution. | | [`fit`](statsmodels.sandbox.distributions.transformed.transf_gen.fit#statsmodels.sandbox.distributions.transformed.Transf_gen.fit "statsmodels.sandbox.distributions.transformed.Transf_gen.fit")(data, \*args, \*\*kwds) | Return MLEs for shape (if applicable), location, and scale parameters from data. | | [`fit_loc_scale`](statsmodels.sandbox.distributions.transformed.transf_gen.fit_loc_scale#statsmodels.sandbox.distributions.transformed.Transf_gen.fit_loc_scale "statsmodels.sandbox.distributions.transformed.Transf_gen.fit_loc_scale")(data, \*args) | Estimate loc and scale parameters from data using 1st and 2nd moments. | | [`freeze`](statsmodels.sandbox.distributions.transformed.transf_gen.freeze#statsmodels.sandbox.distributions.transformed.Transf_gen.freeze "statsmodels.sandbox.distributions.transformed.Transf_gen.freeze")(\*args, \*\*kwds) | Freeze the distribution for the given arguments. | | [`interval`](statsmodels.sandbox.distributions.transformed.transf_gen.interval#statsmodels.sandbox.distributions.transformed.Transf_gen.interval "statsmodels.sandbox.distributions.transformed.Transf_gen.interval")(alpha, \*args, \*\*kwds) | Confidence interval with equal areas around the median. | | [`isf`](statsmodels.sandbox.distributions.transformed.transf_gen.isf#statsmodels.sandbox.distributions.transformed.Transf_gen.isf "statsmodels.sandbox.distributions.transformed.Transf_gen.isf")(q, \*args, \*\*kwds) | Inverse survival function (inverse of `sf`) at q of the given RV. | | [`logcdf`](statsmodels.sandbox.distributions.transformed.transf_gen.logcdf#statsmodels.sandbox.distributions.transformed.Transf_gen.logcdf "statsmodels.sandbox.distributions.transformed.Transf_gen.logcdf")(x, \*args, \*\*kwds) | Log of the cumulative distribution function at x of the given RV. | | [`logpdf`](statsmodels.sandbox.distributions.transformed.transf_gen.logpdf#statsmodels.sandbox.distributions.transformed.Transf_gen.logpdf "statsmodels.sandbox.distributions.transformed.Transf_gen.logpdf")(x, \*args, \*\*kwds) | Log of the probability density function at x of the given RV. | | [`logsf`](statsmodels.sandbox.distributions.transformed.transf_gen.logsf#statsmodels.sandbox.distributions.transformed.Transf_gen.logsf "statsmodels.sandbox.distributions.transformed.Transf_gen.logsf")(x, \*args, \*\*kwds) | Log of the survival function of the given RV. | | [`mean`](statsmodels.sandbox.distributions.transformed.transf_gen.mean#statsmodels.sandbox.distributions.transformed.Transf_gen.mean "statsmodels.sandbox.distributions.transformed.Transf_gen.mean")(\*args, \*\*kwds) | Mean of the distribution. | | [`median`](statsmodels.sandbox.distributions.transformed.transf_gen.median#statsmodels.sandbox.distributions.transformed.Transf_gen.median "statsmodels.sandbox.distributions.transformed.Transf_gen.median")(\*args, \*\*kwds) | Median of the distribution. | | [`moment`](statsmodels.sandbox.distributions.transformed.transf_gen.moment#statsmodels.sandbox.distributions.transformed.Transf_gen.moment "statsmodels.sandbox.distributions.transformed.Transf_gen.moment")(n, \*args, \*\*kwds) | n-th order non-central moment of distribution. | | [`nnlf`](statsmodels.sandbox.distributions.transformed.transf_gen.nnlf#statsmodels.sandbox.distributions.transformed.Transf_gen.nnlf "statsmodels.sandbox.distributions.transformed.Transf_gen.nnlf")(theta, x) | Return negative loglikelihood function. | | [`pdf`](statsmodels.sandbox.distributions.transformed.transf_gen.pdf#statsmodels.sandbox.distributions.transformed.Transf_gen.pdf "statsmodels.sandbox.distributions.transformed.Transf_gen.pdf")(x, \*args, \*\*kwds) | Probability density function at x of the given RV. | | [`ppf`](statsmodels.sandbox.distributions.transformed.transf_gen.ppf#statsmodels.sandbox.distributions.transformed.Transf_gen.ppf "statsmodels.sandbox.distributions.transformed.Transf_gen.ppf")(q, \*args, \*\*kwds) | Percent point function (inverse of `cdf`) at q of the given RV. | | [`rvs`](statsmodels.sandbox.distributions.transformed.transf_gen.rvs#statsmodels.sandbox.distributions.transformed.Transf_gen.rvs "statsmodels.sandbox.distributions.transformed.Transf_gen.rvs")(\*args, \*\*kwds) | Random variates of given type. | | [`sf`](statsmodels.sandbox.distributions.transformed.transf_gen.sf#statsmodels.sandbox.distributions.transformed.Transf_gen.sf "statsmodels.sandbox.distributions.transformed.Transf_gen.sf")(x, \*args, \*\*kwds) | Survival function (1 - `cdf`) at x of the given RV. | | [`stats`](statsmodels.sandbox.distributions.transformed.transf_gen.stats#statsmodels.sandbox.distributions.transformed.Transf_gen.stats "statsmodels.sandbox.distributions.transformed.Transf_gen.stats")(\*args, \*\*kwds) | Some statistics of the given RV. | | [`std`](statsmodels.sandbox.distributions.transformed.transf_gen.std#statsmodels.sandbox.distributions.transformed.Transf_gen.std "statsmodels.sandbox.distributions.transformed.Transf_gen.std")(\*args, \*\*kwds) | Standard deviation of the distribution. | | [`var`](statsmodels.sandbox.distributions.transformed.transf_gen.var#statsmodels.sandbox.distributions.transformed.Transf_gen.var "statsmodels.sandbox.distributions.transformed.Transf_gen.var")(\*args, \*\*kwds) | Variance of the distribution. | #### Attributes | | | | --- | --- | | `random_state` | Get or set the RandomState object for generating random variates. | statsmodels statsmodels.regression.quantile_regression.QuantRegResults.uncentered_tss statsmodels.regression.quantile\_regression.QuantRegResults.uncentered\_tss =========================================================================== `QuantRegResults.uncentered_tss()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/quantile_regression.html#QuantRegResults.uncentered_tss) statsmodels statsmodels.tsa.ar_model.AR statsmodels.tsa.ar\_model.AR ============================ `class statsmodels.tsa.ar_model.AR(endog, dates=None, freq=None, missing='none')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/ar_model.html#AR) Autoregressive AR(p) model | Parameters: | * **endog** (*array-like*) – 1-d endogenous response variable. The independent variable. * **dates** (*array-like of datetime**,* *optional*) – An array-like object of datetime objects. If a pandas object is given for endog or exog, it is assumed to have a DateIndex. * **freq** (*str**,* *optional*) – The frequency of the time-series. A Pandas offset or ‘B’, ‘D’, ‘W’, ‘M’, ‘A’, or ‘Q’. This is optional if dates are given. * **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.’ | #### Methods | | | | --- | --- | | [`fit`](statsmodels.tsa.ar_model.ar.fit#statsmodels.tsa.ar_model.AR.fit "statsmodels.tsa.ar_model.AR.fit")([maxlag, method, ic, trend, …]) | Fit the unconditional maximum likelihood of an AR(p) process. | | [`from_formula`](statsmodels.tsa.ar_model.ar.from_formula#statsmodels.tsa.ar_model.AR.from_formula "statsmodels.tsa.ar_model.AR.from_formula")(formula, data[, subset, drop\_cols]) | Create a Model from a formula and dataframe. | | [`hessian`](statsmodels.tsa.ar_model.ar.hessian#statsmodels.tsa.ar_model.AR.hessian "statsmodels.tsa.ar_model.AR.hessian")(params) | Returns numerical hessian for now. | | [`information`](statsmodels.tsa.ar_model.ar.information#statsmodels.tsa.ar_model.AR.information "statsmodels.tsa.ar_model.AR.information")(params) | Not Implemented Yet | | [`initialize`](statsmodels.tsa.ar_model.ar.initialize#statsmodels.tsa.ar_model.AR.initialize "statsmodels.tsa.ar_model.AR.initialize")() | Initialize (possibly re-initialize) a Model instance. | | [`loglike`](statsmodels.tsa.ar_model.ar.loglike#statsmodels.tsa.ar_model.AR.loglike "statsmodels.tsa.ar_model.AR.loglike")(params) | The loglikelihood of an AR(p) process | | [`predict`](statsmodels.tsa.ar_model.ar.predict#statsmodels.tsa.ar_model.AR.predict "statsmodels.tsa.ar_model.AR.predict")(params[, start, end, dynamic]) | Returns in-sample and out-of-sample prediction. | | [`score`](statsmodels.tsa.ar_model.ar.score#statsmodels.tsa.ar_model.AR.score "statsmodels.tsa.ar_model.AR.score")(params) | Return the gradient of the loglikelihood at params. | | [`select_order`](statsmodels.tsa.ar_model.ar.select_order#statsmodels.tsa.ar_model.AR.select_order "statsmodels.tsa.ar_model.AR.select_order")(maxlag, ic[, trend, method]) | Select the lag order according to the information criterion. | #### Attributes | | | | --- | --- | | `endog_names` | Names of endogenous variables | | `exog_names` | | statsmodels statsmodels.discrete.discrete_model.LogitResults.wald_test_terms statsmodels.discrete.discrete\_model.LogitResults.wald\_test\_terms =================================================================== `LogitResults.wald_test_terms(skip_single=False, extra_constraints=None, combine_terms=None)` Compute a sequence of Wald tests for terms over multiple columns This computes joined Wald tests for the hypothesis that all coefficients corresponding to a `term` are zero. `Terms` are defined by the underlying formula or by string matching. | Parameters: | * **skip\_single** (*boolean*) – If true, then terms that consist only of a single column and, therefore, refers only to a single parameter is skipped. If false, then all terms are included. * **extra\_constraints** (*ndarray*) – not tested yet * **combine\_terms** (*None* *or* *list of strings*) – Each string in this list is matched to the name of the terms or the name of the exogenous variables. All columns whose name includes that string are combined in one joint test. | | Returns: | **test\_result** – The result instance contains `table` which is a pandas DataFrame with the test results: test statistic, degrees of freedom and pvalues. | | Return type: | result instance | #### Examples ``` >>> res_ols = ols("np.log(Days+1) ~ C(Duration, Sum)*C(Weight, Sum)", data).fit() >>> res_ols.wald_test_terms() <class 'statsmodels.stats.contrast.WaldTestResults'> F P>F df constraint df denom Intercept 279.754525 2.37985521351e-22 1 51 C(Duration, Sum) 5.367071 0.0245738436636 1 51 C(Weight, Sum) 12.432445 3.99943118767e-05 2 51 C(Duration, Sum):C(Weight, Sum) 0.176002 0.83912310946 2 51 ``` ``` >>> res_poi = Poisson.from_formula("Days ~ C(Weight) * C(Duration)", data).fit(cov_type='HC0') >>> wt = res_poi.wald_test_terms(skip_single=False, combine_terms=['Duration', 'Weight']) >>> print(wt) chi2 P>chi2 df constraint Intercept 15.695625 7.43960374424e-05 1 C(Weight) 16.132616 0.000313940174705 2 C(Duration) 1.009147 0.315107378931 1 C(Weight):C(Duration) 0.216694 0.897315972824 2 Duration 11.187849 0.010752286833 3 Weight 30.263368 4.32586407145e-06 4 ``` statsmodels statsmodels.sandbox.stats.multicomp.varcorrection_unbalanced statsmodels.sandbox.stats.multicomp.varcorrection\_unbalanced ============================================================= `statsmodels.sandbox.stats.multicomp.varcorrection_unbalanced(nobs_all, srange=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/multicomp.html#varcorrection_unbalanced) correction factor for variance with unequal sample sizes this is just a harmonic mean | Parameters: | * **nobs\_all** (*array\_like*) – The number of observations for each sample * **srange** (*bool*) – if true, then the correction is divided by the number of samples for the variance of the studentized range statistic | | Returns: | **correction** – Correction factor for variance. | | Return type: | float | #### Notes variance correction factor is 1/k \* sum\_i 1/n\_i where k is the number of samples and summation is over i=0,…,k-1. If all n\_i are the same, then the correction factor is 1. This needs to be multiplied by the joint variance estimate, means square error, MSE. To obtain the correction factor for the standard deviation, square root needs to be taken. statsmodels statsmodels.tsa.ar_model.ARResults.roots statsmodels.tsa.ar\_model.ARResults.roots ========================================= `ARResults.roots()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/ar_model.html#ARResults.roots) statsmodels statsmodels.stats.diagnostic.compare_cox statsmodels.stats.diagnostic.compare\_cox ========================================= `statsmodels.stats.diagnostic.compare_cox = <statsmodels.sandbox.stats.diagnostic.CompareCox object>` Cox Test for non-nested models | Parameters: | * **results\_x** (*Result instance*) – result instance of first model * **results\_z** (*Result instance*) – result instance of second model * **attach** (*bool*) – | Formulas from Greene, section 8.3.4 translated to code produces correct results for Example 8.3, Greene statsmodels statsmodels.stats.weightstats.ttost_paired statsmodels.stats.weightstats.ttost\_paired =========================================== `statsmodels.stats.weightstats.ttost_paired(x1, x2, low, upp, transform=None, weights=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/weightstats.html#ttost_paired) test of (non-)equivalence for two dependent, paired sample TOST: two one-sided t tests null hypothesis: md < low or md > upp alternative hypothesis: low < md < upp where md is the mean, expected value of the difference x1 - x2 If the pvalue is smaller than a threshold,say 0.05, then we reject the hypothesis that the difference between the two samples is larger than the the thresholds given by low and upp. | Parameters: | * **x2** (*x1**,*) – two dependent samples * **upp** (*low**,*) – equivalence interval low < mean of difference < upp * **weights** (*None* *or* *ndarray*) – case weights for the two samples. For details on weights see `DescrStatsW` * **transform** (*None* *or* *function*) – If None (default), then the data is not transformed. Given a function sample data and thresholds are transformed. If transform is log the the equivalence interval is in ratio: low < x1 / x2 < upp | | Returns: | * **pvalue** (*float*) – pvalue of the non-equivalence test * **t1, pv1, df1** (*tuple*) – test statistic, pvalue and degrees of freedom for lower threshold test * **t2, pv2, df2** (*tuple*) – test statistic, pvalue and degrees of freedom for upper threshold test | statsmodels statsmodels.regression.recursive_ls.RecursiveLS.information statsmodels.regression.recursive\_ls.RecursiveLS.information ============================================================ `RecursiveLS.information(params)` Fisher information matrix of model Returns -Hessian of loglike evaluated at params. statsmodels statsmodels.graphics.factorplots.interaction_plot statsmodels.graphics.factorplots.interaction\_plot ================================================== `statsmodels.graphics.factorplots.interaction_plot(x, trace, response, func=<function mean>, ax=None, plottype='b', xlabel=None, ylabel=None, colors=None, markers=None, linestyles=None, legendloc='best', legendtitle=None, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/graphics/factorplots.html#interaction_plot) Interaction plot for factor level statistics. Note. If categorial factors are supplied levels will be internally recoded to integers. This ensures matplotlib compatiblity. uses pandas.DataFrame to calculate an `aggregate` statistic for each level of the factor or group given by `trace`. | Parameters: | * **x** (*array-like*) – The `x` factor levels constitute the x-axis. If a `pandas.Series` is given its name will be used in `xlabel` if `xlabel` is None. * **trace** (*array-like*) – The `trace` factor levels will be drawn as lines in the plot. If `trace` is a `pandas.Series` its name will be used as the `legendtitle` if `legendtitle` is None. * **response** (*array-like*) – The reponse or dependent variable. If a `pandas.Series` is given its name will be used in `ylabel` if `ylabel` is None. * **func** (*function*) – Anything accepted by `pandas.DataFrame.aggregate`. This is applied to the response variable grouped by the trace levels. * **plottype** (*str {'line'**,* *'scatter'**,* *'both'}**,* *optional*) – The type of plot to return. Can be ‘l’, ‘s’, or ‘b’ * **ax** (*axes**,* *optional*) – Matplotlib axes instance * **xlabel** (*str**,* *optional*) – Label to use for `x`. Default is ‘X’. If `x` is a `pandas.Series` it will use the series names. * **ylabel** (*str**,* *optional*) – Label to use for `response`. Default is ‘func of response’. If `response` is a `pandas.Series` it will use the series names. * **colors** (*list**,* *optional*) – If given, must have length == number of levels in trace. * **linestyles** (*list**,* *optional*) – If given, must have length == number of levels in trace. * **markers** (*list**,* *optional*) – If given, must have length == number of lovels in trace * **kwargs** – These will be passed to the plot command used either plot or scatter. If you want to control the overall plotting options, use kwargs. | | Returns: | **fig** – The figure given by `ax.figure` or a new instance. | | Return type: | Figure | #### Examples ``` >>> import numpy as np >>> np.random.seed(12345) >>> weight = np.random.randint(1,4,size=60) >>> duration = np.random.randint(1,3,size=60) >>> days = np.log(np.random.randint(1,30, size=60)) >>> fig = interaction_plot(weight, duration, days, ... colors=['red','blue'], markers=['D','^'], ms=10) >>> import matplotlib.pyplot as plt >>> plt.show() ``` ([Source code](statsmodels-graphics-factorplots-interaction_plot-1.py), [png](statsmodels-graphics-factorplots-interaction_plot-1.png), [hires.png](statsmodels-graphics-factorplots-interaction_plot-1.hires.png), [pdf](statsmodels-graphics-factorplots-interaction_plot-1.pdf))
programming_docs
statsmodels statsmodels.miscmodels.count.PoissonOffsetGMLE.hessian statsmodels.miscmodels.count.PoissonOffsetGMLE.hessian ====================================================== `PoissonOffsetGMLE.hessian(params)` Hessian of log-likelihood evaluated at params statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.conf_int statsmodels.sandbox.regression.gmm.IVRegressionResults.conf\_int ================================================================ `IVRegressionResults.conf_int(alpha=0.05, cols=None)` Returns the confidence interval of the fitted parameters. | Parameters: | * **alpha** (*float**,* *optional*) – The `alpha` level for the confidence interval. ie., The default `alpha` = .05 returns a 95% confidence interval. * **cols** (*array-like**,* *optional*) – `cols` specifies which confidence intervals to return | #### Notes The confidence interval is based on Student’s t-distribution. statsmodels statsmodels.stats.anova.anova_lm statsmodels.stats.anova.anova\_lm ================================= `statsmodels.stats.anova.anova_lm(*args, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/anova.html#anova_lm) 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*) * *A DataFrame containing.* | #### 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", "car", 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) ``` statsmodels statsmodels.stats.weightstats.CompareMeans statsmodels.stats.weightstats.CompareMeans ========================================== `class statsmodels.stats.weightstats.CompareMeans(d1, d2)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/weightstats.html#CompareMeans) class for two sample comparison The tests and the confidence interval work for multi-endpoint comparison: If d1 and d2 have the same number of rows, then each column of the data in d1 is compared with the corresponding column in d2. | Parameters: | **d2** (*d1**,*) – | #### Notes The result for the statistical tests and the confidence interval are independent of the user specified ddof. TODO: Extend to any number of groups or write a version that works in that case, like in SAS and SPSS. #### Methods | | | | --- | --- | | [`dof_satt`](statsmodels.stats.weightstats.comparemeans.dof_satt#statsmodels.stats.weightstats.CompareMeans.dof_satt "statsmodels.stats.weightstats.CompareMeans.dof_satt")() | degrees of freedom of Satterthwaite for unequal variance | | [`from_data`](statsmodels.stats.weightstats.comparemeans.from_data#statsmodels.stats.weightstats.CompareMeans.from_data "statsmodels.stats.weightstats.CompareMeans.from_data")(data1, data2[, weights1, …]) | construct a CompareMeans object from data | | [`std_meandiff_pooledvar`](statsmodels.stats.weightstats.comparemeans.std_meandiff_pooledvar#statsmodels.stats.weightstats.CompareMeans.std_meandiff_pooledvar "statsmodels.stats.weightstats.CompareMeans.std_meandiff_pooledvar")() | variance assuming equal variance in both data sets | | [`std_meandiff_separatevar`](statsmodels.stats.weightstats.comparemeans.std_meandiff_separatevar#statsmodels.stats.weightstats.CompareMeans.std_meandiff_separatevar "statsmodels.stats.weightstats.CompareMeans.std_meandiff_separatevar")() | | | [`summary`](statsmodels.stats.weightstats.comparemeans.summary#statsmodels.stats.weightstats.CompareMeans.summary "statsmodels.stats.weightstats.CompareMeans.summary")([use\_t, alpha, usevar, value]) | summarize the results of the hypothesis test | | [`tconfint_diff`](statsmodels.stats.weightstats.comparemeans.tconfint_diff#statsmodels.stats.weightstats.CompareMeans.tconfint_diff "statsmodels.stats.weightstats.CompareMeans.tconfint_diff")([alpha, alternative, usevar]) | confidence interval for the difference in means | | [`ttest_ind`](statsmodels.stats.weightstats.comparemeans.ttest_ind#statsmodels.stats.weightstats.CompareMeans.ttest_ind "statsmodels.stats.weightstats.CompareMeans.ttest_ind")([alternative, usevar, value]) | ttest for the null hypothesis of identical means | | [`ttost_ind`](statsmodels.stats.weightstats.comparemeans.ttost_ind#statsmodels.stats.weightstats.CompareMeans.ttost_ind "statsmodels.stats.weightstats.CompareMeans.ttost_ind")(low, upp[, usevar]) | test of equivalence for two independent samples, base on t-test | | [`zconfint_diff`](statsmodels.stats.weightstats.comparemeans.zconfint_diff#statsmodels.stats.weightstats.CompareMeans.zconfint_diff "statsmodels.stats.weightstats.CompareMeans.zconfint_diff")([alpha, alternative, usevar]) | confidence interval for the difference in means | | [`ztest_ind`](statsmodels.stats.weightstats.comparemeans.ztest_ind#statsmodels.stats.weightstats.CompareMeans.ztest_ind "statsmodels.stats.weightstats.CompareMeans.ztest_ind")([alternative, usevar, value]) | z-test for the null hypothesis of identical means | | [`ztost_ind`](statsmodels.stats.weightstats.comparemeans.ztost_ind#statsmodels.stats.weightstats.CompareMeans.ztost_ind "statsmodels.stats.weightstats.CompareMeans.ztost_ind")(low, upp[, usevar]) | test of equivalence for two independent samples, based on z-test | statsmodels statsmodels.genmod.cov_struct.CovStruct.update statsmodels.genmod.cov\_struct.CovStruct.update =============================================== `CovStruct.update(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/cov_struct.html#CovStruct.update) Updates the association parameter values based on the current regression coefficients. | Parameters: | **params** (*array-like*) – Working values for the regression parameters. | statsmodels statsmodels.sandbox.distributions.extras.ACSkewT_gen.cdf statsmodels.sandbox.distributions.extras.ACSkewT\_gen.cdf ========================================================= `ACSkewT_gen.cdf(x, *args, **kwds)` Cumulative distribution function of the given RV. | Parameters: | * **x** (*array\_like*) – quantiles * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **cdf** – Cumulative distribution function evaluated at `x` | | Return type: | ndarray | statsmodels statsmodels.sandbox.distributions.extras.skewnorm2 statsmodels.sandbox.distributions.extras.skewnorm2 ================================================== `statsmodels.sandbox.distributions.extras.skewnorm2 = <statsmodels.sandbox.distributions.extras.SkewNorm2_gen object>` univariate Skew-Normal distribution of Azzalini class follows scipy.stats.distributions pattern statsmodels statsmodels.regression.recursive_ls.RecursiveLSResults.forecast statsmodels.regression.recursive\_ls.RecursiveLSResults.forecast ================================================================ `RecursiveLSResults.forecast(steps=1, **kwargs)` Out-of-sample forecasts | Parameters: | * **steps** (*int**,* *str**, or* *datetime**,* *optional*) – If an integer, the number of steps to forecast from the end of the sample. Can also be a date string to parse or a datetime type. However, if the dates index does not have a fixed frequency, steps must be an integer. Default * **\*\*kwargs** – Additional arguments may required for forecasting beyond the end of the sample. See `FilterResults.predict` for more details. | | Returns: | **forecast** – Array of out of sample forecasts. A (steps x k\_endog) array. | | Return type: | array | statsmodels statsmodels.tsa.arima_model.ARMAResults.resid statsmodels.tsa.arima\_model.ARMAResults.resid ============================================== `ARMAResults.resid()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_model.html#ARMAResults.resid) statsmodels statsmodels.regression.recursive_ls.RecursiveLSResults.initialize statsmodels.regression.recursive\_ls.RecursiveLSResults.initialize ================================================================== `RecursiveLSResults.initialize(model, params, **kwd)` statsmodels statsmodels.sandbox.regression.gmm.LinearIVGMM.from_formula statsmodels.sandbox.regression.gmm.LinearIVGMM.from\_formula ============================================================ `classmethod LinearIVGMM.from_formula(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** (*extra arguments*) – These are passed to the model * **kwargs** (*extra keyword arguments*) – These are passed to the model with one exception. The `eval_env` keyword is passed to patsy. It can be either a [`patsy.EvalEnvironment`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.EvalEnvironment "(in patsy v0.5.0+dev)") 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** | | Return type: | 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 statsmodels.discrete.discrete_model.DiscreteResults.normalized_cov_params statsmodels.discrete.discrete\_model.DiscreteResults.normalized\_cov\_params ============================================================================ `DiscreteResults.normalized_cov_params()` statsmodels statsmodels.sandbox.distributions.transformed.TransfTwo_gen.fit_loc_scale statsmodels.sandbox.distributions.transformed.TransfTwo\_gen.fit\_loc\_scale ============================================================================ `TransfTwo_gen.fit_loc_scale(data, *args)` Estimate loc and scale parameters from data using 1st and 2nd moments. | Parameters: | * **data** (*array\_like*) – Data to fit. * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information). | | Returns: | * **Lhat** (*float*) – Estimated location parameter for the data. * **Shat** (*float*) – Estimated scale parameter for the data. | statsmodels statsmodels.discrete.discrete_model.ProbitResults.t_test_pairwise statsmodels.discrete.discrete\_model.ProbitResults.t\_test\_pairwise ==================================================================== `ProbitResults.t_test_pairwise(term_name, method='hs', alpha=0.05, factor_labels=None)` perform pairwise t\_test with multiple testing corrected p-values This uses the formula design\_info encoding contrast matrix and should work for all encodings of a main effect. | Parameters: | * **result** (*result instance*) – The results of an estimated model with a categorical main effect. * **term\_name** (*str*) – name of the term for which pairwise comparisons are computed. Term names for categorical effects are created by patsy and correspond to the main part of the exog names. * **method** (*str* *or* *list of strings*) – multiple testing p-value correction, default is ‘hs’, see stats.multipletesting * **alpha** (*float*) – significance level for multiple testing reject decision. * **factor\_labels** (*None**,* *list of str*) – Labels for the factor levels used for pairwise labels. If not provided, then the labels from the formula design\_info are used. | | Returns: | **results** – The results are stored as attributes, the main attributes are the following two. Other attributes are added for debugging purposes or as background information.* result\_frame : pandas DataFrame with t\_test results and multiple testing corrected p-values. * contrasts : matrix of constraints of the null hypothesis in the t\_test. | | Return type: | instance of a simple Results class | #### Notes Status: experimental. Currently only checked for treatment coding with and without specified reference level. Currently there are no multiple testing corrected confidence intervals available. #### Examples ``` >>> res = ols("np.log(Days+1) ~ C(Weight) + C(Duration)", data).fit() >>> pw = res.t_test_pairwise("C(Weight)") >>> pw.result_frame coef std err t P>|t| Conf. Int. Low 2-1 0.632315 0.230003 2.749157 8.028083e-03 0.171563 3-1 1.302555 0.230003 5.663201 5.331513e-07 0.841803 3-2 0.670240 0.230003 2.914044 5.119126e-03 0.209488 Conf. Int. Upp. pvalue-hs reject-hs 2-1 1.093067 0.010212 True 3-1 1.763307 0.000002 True 3-2 1.130992 0.010212 True ``` statsmodels statsmodels.regression.linear_model.GLS.whiten statsmodels.regression.linear\_model.GLS.whiten =============================================== `GLS.whiten(X)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#GLS.whiten) GLS whiten method. | Parameters: | **X** (*array-like*) – Data to be whitened. | | Returns: | | | Return type: | np.dot(cholsigmainv,X) | See also `regression.GLS` statsmodels statsmodels.sandbox.regression.try_catdata.labelmeanfilter_nd statsmodels.sandbox.regression.try\_catdata.labelmeanfilter\_nd =============================================================== `statsmodels.sandbox.regression.try_catdata.labelmeanfilter_nd(y, x)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/try_catdata.html#labelmeanfilter_nd) statsmodels statsmodels.tsa.statespace.sarimax.SARIMAX.loglike statsmodels.tsa.statespace.sarimax.SARIMAX.loglike ================================================== `SARIMAX.loglike(params, *args, **kwargs)` Loglikelihood evaluation | Parameters: | * **params** (*array\_like*) – Array of parameters at which to evaluate the loglikelihood function. * **transformed** (*boolean**,* *optional*) – Whether or not `params` is already transformed. Default is True. * **kwargs** – Additional keyword arguments to pass to the Kalman filter. See `KalmanFilter.filter` for more details. | #### Notes [[1]](#id2) recommend maximizing the average likelihood to avoid scale issues; this is done automatically by the base Model fit method. #### References | | | | --- | --- | | [[1]](#id1) | Koopman, Siem Jan, Neil Shephard, and Jurgen A. Doornik. 1999. Statistical Algorithms for Models in State Space Using SsfPack 2.2. Econometrics Journal 2 (1): 107-60. doi:10.1111/1368-423X.00023. | See also [`update`](statsmodels.tsa.statespace.sarimax.sarimax.update#statsmodels.tsa.statespace.sarimax.SARIMAX.update "statsmodels.tsa.statespace.sarimax.SARIMAX.update") modifies the internal state of the state space model to reflect new params statsmodels statsmodels.sandbox.tsa.fftarma.ArmaFft.fftma statsmodels.sandbox.tsa.fftarma.ArmaFft.fftma ============================================= `ArmaFft.fftma(n)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/tsa/fftarma.html#ArmaFft.fftma) Fourier transform of MA polynomial, zero-padded at end to n | Parameters: | **n** (*int*) – length of array after zero-padding | | Returns: | **fftar** – fft of zero-padded ar polynomial | | Return type: | ndarray | statsmodels statsmodels.tsa.vector_ar.var_model.VARResults.bse statsmodels.tsa.vector\_ar.var\_model.VARResults.bse ==================================================== `VARResults.bse()` Standard errors of coefficients, reshaped to match in size statsmodels statsmodels.tsa.vector_ar.var_model.VARResults.fevd statsmodels.tsa.vector\_ar.var\_model.VARResults.fevd ===================================================== `VARResults.fevd(periods=10, var_decomp=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/var_model.html#VARResults.fevd) Compute forecast error variance decomposition (“fevd”) | Returns: | **fevd** | | Return type: | FEVD instance | statsmodels statsmodels.tsa.statespace.structural.UnobservedComponentsResults.wald_test_terms statsmodels.tsa.statespace.structural.UnobservedComponentsResults.wald\_test\_terms =================================================================================== `UnobservedComponentsResults.wald_test_terms(skip_single=False, extra_constraints=None, combine_terms=None)` Compute a sequence of Wald tests for terms over multiple columns This computes joined Wald tests for the hypothesis that all coefficients corresponding to a `term` are zero. `Terms` are defined by the underlying formula or by string matching. | Parameters: | * **skip\_single** (*boolean*) – If true, then terms that consist only of a single column and, therefore, refers only to a single parameter is skipped. If false, then all terms are included. * **extra\_constraints** (*ndarray*) – not tested yet * **combine\_terms** (*None* *or* *list of strings*) – Each string in this list is matched to the name of the terms or the name of the exogenous variables. All columns whose name includes that string are combined in one joint test. | | Returns: | **test\_result** – The result instance contains `table` which is a pandas DataFrame with the test results: test statistic, degrees of freedom and pvalues. | | Return type: | result instance | #### Examples ``` >>> res_ols = ols("np.log(Days+1) ~ C(Duration, Sum)*C(Weight, Sum)", data).fit() >>> res_ols.wald_test_terms() <class 'statsmodels.stats.contrast.WaldTestResults'> F P>F df constraint df denom Intercept 279.754525 2.37985521351e-22 1 51 C(Duration, Sum) 5.367071 0.0245738436636 1 51 C(Weight, Sum) 12.432445 3.99943118767e-05 2 51 C(Duration, Sum):C(Weight, Sum) 0.176002 0.83912310946 2 51 ``` ``` >>> res_poi = Poisson.from_formula("Days ~ C(Weight) * C(Duration)", data).fit(cov_type='HC0') >>> wt = res_poi.wald_test_terms(skip_single=False, combine_terms=['Duration', 'Weight']) >>> print(wt) chi2 P>chi2 df constraint Intercept 15.695625 7.43960374424e-05 1 C(Weight) 16.132616 0.000313940174705 2 C(Duration) 1.009147 0.315107378931 1 C(Weight):C(Duration) 0.216694 0.897315972824 2 Duration 11.187849 0.010752286833 3 Weight 30.263368 4.32586407145e-06 4 ```
programming_docs
statsmodels statsmodels.genmod.generalized_estimating_equations.GEEResults.load statsmodels.genmod.generalized\_estimating\_equations.GEEResults.load ===================================================================== `classmethod GEEResults.load(fname)` load a pickle, (class method) | Parameters: | **fname** (*string* *or* *filehandle*) – fname can be a string to a file path or filename, or a filehandle. | | Returns: | | | Return type: | unpickled instance | statsmodels statsmodels.tsa.arima_model.ARMAResults.bic statsmodels.tsa.arima\_model.ARMAResults.bic ============================================ `ARMAResults.bic()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_model.html#ARMAResults.bic) statsmodels statsmodels.stats.power.FTestPower.power statsmodels.stats.power.FTestPower.power ======================================== `FTestPower.power(effect_size, df_num, df_denom, alpha, ncc=1)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/power.html#FTestPower.power) Calculate the power of a F-test. | Parameters: | * **effect\_size** (*float*) – standardized effect size, mean divided by the standard deviation. effect size has to be positive. * **df\_num** (*int* *or* *float*) – numerator degrees of freedom. * **df\_denom** (*int* *or* *float*) – denominator degrees of freedom. * **alpha** (*float in interval* *(**0**,**1**)*) – significance level, e.g. 0.05, is the probability of a type I error, that is wrong rejections if the Null Hypothesis is true. * **ncc** (*int*) – degrees of freedom correction for non-centrality parameter. see Notes | | Returns: | **power** – Power of the test, e.g. 0.8, is one minus the probability of a type II error. Power is the probability that the test correctly rejects the Null Hypothesis if the Alternative Hypothesis is true. | | Return type: | float | #### Notes sample size is given implicitly by df\_num set ncc=0 to match t-test, or f-test in LikelihoodModelResults. ncc=1 matches the non-centrality parameter in R::pwr::pwr.f2.test ftest\_power with ncc=0 should also be correct for f\_test in regression models, with df\_num and d\_denom as defined there. (not verified yet) statsmodels statsmodels.tsa.statespace.mlemodel.MLEModel.update statsmodels.tsa.statespace.mlemodel.MLEModel.update =================================================== `MLEModel.update(params, transformed=True, complex_step=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEModel.update) Update the parameters of the model | Parameters: | * **params** (*array\_like*) – Array of new parameters. * **transformed** (*boolean**,* *optional*) – Whether or not `params` is already transformed. If set to False, `transform_params` is called. Default is True. | | Returns: | **params** – Array of parameters. | | Return type: | array\_like | #### Notes Since Model is a base class, this method should be overridden by subclasses to perform actual updating steps. statsmodels statsmodels.tsa.statespace.tools.validate_vector_shape statsmodels.tsa.statespace.tools.validate\_vector\_shape ======================================================== `statsmodels.tsa.statespace.tools.validate_vector_shape(name, shape, nrows, nobs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/tools.html#validate_vector_shape) Validate the shape of a possibly time-varying vector, or raise an exception | Parameters: | * **name** (*str*) – The name of the vector being validated (used in exception messages) * **shape** (*array\_like*) – The shape of the vector to be validated. May be of size 1 or (if the vector is time-varying) 2. * **nrows** (*int*) – The expected number of rows (elements of the vector). * **nobs** (*int*) – The number of observations (used to validate the last dimension of a time-varying vector) | | Raises: | [`ValueError`](https://docs.python.org/3.2/library/exceptions.html#ValueError "(in Python v3.2)") – If the vector is not of the desired shape. | statsmodels statsmodels.genmod.families.family.Gaussian.resid_anscombe statsmodels.genmod.families.family.Gaussian.resid\_anscombe =========================================================== `Gaussian.resid_anscombe(endog, mu, var_weights=1.0, scale=1.0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/family.html#Gaussian.resid_anscombe) The Anscombe residuals | Parameters: | * **endog** (*array*) – The endogenous response variable * **mu** (*array*) – The inverse of the link function at the linear predicted values. * **var\_weights** (*array-like*) – 1d array of variance (analytic) weights. The default is 1. * **scale** (*float**,* *optional*) – An optional argument to divide the residuals by sqrt(scale). The default is 1. | | Returns: | **resid\_anscombe** – The Anscombe residuals for the Gaussian family defined below | | Return type: | array | #### Notes For the Gaussian distribution, Anscombe residuals are the same as deviance residuals. \[resid\\_anscombe\_i = (Y\_i - \mu\_i) / \sqrt{scale} \* \sqrt(var\\_weights)\] statsmodels statsmodels.tsa.statespace.mlemodel.MLEModel.untransform_params statsmodels.tsa.statespace.mlemodel.MLEModel.untransform\_params ================================================================ `MLEModel.untransform_params(constrained)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEModel.untransform_params) Transform constrained parameters used in likelihood evaluation to unconstrained parameters used by the optimizer | Parameters: | **constrained** (*array\_like*) – Array of constrained parameters used in likelihood evalution, to be transformed. | | Returns: | **unconstrained** – Array of unconstrained parameters used by the optimizer. | | Return type: | array\_like | #### Notes This is a noop in the base class, subclasses should override where appropriate. statsmodels statsmodels.sandbox.distributions.transformed.LogTransf_gen.std statsmodels.sandbox.distributions.transformed.LogTransf\_gen.std ================================================================ `LogTransf_gen.std(*args, **kwds)` Standard deviation of the distribution. | Parameters: | * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **std** – standard deviation of the distribution | | Return type: | float | statsmodels statsmodels.stats.mediation.MediationResults.summary statsmodels.stats.mediation.MediationResults.summary ==================================================== `MediationResults.summary(alpha=0.05)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/mediation.html#MediationResults.summary) Provide a summary of a mediation analysis. statsmodels statsmodels.regression.linear_model.RegressionResults.t_test statsmodels.regression.linear\_model.RegressionResults.t\_test ============================================================== `RegressionResults.t_test(r_matrix, cov_p=None, scale=None, use_t=None)` Compute a t-test for a each linear hypothesis of the form Rb = q | Parameters: | * **r\_matrix** (*array-like**,* *str**,* *tuple*) – + array : If an array is given, a p x k 2d array or length k 1d array specifying the linear restrictions. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q). If q is given, can be either a scalar or a length p row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – An optional `scale` to use. Default is the scale specified by the model fit. * **use\_t** (*bool**,* *optional*) – If use\_t is None, then the default of the model is used. If use\_t is True, then the p-values are based on the t distribution. If use\_t is False, then the p-values are based on the normal distribution. | | Returns: | **res** – The results for the test are attributes of this results instance. The available results have the same elements as the parameter table in `summary()`. | | Return type: | ContrastResults instance | #### Examples ``` >>> import numpy as np >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> r = np.zeros_like(results.params) >>> r[5:] = [1,-1] >>> print(r) [ 0. 0. 0. 0. 0. 1. -1.] ``` r tests that the coefficients on the 5th and 6th independent variable are the same. ``` >>> T_test = results.t_test(r) >>> print(T_test) Test for Constraints ============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------ c0 -1829.2026 455.391 -4.017 0.003 -2859.368 -799.037 ============================================================================== >>> T_test.effect -1829.2025687192481 >>> T_test.sd 455.39079425193762 >>> T_test.tvalue -4.0167754636411717 >>> T_test.pvalue 0.0015163772380899498 ``` Alternatively, you can specify the hypothesis tests using a string ``` >>> from statsmodels.formula.api import ols >>> dta = sm.datasets.longley.load_pandas().data >>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' >>> results = ols(formula, dta).fit() >>> hypotheses = 'GNPDEFL = GNP, UNEMP = 2, YEAR/1829 = 1' >>> t_test = results.t_test(hypotheses) >>> print(t_test) Test for Constraints ============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------ c0 15.0977 84.937 0.178 0.863 -177.042 207.238 c1 -2.0202 0.488 -8.231 0.000 -3.125 -0.915 c2 1.0001 0.249 0.000 1.000 0.437 1.563 ============================================================================== ``` See also [`tvalues`](statsmodels.regression.linear_model.regressionresults.tvalues#statsmodels.regression.linear_model.RegressionResults.tvalues "statsmodels.regression.linear_model.RegressionResults.tvalues") individual t statistics [`f_test`](statsmodels.regression.linear_model.regressionresults.f_test#statsmodels.regression.linear_model.RegressionResults.f_test "statsmodels.regression.linear_model.RegressionResults.f_test") for F tests [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") statsmodels statsmodels.sandbox.regression.anova_nistcertified.anova_oneway statsmodels.sandbox.regression.anova\_nistcertified.anova\_oneway ================================================================= `statsmodels.sandbox.regression.anova_nistcertified.anova_oneway(y, x, seq=0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/anova_nistcertified.html#anova_oneway) statsmodels statsmodels.multivariate.factor.FactorResults.get_loadings_frame statsmodels.multivariate.factor.FactorResults.get\_loadings\_frame ================================================================== `FactorResults.get_loadings_frame(style='display', sort_=True, threshold=0.3, highlight_max=True, color_max='yellow', decimals=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/multivariate/factor.html#FactorResults.get_loadings_frame) get loadings matrix as DataFrame or pandas Styler | Parameters: | * **style** (*'display'* *(**default**)**,* *'raw'* *or* *'strings'*) – Style to use for display + ’raw’ returns just a DataFrame of the loadings matrix, no options are applied + ’display’ add sorting and styling as defined by other keywords + ’strings’ returns a DataFrame with string elements with optional sorting and surpressing small loading coefficients. * **sort** (*boolean*) – If True, then the rows of the DataFrame is sorted by contribution of each factor. applies if style is either ‘display’ or ‘strings’ * **threshold** (*float*) – If the threshold is larger than zero, then loading coefficients are either colored white (if style is ‘display’) or replace by empty string (if style is ‘strings’). * **highlight\_max** (*boolean*) – This add a background color to the largest coefficient in each row. * **color\_max** (*html color*) – default is ‘yellow’. color for background of row maximum * **decimals** (*None* *or* *int*) – If None, then pandas default precision applies. Otherwise values are rounded to the specified decimals. If style is ‘display’, then the underlying dataframe is not changed. If style is ‘strings’, then values are rounded before conversion to strings. | | Returns: | **loadings** – The return is a pandas Styler instance, if style is ‘display’ and at least one of highlight\_max, threshold or decimals is applied. Otherwise, the returned loadings is a DataFrame. | | Return type: | DataFrame or pandas Styler instance | #### Examples ``` >>> mod = Factor(df, 3, smc=True) >>> res = mod.fit() >>> res.get_loadings_frame(style='display', decimals=3, threshold=0.2) ``` To get a sorted DataFrame, all styling options need to be turned off: ``` >>> df_sorted = res.get_loadings_frame(style='display', ... highlight_max=False, decimals=None, threshold=0) ``` Options except for highlighting are available for plain test or Latex usage: ``` >>> lds = res_u.get_loadings_frame(style='strings', decimals=3, ... threshold=0.3) >>> print(lds.to_latex()) ``` statsmodels statsmodels.tsa.arima_model.ARMA.score statsmodels.tsa.arima\_model.ARMA.score ======================================= `ARMA.score(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_model.html#ARMA.score) Compute the score function at params. #### Notes This is a numerical approximation. statsmodels statsmodels.sandbox.tsa.movstat.movmean statsmodels.sandbox.tsa.movstat.movmean ======================================= `statsmodels.sandbox.tsa.movstat.movmean(x, windowsize=3, lag='lagged')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/tsa/movstat.html#movmean) moving window mean | Parameters: | * **x** (*array*) – time series data * **windsize** (*int*) – window size * **lag** (*'lagged'**,* *'centered'**, or* *'leading'*) – location of window relative to current position | | Returns: | **mk** – moving mean, with same shape as x | | Return type: | array | #### Notes for leading and lagging the data array x is extended by the closest value of the array statsmodels statsmodels.regression.recursive_ls.RecursiveLS.set_filter_method statsmodels.regression.recursive\_ls.RecursiveLS.set\_filter\_method ==================================================================== `RecursiveLS.set_filter_method(filter_method=None, **kwargs)` Set the filtering method The filtering method controls aspects of which Kalman filtering approach will be used. | Parameters: | * **filter\_method** (*integer**,* *optional*) – Bitmask value to set the filter method to. See notes for details. * **\*\*kwargs** – Keyword arguments may be used to influence the filter method by setting individual boolean flags. See notes for details. | #### Notes This method is rarely used. See the corresponding function in the `KalmanFilter` class for details. statsmodels statsmodels.genmod.generalized_estimating_equations.GEEResults.plot_added_variable statsmodels.genmod.generalized\_estimating\_equations.GEEResults.plot\_added\_variable ====================================================================================== `GEEResults.plot_added_variable(focus_exog, resid_type=None, use_glm_weights=True, fit_kwargs=None, ax=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_estimating_equations.html#GEEResults.plot_added_variable) Create an added variable plot for a fitted regression model. | Parameters: | * **focus\_exog** (*int* *or* *string*) – The column index of exog, or a variable name, indicating the variable whose role in the regression is to be assessed. * **resid\_type** (*string*) – The type of residuals to use for the dependent variable. If None, uses `resid_deviance` for GLM/GEE and `resid` otherwise. * **use\_glm\_weights** (*bool*) – Only used if the model is a GLM or GEE. If True, the residuals for the focus predictor are computed using WLS, with the weights obtained from the IRLS calculations for fitting the GLM. If False, unweighted regression is used. * **fit\_kwargs** ([dict](https://docs.python.org/3.2/library/stdtypes.html#dict "(in Python v3.2)")*,* *optional*) – Keyword arguments to be passed to fit when refitting the model. * **ax** (*Axes instance*) – Matplotlib Axes instance | | Returns: | **fig** – A matplotlib figure instance. | | Return type: | matplotlib Figure | statsmodels statsmodels.tsa.arima_model.ARIMA.geterrors statsmodels.tsa.arima\_model.ARIMA.geterrors ============================================ `ARIMA.geterrors(params)` Get the errors of the ARMA process. | Parameters: | * **params** (*array-like*) – The fitted ARMA parameters * **order** (*array-like*) – 3 item iterable, with the number of AR, MA, and exogenous parameters, including the trend | statsmodels statsmodels.regression.linear_model.OLSResults.normalized_cov_params statsmodels.regression.linear\_model.OLSResults.normalized\_cov\_params ======================================================================= `OLSResults.normalized_cov_params()` statsmodels statsmodels.tsa.arima_model.ARIMAResults.f_test statsmodels.tsa.arima\_model.ARIMAResults.f\_test ================================================= `ARIMAResults.f_test(r_matrix, cov_p=None, scale=1.0, invcov=None)` Compute the F-test for a joint linear hypothesis. This is a special case of `wald_test` that always uses the F distribution. | Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) – + array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length k row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – Default is 1.0 for no scaling. * **invcov** (*array-like**,* *optional*) – A q x q array to specify an inverse covariance matrix based on a restrictions matrix. | | Returns: | **res** – The results for the test are attributes of this results instance. | | Return type: | ContrastResults instance | #### Examples ``` >>> import numpy as np >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> A = np.identity(len(results.params)) >>> A = A[1:,:] ``` This tests that each coefficient is jointly statistically significantly different from zero. ``` >>> print(results.f_test(A)) <F test: F=array([[ 330.28533923]]), p=4.984030528700946e-10, df_denom=9, df_num=6> ``` Compare this to ``` >>> results.fvalue 330.2853392346658 >>> results.f_pvalue 4.98403096572e-10 ``` ``` >>> B = np.array(([0,0,1,-1,0,0,0],[0,0,0,0,0,1,-1])) ``` This tests that the coefficient on the 2nd and 3rd regressors are equal and jointly that the coefficient on the 5th and 6th regressors are equal. ``` >>> print(results.f_test(B)) <F test: F=array([[ 9.74046187]]), p=0.005605288531708235, df_denom=9, df_num=2> ``` Alternatively, you can specify the hypothesis tests using a string ``` >>> from statsmodels.datasets import longley >>> from statsmodels.formula.api import ols >>> dta = longley.load_pandas().data >>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' >>> results = ols(formula, dta).fit() >>> hypotheses = '(GNPDEFL = GNP), (UNEMP = 2), (YEAR/1829 = 1)' >>> f_test = results.f_test(hypotheses) >>> print(f_test) <F test: F=array([[ 144.17976065]]), p=6.322026217355609e-08, df_denom=9, df_num=3> ``` See also [`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`wald_test`](statsmodels.tsa.arima_model.arimaresults.wald_test#statsmodels.tsa.arima_model.ARIMAResults.wald_test "statsmodels.tsa.arima_model.ARIMAResults.wald_test"), [`t_test`](statsmodels.tsa.arima_model.arimaresults.t_test#statsmodels.tsa.arima_model.ARIMAResults.t_test "statsmodels.tsa.arima_model.ARIMAResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") #### Notes The matrix `r_matrix` is assumed to be non-singular. More precisely, r\_matrix (pX pX.T) r\_matrix.T is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full.
programming_docs
statsmodels statsmodels.sandbox.regression.gmm.IVGMMResults.save statsmodels.sandbox.regression.gmm.IVGMMResults.save ==================================================== `IVGMMResults.save(fname, remove_data=False)` save a pickle of this instance | Parameters: | * **fname** (*string* *or* *filehandle*) – fname can be a string to a file path or filename, or a filehandle. * **remove\_data** (*bool*) – If False (default), then the instance is pickled without changes. If True, then all arrays with length nobs are set to None before pickling. See the remove\_data method. In some cases not all arrays will be set to None. | #### Notes If remove\_data is true and the model result does not implement a remove\_data method then this will raise an exception. statsmodels statsmodels.stats.contingency_tables.Table.resid_pearson statsmodels.stats.contingency\_tables.Table.resid\_pearson ========================================================== `Table.resid_pearson()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#Table.resid_pearson) statsmodels statsmodels.tsa.vector_ar.var_model.VARResults.resid statsmodels.tsa.vector\_ar.var\_model.VARResults.resid ====================================================== `VARResults.resid()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/var_model.html#VARResults.resid) Residuals of response variable resulting from estimated coefficients statsmodels statsmodels.stats.correlation_tools.cov_nearest_factor_homog statsmodels.stats.correlation\_tools.cov\_nearest\_factor\_homog ================================================================ `statsmodels.stats.correlation_tools.cov_nearest_factor_homog(cov, rank)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/correlation_tools.html#cov_nearest_factor_homog) Approximate an arbitrary square matrix with a factor-structured matrix of the form k\*I + XX’. | Parameters: | * **cov** (*array-like*) – The input array, must be square but need not be positive semidefinite * **rank** (*positive integer*) – The rank of the fitted factor structure | | Returns: | | | Return type: | A FactoredPSDMatrix instance containing the fitted matrix | #### Notes This routine is useful if one has an estimated covariance matrix that is not SPD, and the ultimate goal is to estimate the inverse, square root, or inverse square root of the true covariance matrix. The factor structure allows these tasks to be performed without constructing any n x n matrices. The calculations use the fact that if k is known, then X can be determined from the eigen-decomposition of cov - k\*I, which can in turn be easily obtained form the eigen-decomposition of `cov`. Thus the problem can be reduced to a 1-dimensional search for k that does not require repeated eigen-decompositions. If the input matrix is sparse, then cov - k\*I is also sparse, so the eigen-decomposition can be done effciciently using sparse routines. The one-dimensional search for the optimal value of k is not convex, so a local minimum could be obtained. #### Examples Hard thresholding a covariance matrix may result in a matrix that is not positive semidefinite. We can approximate a hard thresholded covariance matrix with a PSD matrix as follows: ``` >>> import numpy as np >>> np.random.seed(1234) >>> b = 1.5 - np.random.rand(10, 1) >>> x = np.random.randn(100,1).dot(b.T) + np.random.randn(100,10) >>> cov = np.cov(x) >>> cov = cov * (np.abs(cov) >= 0.3) >>> rslt = cov_nearest_factor_homog(cov, 3) ``` statsmodels statsmodels.discrete.discrete_model.NegativeBinomialP.pdf statsmodels.discrete.discrete\_model.NegativeBinomialP.pdf ========================================================== `NegativeBinomialP.pdf(X)` The probability density (mass) function of the model. statsmodels statsmodels.genmod.families.family.Binomial.resid_anscombe statsmodels.genmod.families.family.Binomial.resid\_anscombe =========================================================== `Binomial.resid_anscombe(endog, mu, var_weights=1.0, scale=1.0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/family.html#Binomial.resid_anscombe) The Anscombe residuals | Parameters: | * **endog** (*array*) – The endogenous response variable * **mu** (*array*) – The inverse of the link function at the linear predicted values. * **var\_weights** (*array-like*) – 1d array of variance (analytic) weights. The default is 1. * **scale** (*float**,* *optional*) – An optional argument to divide the residuals by sqrt(scale). The default is 1. | | Returns: | **resid\_anscombe** – The Anscombe residuals as defined below. | | Return type: | array | #### Notes \[n^{2/3}\*(cox\\_snell(endog)-cox\\_snell(mu)) / (mu\*(1-mu/n)\*scale^3)^{1/6} \* \sqrt(var\\_weights)\] where cox\_snell is defined as cox\_snell(x) = betainc(2/3., 2/3., x)\*betainc(2/3.,2/3.) where betainc is the incomplete beta function as defined in scipy, which uses a regularized version (with the unregularized version, one would just have \(cox\_snell(x) = Betainc(2/3., 2/3., x)\)). The name ‘cox\_snell’ is idiosyncratic and is simply used for convenience following the approach suggested in Cox and Snell (1968). Further note that \(cox\\_snell(x) = \frac{3}{2}\*x^{2/3} \* hyp2f1(2/3.,1/3.,5/3.,x)\) where hyp2f1 is the hypergeometric 2f1 function. The Anscombe residuals are sometimes defined in the literature using the hyp2f1 formulation. Both betainc and hyp2f1 can be found in scipy. #### References Anscombe, FJ. (1953) “Contribution to the discussion of H. Hotelling’s paper.” Journal of the Royal Statistical Society B. 15, 229-30. Cox, DR and Snell, EJ. (1968) “A General Definition of Residuals.” Journal of the Royal Statistical Society B. 30, 248-75. statsmodels statsmodels.sandbox.regression.gmm.IVGMM.start_weights statsmodels.sandbox.regression.gmm.IVGMM.start\_weights ======================================================= `IVGMM.start_weights(inv=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#IVGMM.start_weights) statsmodels statsmodels.tsa.statespace.sarimax.SARIMAXResults.bse statsmodels.tsa.statespace.sarimax.SARIMAXResults.bse ===================================================== `SARIMAXResults.bse()` statsmodels statsmodels.nonparametric.kernel_regression.KernelReg.loo_likelihood statsmodels.nonparametric.kernel\_regression.KernelReg.loo\_likelihood ====================================================================== `KernelReg.loo_likelihood()` statsmodels statsmodels.regression.linear_model.OLSResults.ssr statsmodels.regression.linear\_model.OLSResults.ssr =================================================== `OLSResults.ssr()` statsmodels statsmodels.stats.outliers_influence.OLSInfluence.resid_var statsmodels.stats.outliers\_influence.OLSInfluence.resid\_var ============================================================= `OLSInfluence.resid_var()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/outliers_influence.html#OLSInfluence.resid_var) (cached attribute) estimate of variance of the residuals ``` sigma2 = sigma2_OLS * (1 - hii) ``` where hii is the diagonal of the hat matrix statsmodels statsmodels.tsa.tsatools.detrend statsmodels.tsa.tsatools.detrend ================================ `statsmodels.tsa.tsatools.detrend(x, order=1, axis=0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/tsatools.html#detrend) Detrend an array with a trend of given order along axis 0 or 1 | Parameters: | * **x** (*array\_like**,* *1d* *or* *2d*) – data, if 2d, then each row or column is independently detrended with the same trendorder, but independent trend estimates * **order** (*int*) – specifies the polynomial order of the trend, zero is constant, one is linear trend, two is quadratic trend * **axis** (*int*) – axis can be either 0, observations by rows, or 1, observations by columns | | Returns: | **detrended data series** – The detrended series is the residual of the linear regression of the data on the trend of given order. | | Return type: | ndarray | statsmodels statsmodels.regression.linear_model.RegressionResults.get_robustcov_results statsmodels.regression.linear\_model.RegressionResults.get\_robustcov\_results ============================================================================== `RegressionResults.get_robustcov_results(cov_type='HC1', use_t=None, **kwds)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/regression/linear_model.html#RegressionResults.get_robustcov_results) create new results instance with robust covariance as default | Parameters: | * **cov\_type** (*string*) – the type of robust sandwich estimator to use. see Notes below * **use\_t** (*bool*) – If true, then the t distribution is used for inference. If false, then the normal distribution is used. If `use_t` is None, then an appropriate default is used, which is `true` if the cov\_type is nonrobust, and `false` in all other cases. * **kwds** (*depends on cov\_type*) – Required or optional arguments for robust covariance calculation. see Notes below | | Returns: | **results** – This method creates a new results instance with the requested robust covariance as the default covariance of the parameters. Inferential statistics like p-values and hypothesis tests will be based on this covariance matrix. | | Return type: | results instance | #### Notes The following covariance types and required or optional arguments are currently available: * ‘fixed scale’ and optional keyword argument ‘scale’ which uses a predefined scale estimate with default equal to one. * ‘HC0’, ‘HC1’, ‘HC2’, ‘HC3’ and no keyword arguments: heteroscedasticity robust covariance * ‘HAC’ and keywords + `maxlag` integer (required) : number of lags to use + `kernel callable or str (optional) : kernel` currently available kernels are [‘bartlett’, ‘uniform’], default is Bartlett + `use_correction bool (optional) : If true, use small sample` correction * ‘cluster’ and required keyword `groups`, integer group indicator + `groups array_like, integer (required) :` index of clusters or groups + `use_correction bool (optional) :` If True the sandwich covariance is calculated with a small sample correction. If False the sandwich covariance is calculated without small sample correction. + `df_correction bool (optional)` If True (default), then the degrees of freedom for the inferential statistics and hypothesis tests, such as pvalues, f\_pvalue, conf\_int, and t\_test and f\_test, are based on the number of groups minus one instead of the total number of observations minus the number of explanatory variables. `df_resid` of the results instance is adjusted. If False, then `df_resid` of the results instance is not adjusted. * ‘hac-groupsum’ Driscoll and Kraay, heteroscedasticity and autocorrelation robust standard errors in panel data keywords + `time` array\_like (required) : index of time periods + `maxlag` integer (required) : number of lags to use + `kernel callable or str (optional) : kernel` currently available kernels are [‘bartlett’, ‘uniform’], default is Bartlett + `use_correction False or string in [‘hac’, ‘cluster’] (optional) :` If False the the sandwich covariance is calulated without small sample correction. If `use_correction = ‘cluster’` (default), then the same small sample correction as in the case of ‘covtype=’cluster’’ is used. + `df_correction bool (optional)` adjustment to df\_resid, see cov\_type ‘cluster’ above # TODO: we need more options here * ‘hac-panel’ heteroscedasticity and autocorrelation robust standard errors in panel data. The data needs to be sorted in this case, the time series for each panel unit or cluster need to be stacked. The membership to a timeseries of an individual or group can be either specified by group indicators or by increasing time periods. keywords + either `groups` or `time` : array\_like (required) `groups` : indicator for groups `time` : index of time periods + `maxlag` integer (required) : number of lags to use + `kernel callable or str (optional) : kernel` currently available kernels are [‘bartlett’, ‘uniform’], default is Bartlett + `use_correction False or string in [‘hac’, ‘cluster’] (optional) :` If False the sandwich covariance is calculated without small sample correction. + `df_correction bool (optional)` adjustment to df\_resid, see cov\_type ‘cluster’ above # TODO: we need more options here Reminder: `use_correction` in “hac-groupsum” and “hac-panel” is not bool, needs to be in [False, ‘hac’, ‘cluster’] TODO: Currently there is no check for extra or misspelled keywords, except in the case of cov\_type `HCx` statsmodels statsmodels.sandbox.regression.gmm.IVGMMResults.jval statsmodels.sandbox.regression.gmm.IVGMMResults.jval ==================================================== `IVGMMResults.jval()` statsmodels statsmodels.regression.mixed_linear_model.MixedLMResults.hessv statsmodels.regression.mixed\_linear\_model.MixedLMResults.hessv ================================================================ `MixedLMResults.hessv()` cached Hessian of log-likelihood statsmodels statsmodels.emplike.descriptive.DescStatUV.ci_skew statsmodels.emplike.descriptive.DescStatUV.ci\_skew =================================================== `DescStatUV.ci_skew(sig=0.05, upper_bound=None, lower_bound=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/emplike/descriptive.html#DescStatUV.ci_skew) Returns the confidence interval for skewness. | Parameters: | * **sig** (*float*) – The significance level. Default is .05 * **upper\_bound** (*float*) – Maximum value of skewness the upper limit can be. Default is .99 confidence limit assuming normality. * **lower\_bound** (*float*) – Minimum value of skewness the lower limit can be. Default is .99 confidence level assuming normality. | | Returns: | **Interval** – Confidence interval for the skewness | | Return type: | tuple | #### Notes If function returns f(a) and f(b) must have different signs, consider expanding lower and upper bounds statsmodels statsmodels.sandbox.stats.runs.symmetry_bowker statsmodels.sandbox.stats.runs.symmetry\_bowker =============================================== `statsmodels.sandbox.stats.runs.symmetry_bowker(table)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/runs.html#symmetry_bowker) Test for symmetry of a (k, k) square contingency table This is an extension of the McNemar test to test the Null hypothesis that the contingency table is symmetric around the main diagonal, that is n\_{i, j} = n\_{j, i} for all i, j | Parameters: | **table** (*array\_like**,* *2d**,* *(**k**,* *k**)*) – a square contingency table that contains the count for k categories in rows and columns. | | Returns: | * **statistic** (*float*) – chisquare test statistic * **p-value** (*float*) – p-value of the test statistic based on chisquare distribution * **df** (*int*) – degrees of freedom of the chisquare distribution | #### Notes Implementation is based on the SAS documentation, R includes it in `mcnemar.test` if the table is not 2 by 2. The pvalue is based on the chisquare distribution which requires that the sample size is not very small to be a good approximation of the true distribution. For 2x2 contingency tables exact distribution can be obtained with `mcnemar` See also [`mcnemar`](statsmodels.sandbox.stats.runs.mcnemar#statsmodels.sandbox.stats.runs.mcnemar "statsmodels.sandbox.stats.runs.mcnemar") statsmodels statsmodels.tsa.stattools.pacf_ols statsmodels.tsa.stattools.pacf\_ols =================================== `statsmodels.tsa.stattools.pacf_ols(x, nlags=40)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/stattools.html#pacf_ols) Calculate partial autocorrelations | Parameters: | * **x** (*1d array*) – observations of time series for which pacf is calculated * **nlags** (*int*) – Number of lags for which pacf is returned. Lag 0 is not returned. | | Returns: | **pacf** – partial autocorrelations, maxlag+1 elements | | Return type: | 1d array | #### Notes This solves a separate OLS estimation for each desired lag. statsmodels statsmodels.tsa.ar_model.ARResults.normalized_cov_params statsmodels.tsa.ar\_model.ARResults.normalized\_cov\_params =========================================================== `ARResults.normalized_cov_params()` statsmodels statsmodels.genmod.families.family.Family.predict statsmodels.genmod.families.family.Family.predict ================================================= `Family.predict(mu)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/family.html#Family.predict) Linear predictors based on given mu values. | Parameters: | **mu** (*array*) – The mean response variables | | Returns: | **lin\_pred** – Linear predictors based on the mean response variables. The value of the link function at the given mu. | | Return type: | array | statsmodels statsmodels.tsa.vector_ar.var_model.FEVD.cov statsmodels.tsa.vector\_ar.var\_model.FEVD.cov ============================================== `FEVD.cov()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/vector_ar/var_model.html#FEVD.cov) Compute asymptotic standard errors statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.predict statsmodels.sandbox.regression.gmm.IVRegressionResults.predict ============================================================== `IVRegressionResults.predict(exog=None, transform=True, *args, **kwargs)` Call self.model.predict with self.params as the first argument. | Parameters: | * **exog** (*array-like**,* *optional*) – The values for which you want to predict. see Notes below. * **transform** (*bool**,* *optional*) – If the model was fit via a formula, do you want to pass exog through the formula. Default is True. E.g., if you fit a model y ~ log(x1) + log(x2), and transform is True, then you can pass a data structure that contains x1 and x2 in their original form. Otherwise, you’d need to log the data first. * **kwargs** (*args**,*) – Some models can take additional arguments or keywords, see the predict method of the model for the details. | | Returns: | **prediction** – See self.model.predict | | Return type: | ndarray, [pandas.Series](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html#pandas.Series "(in pandas v0.22.0)") or [pandas.DataFrame](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html#pandas.DataFrame "(in pandas v0.22.0)") | #### Notes The types of exog that are supported depends on whether a formula was used in the specification of the model. If a formula was used, then exog is processed in the same way as the original data. This transformation needs to have key access to the same variable names, and can be a pandas DataFrame or a dict like object. If no formula was used, then the provided exog needs to have the same number of columns as the original exog in the model. No transformation of the data is performed except converting it to a numpy array. Row indices as in pandas data frames are supported, and added to the returned prediction. statsmodels statsmodels.nonparametric.kernel_density.KDEMultivariate statsmodels.nonparametric.kernel\_density.KDEMultivariate ========================================================= `class statsmodels.nonparametric.kernel_density.KDEMultivariate(data, var_type, bw=None, defaults=<statsmodels.nonparametric._kernel_base.EstimatorSettings object>)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/nonparametric/kernel_density.html#KDEMultivariate) Multivariate kernel density estimator. This density estimator can handle univariate as well as multivariate data, including mixed continuous / ordered discrete / unordered discrete data. It also provides cross-validated bandwidth selection methods (least squares, maximum likelihood). | Parameters: | * **data** (*list of ndarrays* *or* *2-D ndarray*) – The training data for the Kernel Density Estimation, used to determine the bandwidth(s). If a 2-D array, should be of shape (num\_observations, num\_variables). If a list, each list element is a separate observation. * **var\_type** (*str*) – The type of the variables: + c : continuous + u : unordered (discrete) + o : ordered (discrete)The string should contain a type specifier for each variable, so for example `var_type='ccuo'`. * **bw** (*array\_like* *or* *str**,* *optional*) – If an array, it is a fixed user-specified bandwidth. If a string, should be one of: + normal\_reference: normal reference rule of thumb (default) + cv\_ml: cross validation maximum likelihood + cv\_ls: cross validation least squares * **defaults** (*EstimatorSettings instance**,* *optional*) – The default values for (efficient) bandwidth estimation. | `bw` *array\_like* – The bandwidth parameters. See also [`KDEMultivariateConditional`](statsmodels.nonparametric.kernel_density.kdemultivariateconditional#statsmodels.nonparametric.kernel_density.KDEMultivariateConditional "statsmodels.nonparametric.kernel_density.KDEMultivariateConditional") #### Examples ``` >>> import statsmodels.api as sm >>> nobs = 300 >>> np.random.seed(1234) # Seed random generator >>> c1 = np.random.normal(size=(nobs,1)) >>> c2 = np.random.normal(2, 1, size=(nobs,1)) ``` Estimate a bivariate distribution and display the bandwidth found: ``` >>> dens_u = sm.nonparametric.KDEMultivariate(data=[c1,c2], ... var_type='cc', bw='normal_reference') >>> dens_u.bw array([ 0.39967419, 0.38423292]) ``` #### Methods | | | | --- | --- | | [`cdf`](statsmodels.nonparametric.kernel_density.kdemultivariate.cdf#statsmodels.nonparametric.kernel_density.KDEMultivariate.cdf "statsmodels.nonparametric.kernel_density.KDEMultivariate.cdf")([data\_predict]) | Evaluate the cumulative distribution function. | | [`imse`](statsmodels.nonparametric.kernel_density.kdemultivariate.imse#statsmodels.nonparametric.kernel_density.KDEMultivariate.imse "statsmodels.nonparametric.kernel_density.KDEMultivariate.imse")(bw) | Returns the Integrated Mean Square Error for the unconditional KDE. | | [`loo_likelihood`](statsmodels.nonparametric.kernel_density.kdemultivariate.loo_likelihood#statsmodels.nonparametric.kernel_density.KDEMultivariate.loo_likelihood "statsmodels.nonparametric.kernel_density.KDEMultivariate.loo_likelihood")(bw[, func]) | Returns the leave-one-out likelihood function. | | [`pdf`](statsmodels.nonparametric.kernel_density.kdemultivariate.pdf#statsmodels.nonparametric.kernel_density.KDEMultivariate.pdf "statsmodels.nonparametric.kernel_density.KDEMultivariate.pdf")([data\_predict]) | Evaluate the probability density function. |
programming_docs
statsmodels statsmodels.stats.diagnostic.acorr_breusch_godfrey statsmodels.stats.diagnostic.acorr\_breusch\_godfrey ==================================================== `statsmodels.stats.diagnostic.acorr_breusch_godfrey(results, nlags=None, store=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/diagnostic.html#acorr_breusch_godfrey) Breusch Godfrey Lagrange Multiplier tests for residual autocorrelation | Parameters: | * **results** (*Result instance*) – Estimation results for which the residuals are tested for serial correlation * **nlags** (*int*) – Number of lags to include in the auxiliary regression. (nlags is highest lag) * **store** (*bool*) – If store is true, then an additional class instance that contains intermediate results is returned. | | Returns: | * **lm** (*float*) – Lagrange multiplier test statistic * **lmpval** (*float*) – p-value for Lagrange multiplier test * **fval** (*float*) – fstatistic for F test, alternative version of the same test based on F test for the parameter restriction * **fpval** (*float*) – pvalue for F test * **resstore** (*instance (optional)*) – a class instance that holds intermediate results. Only returned if store=True | #### Notes BG adds lags of residual to exog in the design matrix for the auxiliary regression with residuals as endog, see Greene 12.7.1. #### References Greene Econometrics, 5th edition statsmodels statsmodels.sandbox.regression.gmm.IVGMMResults.calc_cov_params statsmodels.sandbox.regression.gmm.IVGMMResults.calc\_cov\_params ================================================================= `IVGMMResults.calc_cov_params(moms, gradmoms, weights=None, use_weights=False, has_optimal_weights=True, weights_method='cov', wargs=())` calculate covariance of parameter estimates not all options tried out yet If weights matrix is given, then the formula use to calculate cov\_params depends on whether has\_optimal\_weights is true. If no weights are given, then the weight matrix is calculated with the given method, and has\_optimal\_weights is assumed to be true. (API Note: The latter assumption could be changed if we allow for has\_optimal\_weights=None.) statsmodels statsmodels.nonparametric.kde.KDEUnivariate.entropy statsmodels.nonparametric.kde.KDEUnivariate.entropy =================================================== `KDEUnivariate.entropy()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/nonparametric/kde.html#KDEUnivariate.entropy) Returns the differential entropy evaluated at the support #### Notes Will not work if fit has not been called. 1e-12 is added to each probability to ensure that log(0) is not called. statsmodels statsmodels.discrete.count_model.ZeroInflatedGeneralizedPoisson.from_formula statsmodels.discrete.count\_model.ZeroInflatedGeneralizedPoisson.from\_formula ============================================================================== `classmethod ZeroInflatedGeneralizedPoisson.from_formula(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** (*extra arguments*) – These are passed to the model * **kwargs** (*extra keyword arguments*) – These are passed to the model with one exception. The `eval_env` keyword is passed to patsy. It can be either a [`patsy.EvalEnvironment`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.EvalEnvironment "(in patsy v0.5.0+dev)") 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** | | Return type: | 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 statsmodels.iolib.foreign.StataReader.file_timestamp statsmodels.iolib.foreign.StataReader.file\_timestamp ===================================================== `StataReader.file_timestamp()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/iolib/foreign.html#StataReader.file_timestamp) Returns the date and time Stata recorded on last file save. | Returns: | **out** | | Return type: | str | statsmodels statsmodels.sandbox.regression.gmm.IVGMMResults.summary statsmodels.sandbox.regression.gmm.IVGMMResults.summary ======================================================= `IVGMMResults.summary(yname=None, xname=None, title=None, alpha=0.05)` Summarize the Regression Results | Parameters: | * **yname** (*string**,* *optional*) – Default is `y` * **xname** (*list of strings**,* *optional*) – Default is `var_##` for ## in p the number of regressors * **title** (*string**,* *optional*) – Title for the top table. If not None, then this replaces the default title * **alpha** (*float*) – significance level for the confidence intervals | | Returns: | **smry** – this holds the summary tables and text, which can be printed or converted to various output formats. | | Return type: | Summary instance | See also [`statsmodels.iolib.summary.Summary`](statsmodels.iolib.summary.summary#statsmodels.iolib.summary.Summary "statsmodels.iolib.summary.Summary") class to hold summary results statsmodels statsmodels.discrete.discrete_model.BinaryResults.llf statsmodels.discrete.discrete\_model.BinaryResults.llf ====================================================== `BinaryResults.llf()` statsmodels statsmodels.discrete.discrete_model.Logit statsmodels.discrete.discrete\_model.Logit ========================================== `class statsmodels.discrete.discrete_model.Logit(endog, exog, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#Logit) Binary choice logit model | Parameters: | * **endog** (*array-like*) – 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 `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.’ | `endog` *array* – A reference to the endogenous response variable `exog` *array* – A reference to the exogenous design. #### Methods | | | | --- | --- | | [`cdf`](statsmodels.discrete.discrete_model.logit.cdf#statsmodels.discrete.discrete_model.Logit.cdf "statsmodels.discrete.discrete_model.Logit.cdf")(X) | The logistic cumulative distribution function | | [`cov_params_func_l1`](statsmodels.discrete.discrete_model.logit.cov_params_func_l1#statsmodels.discrete.discrete_model.Logit.cov_params_func_l1 "statsmodels.discrete.discrete_model.Logit.cov_params_func_l1")(likelihood\_model, xopt, …) | Computes cov\_params on a reduced parameter space corresponding to the nonzero parameters resulting from the l1 regularized fit. | | [`fit`](statsmodels.discrete.discrete_model.logit.fit#statsmodels.discrete.discrete_model.Logit.fit "statsmodels.discrete.discrete_model.Logit.fit")([start\_params, method, maxiter, …]) | Fit the model using maximum likelihood. | | [`fit_regularized`](statsmodels.discrete.discrete_model.logit.fit_regularized#statsmodels.discrete.discrete_model.Logit.fit_regularized "statsmodels.discrete.discrete_model.Logit.fit_regularized")([start\_params, method, …]) | Fit the model using a regularized maximum likelihood. | | [`from_formula`](statsmodels.discrete.discrete_model.logit.from_formula#statsmodels.discrete.discrete_model.Logit.from_formula "statsmodels.discrete.discrete_model.Logit.from_formula")(formula, data[, subset, drop\_cols]) | Create a Model from a formula and dataframe. | | [`hessian`](statsmodels.discrete.discrete_model.logit.hessian#statsmodels.discrete.discrete_model.Logit.hessian "statsmodels.discrete.discrete_model.Logit.hessian")(params) | Logit model Hessian matrix of the log-likelihood | | [`information`](statsmodels.discrete.discrete_model.logit.information#statsmodels.discrete.discrete_model.Logit.information "statsmodels.discrete.discrete_model.Logit.information")(params) | Fisher information matrix of model | | [`initialize`](statsmodels.discrete.discrete_model.logit.initialize#statsmodels.discrete.discrete_model.Logit.initialize "statsmodels.discrete.discrete_model.Logit.initialize")() | Initialize is called by statsmodels.model.LikelihoodModel.\_\_init\_\_ and should contain any preprocessing that needs to be done for a model. | | [`loglike`](statsmodels.discrete.discrete_model.logit.loglike#statsmodels.discrete.discrete_model.Logit.loglike "statsmodels.discrete.discrete_model.Logit.loglike")(params) | Log-likelihood of logit model. | | [`loglikeobs`](statsmodels.discrete.discrete_model.logit.loglikeobs#statsmodels.discrete.discrete_model.Logit.loglikeobs "statsmodels.discrete.discrete_model.Logit.loglikeobs")(params) | Log-likelihood of logit model for each observation. | | [`pdf`](statsmodels.discrete.discrete_model.logit.pdf#statsmodels.discrete.discrete_model.Logit.pdf "statsmodels.discrete.discrete_model.Logit.pdf")(X) | The logistic probability density function | | [`predict`](statsmodels.discrete.discrete_model.logit.predict#statsmodels.discrete.discrete_model.Logit.predict "statsmodels.discrete.discrete_model.Logit.predict")(params[, exog, linear]) | Predict response variable of a model given exogenous variables. | | [`score`](statsmodels.discrete.discrete_model.logit.score#statsmodels.discrete.discrete_model.Logit.score "statsmodels.discrete.discrete_model.Logit.score")(params) | Logit model score (gradient) vector of the log-likelihood | | [`score_obs`](statsmodels.discrete.discrete_model.logit.score_obs#statsmodels.discrete.discrete_model.Logit.score_obs "statsmodels.discrete.discrete_model.Logit.score_obs")(params) | Logit model Jacobian of the log-likelihood for each observation | #### Attributes | | | | --- | --- | | `endog_names` | Names of endogenous variables | | `exog_names` | Names of exogenous variables | statsmodels statsmodels.genmod.families.links.Power statsmodels.genmod.families.links.Power ======================================= `class statsmodels.genmod.families.links.Power(power=1.0)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/links.html#Power) The power transform | Parameters: | **power** (*float*) – The exponent of the power transform | #### Notes Aliases of Power: inverse = Power(power=-1) sqrt = Power(power=.5) inverse\_squared = Power(power=-2.) identity = Power(power=1.) #### Methods | | | | --- | --- | | [`deriv`](statsmodels.genmod.families.links.power.deriv#statsmodels.genmod.families.links.Power.deriv "statsmodels.genmod.families.links.Power.deriv")(p) | Derivative of the power transform | | [`deriv2`](statsmodels.genmod.families.links.power.deriv2#statsmodels.genmod.families.links.Power.deriv2 "statsmodels.genmod.families.links.Power.deriv2")(p) | Second derivative of the power transform | | [`inverse`](statsmodels.genmod.families.links.power.inverse#statsmodels.genmod.families.links.Power.inverse "statsmodels.genmod.families.links.Power.inverse")(z) | Inverse of the power transform link function | | [`inverse_deriv`](statsmodels.genmod.families.links.power.inverse_deriv#statsmodels.genmod.families.links.Power.inverse_deriv "statsmodels.genmod.families.links.Power.inverse_deriv")(z) | Derivative of the inverse of the power transform | statsmodels statsmodels.duration.hazard_regression.PHReg.robust_covariance statsmodels.duration.hazard\_regression.PHReg.robust\_covariance ================================================================ `PHReg.robust_covariance(params)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/duration/hazard_regression.html#PHReg.robust_covariance) Returns a covariance matrix for the proportional hazards model regresion coefficient estimates that is robust to certain forms of model misspecification. | Parameters: | **params** (*ndarray*) – The parameter vector at which the covariance matrix is calculated. | | Returns: | | | Return type: | The robust covariance matrix as a square ndarray. | #### Notes This function uses the `groups` argument to determine groups within which observations may be dependent. The covariance matrix is calculated using the Huber-White “sandwich” approach. statsmodels statsmodels.discrete.discrete_model.DiscreteResults statsmodels.discrete.discrete\_model.DiscreteResults ==================================================== `class statsmodels.discrete.discrete_model.DiscreteResults(model, mlefit, cov_type='nonrobust', cov_kwds=None, use_t=None)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/discrete/discrete_model.html#DiscreteResults) A results class for the discrete dependent variable models. | Parameters: | * **model** (*A DiscreteModel instance*) – * **params** (*array-like*) – The parameters of a fitted model. * **hessian** (*array-like*) – The hessian of the fitted model. * **scale** (*float*) – A scale parameter for the covariance matrix. | | Returns: | * *\*Attributes\** * **aic** (*float*) – Akaike information criterion. `-2*(llf - p)` where `p` is the number of regressors including the intercept. * **bic** (*float*) – Bayesian information criterion. `-2*llf + ln(nobs)*p` where `p` is the number of regressors including the intercept. * **bse** (*array*) – The standard errors of the coefficients. * **df\_resid** (*float*) – See model definition. * **df\_model** (*float*) – See model definition. * **fitted\_values** (*array*) – Linear predictor XB. * **llf** (*float*) – Value of the loglikelihood * **llnull** (*float*) – Value of the constant-only loglikelihood * **llr** (*float*) – Likelihood ratio chi-squared statistic; `-2*(llnull - llf)` * **llr\_pvalue** (*float*) – The chi-squared probability of getting a log-likelihood ratio statistic greater than llr. llr has a chi-squared distribution with degrees of freedom `df_model`. * **prsquared** (*float*) – McFadden’s pseudo-R-squared. `1 - (llf / llnull)` | #### Methods | | | | --- | --- | | [`aic`](statsmodels.discrete.discrete_model.discreteresults.aic#statsmodels.discrete.discrete_model.DiscreteResults.aic "statsmodels.discrete.discrete_model.DiscreteResults.aic")() | | | [`bic`](statsmodels.discrete.discrete_model.discreteresults.bic#statsmodels.discrete.discrete_model.DiscreteResults.bic "statsmodels.discrete.discrete_model.DiscreteResults.bic")() | | | [`bse`](statsmodels.discrete.discrete_model.discreteresults.bse#statsmodels.discrete.discrete_model.DiscreteResults.bse "statsmodels.discrete.discrete_model.DiscreteResults.bse")() | | | [`conf_int`](statsmodels.discrete.discrete_model.discreteresults.conf_int#statsmodels.discrete.discrete_model.DiscreteResults.conf_int "statsmodels.discrete.discrete_model.DiscreteResults.conf_int")([alpha, cols, method]) | Returns the confidence interval of the fitted parameters. | | [`cov_params`](statsmodels.discrete.discrete_model.discreteresults.cov_params#statsmodels.discrete.discrete_model.DiscreteResults.cov_params "statsmodels.discrete.discrete_model.DiscreteResults.cov_params")([r\_matrix, column, scale, cov\_p, …]) | Returns the variance/covariance matrix. | | [`f_test`](statsmodels.discrete.discrete_model.discreteresults.f_test#statsmodels.discrete.discrete_model.DiscreteResults.f_test "statsmodels.discrete.discrete_model.DiscreteResults.f_test")(r\_matrix[, cov\_p, scale, invcov]) | Compute the F-test for a joint linear hypothesis. | | [`fittedvalues`](statsmodels.discrete.discrete_model.discreteresults.fittedvalues#statsmodels.discrete.discrete_model.DiscreteResults.fittedvalues "statsmodels.discrete.discrete_model.DiscreteResults.fittedvalues")() | | | [`get_margeff`](statsmodels.discrete.discrete_model.discreteresults.get_margeff#statsmodels.discrete.discrete_model.DiscreteResults.get_margeff "statsmodels.discrete.discrete_model.DiscreteResults.get_margeff")([at, method, atexog, dummy, count]) | Get marginal effects of the fitted model. | | [`initialize`](statsmodels.discrete.discrete_model.discreteresults.initialize#statsmodels.discrete.discrete_model.DiscreteResults.initialize "statsmodels.discrete.discrete_model.DiscreteResults.initialize")(model, params, \*\*kwd) | | | [`llf`](statsmodels.discrete.discrete_model.discreteresults.llf#statsmodels.discrete.discrete_model.DiscreteResults.llf "statsmodels.discrete.discrete_model.DiscreteResults.llf")() | | | [`llnull`](statsmodels.discrete.discrete_model.discreteresults.llnull#statsmodels.discrete.discrete_model.DiscreteResults.llnull "statsmodels.discrete.discrete_model.DiscreteResults.llnull")() | | | [`llr`](statsmodels.discrete.discrete_model.discreteresults.llr#statsmodels.discrete.discrete_model.DiscreteResults.llr "statsmodels.discrete.discrete_model.DiscreteResults.llr")() | | | [`llr_pvalue`](statsmodels.discrete.discrete_model.discreteresults.llr_pvalue#statsmodels.discrete.discrete_model.DiscreteResults.llr_pvalue "statsmodels.discrete.discrete_model.DiscreteResults.llr_pvalue")() | | | [`load`](statsmodels.discrete.discrete_model.discreteresults.load#statsmodels.discrete.discrete_model.DiscreteResults.load "statsmodels.discrete.discrete_model.DiscreteResults.load")(fname) | load a pickle, (class method) | | [`normalized_cov_params`](statsmodels.discrete.discrete_model.discreteresults.normalized_cov_params#statsmodels.discrete.discrete_model.DiscreteResults.normalized_cov_params "statsmodels.discrete.discrete_model.DiscreteResults.normalized_cov_params")() | | | [`predict`](statsmodels.discrete.discrete_model.discreteresults.predict#statsmodels.discrete.discrete_model.DiscreteResults.predict "statsmodels.discrete.discrete_model.DiscreteResults.predict")([exog, transform]) | Call self.model.predict with self.params as the first argument. | | [`prsquared`](statsmodels.discrete.discrete_model.discreteresults.prsquared#statsmodels.discrete.discrete_model.DiscreteResults.prsquared "statsmodels.discrete.discrete_model.DiscreteResults.prsquared")() | | | [`pvalues`](statsmodels.discrete.discrete_model.discreteresults.pvalues#statsmodels.discrete.discrete_model.DiscreteResults.pvalues "statsmodels.discrete.discrete_model.DiscreteResults.pvalues")() | | | [`remove_data`](statsmodels.discrete.discrete_model.discreteresults.remove_data#statsmodels.discrete.discrete_model.DiscreteResults.remove_data "statsmodels.discrete.discrete_model.DiscreteResults.remove_data")() | remove data arrays, all nobs arrays from result and model | | [`save`](statsmodels.discrete.discrete_model.discreteresults.save#statsmodels.discrete.discrete_model.DiscreteResults.save "statsmodels.discrete.discrete_model.DiscreteResults.save")(fname[, remove\_data]) | save a pickle of this instance | | [`set_null_options`](statsmodels.discrete.discrete_model.discreteresults.set_null_options#statsmodels.discrete.discrete_model.DiscreteResults.set_null_options "statsmodels.discrete.discrete_model.DiscreteResults.set_null_options")([llnull, attach\_results]) | set fit options for Null (constant-only) model | | [`summary`](statsmodels.discrete.discrete_model.discreteresults.summary#statsmodels.discrete.discrete_model.DiscreteResults.summary "statsmodels.discrete.discrete_model.DiscreteResults.summary")([yname, xname, title, alpha, yname\_list]) | Summarize the Regression Results | | [`summary2`](statsmodels.discrete.discrete_model.discreteresults.summary2#statsmodels.discrete.discrete_model.DiscreteResults.summary2 "statsmodels.discrete.discrete_model.DiscreteResults.summary2")([yname, xname, title, alpha, …]) | Experimental function to summarize regression results | | [`t_test`](statsmodels.discrete.discrete_model.discreteresults.t_test#statsmodels.discrete.discrete_model.DiscreteResults.t_test "statsmodels.discrete.discrete_model.DiscreteResults.t_test")(r\_matrix[, cov\_p, scale, use\_t]) | Compute a t-test for a each linear hypothesis of the form Rb = q | | [`t_test_pairwise`](statsmodels.discrete.discrete_model.discreteresults.t_test_pairwise#statsmodels.discrete.discrete_model.DiscreteResults.t_test_pairwise "statsmodels.discrete.discrete_model.DiscreteResults.t_test_pairwise")(term\_name[, method, alpha, …]) | perform pairwise t\_test with multiple testing corrected p-values | | [`tvalues`](statsmodels.discrete.discrete_model.discreteresults.tvalues#statsmodels.discrete.discrete_model.DiscreteResults.tvalues "statsmodels.discrete.discrete_model.DiscreteResults.tvalues")() | Return the t-statistic for a given parameter estimate. | | [`wald_test`](statsmodels.discrete.discrete_model.discreteresults.wald_test#statsmodels.discrete.discrete_model.DiscreteResults.wald_test "statsmodels.discrete.discrete_model.DiscreteResults.wald_test")(r\_matrix[, cov\_p, scale, invcov, …]) | Compute a Wald-test for a joint linear hypothesis. | | [`wald_test_terms`](statsmodels.discrete.discrete_model.discreteresults.wald_test_terms#statsmodels.discrete.discrete_model.DiscreteResults.wald_test_terms "statsmodels.discrete.discrete_model.DiscreteResults.wald_test_terms")([skip\_single, …]) | Compute a sequence of Wald tests for terms over multiple columns | #### Attributes | | | | --- | --- | | `use_t` | |
programming_docs
statsmodels statsmodels.tsa.holtwinters.ExponentialSmoothing.initialize statsmodels.tsa.holtwinters.ExponentialSmoothing.initialize =========================================================== `ExponentialSmoothing.initialize()` Initialize (possibly re-initialize) a Model instance. For instance, the design matrix of a linear model may change and some things must be recomputed. statsmodels statsmodels.regression.linear_model.OLSResults.ess statsmodels.regression.linear\_model.OLSResults.ess =================================================== `OLSResults.ess()` statsmodels statsmodels.miscmodels.count.PoissonOffsetGMLE.from_formula statsmodels.miscmodels.count.PoissonOffsetGMLE.from\_formula ============================================================ `classmethod PoissonOffsetGMLE.from_formula(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** (*extra arguments*) – These are passed to the model * **kwargs** (*extra keyword arguments*) – These are passed to the model with one exception. The `eval_env` keyword is passed to patsy. It can be either a [`patsy.EvalEnvironment`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.EvalEnvironment "(in patsy v0.5.0+dev)") 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** | | Return type: | 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 statsmodels.tsa.statespace.representation.Representation statsmodels.tsa.statespace.representation.Representation ======================================================== `class statsmodels.tsa.statespace.representation.Representation(k_endog, k_states, k_posdef=None, initial_variance=1000000.0, nobs=0, dtype=<class 'numpy.float64'>, design=None, obs_intercept=None, obs_cov=None, transition=None, state_intercept=None, selection=None, state_cov=None, statespace_classes=None, **kwargs)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/representation.html#Representation) State space representation of a time series process | Parameters: | * **k\_endog** (*array\_like* *or* *integer*) – The observed time-series process \(y\) if array like or the number of variables in the process if an integer. * **k\_states** (*int*) – The dimension of the unobserved state process. * **k\_posdef** (*int**,* *optional*) – The dimension of a guaranteed positive definite covariance matrix describing the shocks in the measurement equation. Must be less than or equal to `k_states`. Default is `k_states`. * **initial\_variance** (*float**,* *optional*) – Initial variance used when approximate diffuse initialization is specified. Default is 1e6. * **initialization** (*{'approximate\_diffuse'**,**'stationary'**,**'known'}**,* *optional*) – Initialization method for the initial state. * **initial\_state** (*array\_like**,* *optional*) – If known initialization is used, the mean of the initial state’s distribution. * **initial\_state\_cov** (*array\_like**,* *optional*) – If known initialization is used, the covariance matrix of the initial state’s distribution. * **nobs** (*integer**,* *optional*) – If an endogenous vector is not given (i.e. `k_endog` is an integer), the number of observations can optionally be specified. If not specified, they will be set to zero until data is bound to the model. * **dtype** (*np.dtype**,* *optional*) – If an endogenous vector is not given (i.e. `k_endog` is an integer), the default datatype of the state space matrices can optionally be specified. Default is `np.float64`. * **design** (*array\_like**,* *optional*) – The design matrix, \(Z\). Default is set to zeros. * **obs\_intercept** (*array\_like**,* *optional*) – The intercept for the observation equation, \(d\). Default is set to zeros. * **obs\_cov** (*array\_like**,* *optional*) – The covariance matrix for the observation equation \(H\). Default is set to zeros. * **transition** (*array\_like**,* *optional*) – The transition matrix, \(T\). Default is set to zeros. * **state\_intercept** (*array\_like**,* *optional*) – The intercept for the transition equation, \(c\). Default is set to zeros. * **selection** (*array\_like**,* *optional*) – The selection matrix, \(R\). Default is set to zeros. * **state\_cov** (*array\_like**,* *optional*) – The covariance matrix for the state equation \(Q\). Default is set to zeros. * **\*\*kwargs** – Additional keyword arguments. Not used directly. It is present to improve compatibility with subclasses, so that they can use `**kwargs` to specify any default state space matrices (e.g. `design`) without having to clean out any other keyword arguments they might have been passed. | `nobs` *int* – The number of observations. `k_endog` *int* – The dimension of the observation series. `k_states` *int* – The dimension of the unobserved state process. `k_posdef` *int* – The dimension of a guaranteed positive definite covariance matrix describing the shocks in the measurement equation. `shapes` *dictionary of name:tuple* – A dictionary recording the initial shapes of each of the representation matrices as tuples. `initialization` *str* – Kalman filter initialization method. Default is unset. `initial_variance` *float* – Initial variance for approximate diffuse initialization. Default is 1e6. #### Notes A general state space model is of the form \[\begin{split}y\_t & = Z\_t \alpha\_t + d\_t + \varepsilon\_t \\ \alpha\_t & = T\_t \alpha\_{t-1} + c\_t + R\_t \eta\_t \\\end{split}\] where \(y\_t\) refers to the observation vector at time \(t\), \(\alpha\_t\) refers to the (unobserved) state vector at time \(t\), and where the irregular components are defined as \[\begin{split}\varepsilon\_t \sim N(0, H\_t) \\ \eta\_t \sim N(0, Q\_t) \\\end{split}\] The remaining variables (\(Z\_t, d\_t, H\_t, T\_t, c\_t, R\_t, Q\_t\)) in the equations are matrices describing the process. Their variable names and dimensions are as follows Z : `design` \((k\\_endog \times k\\_states \times nobs)\) d : `obs_intercept` \((k\\_endog \times nobs)\) H : `obs_cov` \((k\\_endog \times k\\_endog \times nobs)\) T : `transition` \((k\\_states \times k\\_states \times nobs)\) c : `state_intercept` \((k\\_states \times nobs)\) R : `selection` \((k\\_states \times k\\_posdef \times nobs)\) Q : `state_cov` \((k\\_posdef \times k\\_posdef \times nobs)\) In the case that one of the matrices is time-invariant (so that, for example, \(Z\_t = Z\_{t+1} ~ \forall ~ t\)), its last dimension may be of size \(1\) rather than size `nobs`. #### References | | | | --- | --- | | [\*] | Durbin, James, and Siem Jan Koopman. 2012. Time Series Analysis by State Space Methods: Second Edition. Oxford University Press. | #### Methods | | | | --- | --- | | [`bind`](statsmodels.tsa.statespace.representation.representation.bind#statsmodels.tsa.statespace.representation.Representation.bind "statsmodels.tsa.statespace.representation.Representation.bind")(endog) | Bind data to the statespace representation | | [`initialize_approximate_diffuse`](statsmodels.tsa.statespace.representation.representation.initialize_approximate_diffuse#statsmodels.tsa.statespace.representation.Representation.initialize_approximate_diffuse "statsmodels.tsa.statespace.representation.Representation.initialize_approximate_diffuse")([variance]) | Initialize the statespace model with approximate diffuse values. | | [`initialize_known`](statsmodels.tsa.statespace.representation.representation.initialize_known#statsmodels.tsa.statespace.representation.Representation.initialize_known "statsmodels.tsa.statespace.representation.Representation.initialize_known")(initial\_state, …) | Initialize the statespace model with known distribution for initial state. | | [`initialize_stationary`](statsmodels.tsa.statespace.representation.representation.initialize_stationary#statsmodels.tsa.statespace.representation.Representation.initialize_stationary "statsmodels.tsa.statespace.representation.Representation.initialize_stationary")() | Initialize the statespace model as stationary. | #### Attributes | | | | --- | --- | | `design` | *(array) Design matrix* – \(Z~(k\\_endog \times k\\_states \times nobs)\) | | `dtype` | (dtype) Datatype of currently active representation matrices | | `endog` | (array) The observation vector, alias for `obs`. | | `obs` | *(array) Observation vector* – \(y~(k\\_endog \times nobs)\) | | `obs_cov` | *(array) Observation covariance matrix* – \(H~(k\\_endog \times k\\_endog \times nobs)\) | | `obs_intercept` | *(array) Observation intercept* – \(d~(k\\_endog \times nobs)\) | | `prefix` | (str) BLAS prefix of currently active representation matrices | | `selection` | *(array) Selection matrix* – \(R~(k\\_states \times k\\_posdef \times nobs)\) | | `state_cov` | *(array) State covariance matrix* – \(Q~(k\\_posdef \times k\\_posdef \times nobs)\) | | `state_intercept` | *(array) State intercept* – \(c~(k\\_states \times nobs)\) | | `time_invariant` | (bool) Whether or not currently active representation matrices are time-invariant | | `transition` | *(array) Transition matrix* – \(T~(k\\_states \times k\\_states \times nobs)\) | statsmodels statsmodels.sandbox.distributions.transformed.Transf_gen.logpdf statsmodels.sandbox.distributions.transformed.Transf\_gen.logpdf ================================================================ `Transf_gen.logpdf(x, *args, **kwds)` Log of the probability density function at x of the given RV. This uses a more numerically accurate calculation if available. | Parameters: | * **x** (*array\_like*) – quantiles * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information) * **loc** (*array\_like**,* *optional*) – location parameter (default=0) * **scale** (*array\_like**,* *optional*) – scale parameter (default=1) | | Returns: | **logpdf** – Log of the probability density function evaluated at x | | Return type: | array\_like | statsmodels statsmodels.regression.quantile_regression.QuantRegResults.conf_int statsmodels.regression.quantile\_regression.QuantRegResults.conf\_int ===================================================================== `QuantRegResults.conf_int(alpha=0.05, cols=None)` Returns the confidence interval of the fitted parameters. | Parameters: | * **alpha** (*float**,* *optional*) – The `alpha` level for the confidence interval. ie., The default `alpha` = .05 returns a 95% confidence interval. * **cols** (*array-like**,* *optional*) – `cols` specifies which confidence intervals to return | #### Notes The confidence interval is based on Student’s t-distribution. statsmodels statsmodels.multivariate.pca.PCA.project statsmodels.multivariate.pca.PCA.project ======================================== `PCA.project(ncomp=None, transform=True, unweight=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/multivariate/pca.html#PCA.project) Project series onto a specific number of factors | Parameters: | **ncomp** (*int**,* *optional*) – Number of components to use. If omitted, all components initially computed are used. | | Returns: | * **projection** (*array*) – nobs by nvar array of the projection onto ncomp factors * **transform** (*bool*) – Flag indicating whether to return the projection in the original space of the data (True, default) or in the space of the standardized/demeaned data * **unweight** (*bool*) – Flag indicating whether to undo the effects of the estimation weights | #### Notes statsmodels statsmodels.genmod.bayes_mixed_glm.PoissonBayesMixedGLM.vb_elbo statsmodels.genmod.bayes\_mixed\_glm.PoissonBayesMixedGLM.vb\_elbo ================================================================== `PoissonBayesMixedGLM.vb_elbo(vb_mean, vb_sd)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/bayes_mixed_glm.html#PoissonBayesMixedGLM.vb_elbo) Returns the evidence lower bound (ELBO) for the model. statsmodels statsmodels.tsa.arima_model.ARMAResults.bse statsmodels.tsa.arima\_model.ARMAResults.bse ============================================ `ARMAResults.bse()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/arima_model.html#ARMAResults.bse) statsmodels statsmodels.sandbox.distributions.transformed.TransfTwo_gen.entropy statsmodels.sandbox.distributions.transformed.TransfTwo\_gen.entropy ==================================================================== `TransfTwo_gen.entropy(*args, **kwds)` Differential entropy of the RV. | Parameters: | * **arg2****,** **arg3****,****..** (*arg1**,*) – The shape parameter(s) for the distribution (see docstring of the instance object for more information). * **loc** (*array\_like**,* *optional*) – Location parameter (default=0). * **scale** (*array\_like**,* *optional* *(**continuous distributions only**)*) – Scale parameter (default=1). | #### Notes Entropy is defined base `e`: ``` >>> drv = rv_discrete(values=((0, 1), (0.5, 0.5))) >>> np.allclose(drv.entropy(), np.log(2.0)) True ``` statsmodels statsmodels.sandbox.stats.runs.mcnemar statsmodels.sandbox.stats.runs.mcnemar ====================================== `statsmodels.sandbox.stats.runs.mcnemar(x, y=None, exact=True, correction=True)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/stats/runs.html#mcnemar) McNemar test | Parameters: | * **y** (*x**,*) – two paired data samples. If y is None, then x can be a 2 by 2 contingency table. x and y can have more than one dimension, then the results are calculated under the assumption that axis zero contains the observation for the samples. * **exact** (*bool*) – If exact is true, then the binomial distribution will be used. If exact is false, then the chisquare distribution will be used, which is the approximation to the distribution of the test statistic for large sample sizes. * **correction** (*bool*) – If true, then a continuity correction is used for the chisquare distribution (if exact is false.) | | Returns: | * **stat** (*float or int, array*) – The test statistic is the chisquare statistic if exact is false. If the exact binomial distribution is used, then this contains the min(n1, n2), where n1, n2 are cases that are zero in one sample but one in the other sample. * **pvalue** (*float or array*) – p-value of the null hypothesis of equal effects. | #### Notes This is a special case of Cochran’s Q test. The results when the chisquare distribution is used are identical, except for continuity correction. statsmodels statsmodels.genmod.generalized_estimating_equations.GEEResults statsmodels.genmod.generalized\_estimating\_equations.GEEResults ================================================================ `class statsmodels.genmod.generalized_estimating_equations.GEEResults(model, params, cov_params, scale, cov_type='robust', use_t=False, **kwds)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_estimating_equations.html#GEEResults) This class summarizes the fit of a marginal regression model using GEE. | Returns: | * *\*\*Attributes\*\** * **cov\_params\_default** (*ndarray*) – default covariance of the parameter estimates. Is chosen among one of the following three based on `cov_type` * **cov\_robust** (*ndarray*) – covariance of the parameter estimates that is robust * **cov\_naive** (*ndarray*) – covariance of the parameter estimates that is not robust to correlation or variance misspecification * **cov\_robust\_bc** (*ndarray*) – covariance of the parameter estimates that is robust and bias reduced * **converged** (*bool*) – indicator for convergence of the optimization. True if the norm of the score is smaller than a threshold * **cov\_type** (*string*) – string indicating whether a “robust”, “naive” or “bias\_reduced” covariance is used as default * **fit\_history** (*dict*) – Contains information about the iterations. * **fittedvalues** (*array*) – Linear predicted values for the fitted model. dot(exog, params) * **model** (*class instance*) – Pointer to GEE model instance that called `fit`. * **normalized\_cov\_params** (*array*) – See GEE docstring * **params** (*array*) – The coefficients of the fitted model. Note that interpretation of the coefficients often depends on the distribution family and the data. * **scale** (*float*) – The estimate of the scale / dispersion for the model fit. See GEE.fit for more information. * **score\_norm** (*float*) – norm of the score at the end of the iterative estimation. * **bse** (*array*) – The standard errors of the fitted GEE parameters. | #### Methods | | | | --- | --- | | [`bse`](statsmodels.genmod.generalized_estimating_equations.geeresults.bse#statsmodels.genmod.generalized_estimating_equations.GEEResults.bse "statsmodels.genmod.generalized_estimating_equations.GEEResults.bse")() | | | [`centered_resid`](statsmodels.genmod.generalized_estimating_equations.geeresults.centered_resid#statsmodels.genmod.generalized_estimating_equations.GEEResults.centered_resid "statsmodels.genmod.generalized_estimating_equations.GEEResults.centered_resid")() | Returns the residuals centered within each group. | | [`conf_int`](statsmodels.genmod.generalized_estimating_equations.geeresults.conf_int#statsmodels.genmod.generalized_estimating_equations.GEEResults.conf_int "statsmodels.genmod.generalized_estimating_equations.GEEResults.conf_int")([alpha, cols, cov\_type]) | Returns confidence intervals for the fitted parameters. | | [`cov_params`](statsmodels.genmod.generalized_estimating_equations.geeresults.cov_params#statsmodels.genmod.generalized_estimating_equations.GEEResults.cov_params "statsmodels.genmod.generalized_estimating_equations.GEEResults.cov_params")([r\_matrix, column, scale, cov\_p, …]) | Returns the variance/covariance matrix. | | [`f_test`](statsmodels.genmod.generalized_estimating_equations.geeresults.f_test#statsmodels.genmod.generalized_estimating_equations.GEEResults.f_test "statsmodels.genmod.generalized_estimating_equations.GEEResults.f_test")(r\_matrix[, cov\_p, scale, invcov]) | Compute the F-test for a joint linear hypothesis. | | [`fittedvalues`](statsmodels.genmod.generalized_estimating_equations.geeresults.fittedvalues#statsmodels.genmod.generalized_estimating_equations.GEEResults.fittedvalues "statsmodels.genmod.generalized_estimating_equations.GEEResults.fittedvalues")() | Returns the fitted values from the model. | | [`get_margeff`](statsmodels.genmod.generalized_estimating_equations.geeresults.get_margeff#statsmodels.genmod.generalized_estimating_equations.GEEResults.get_margeff "statsmodels.genmod.generalized_estimating_equations.GEEResults.get_margeff")([at, method, atexog, dummy, count]) | Get marginal effects of the fitted model. | | [`initialize`](statsmodels.genmod.generalized_estimating_equations.geeresults.initialize#statsmodels.genmod.generalized_estimating_equations.GEEResults.initialize "statsmodels.genmod.generalized_estimating_equations.GEEResults.initialize")(model, params, \*\*kwd) | | | [`llf`](statsmodels.genmod.generalized_estimating_equations.geeresults.llf#statsmodels.genmod.generalized_estimating_equations.GEEResults.llf "statsmodels.genmod.generalized_estimating_equations.GEEResults.llf")() | | | [`load`](statsmodels.genmod.generalized_estimating_equations.geeresults.load#statsmodels.genmod.generalized_estimating_equations.GEEResults.load "statsmodels.genmod.generalized_estimating_equations.GEEResults.load")(fname) | load a pickle, (class method) | | [`normalized_cov_params`](statsmodels.genmod.generalized_estimating_equations.geeresults.normalized_cov_params#statsmodels.genmod.generalized_estimating_equations.GEEResults.normalized_cov_params "statsmodels.genmod.generalized_estimating_equations.GEEResults.normalized_cov_params")() | | | [`params_sensitivity`](statsmodels.genmod.generalized_estimating_equations.geeresults.params_sensitivity#statsmodels.genmod.generalized_estimating_equations.GEEResults.params_sensitivity "statsmodels.genmod.generalized_estimating_equations.GEEResults.params_sensitivity")(dep\_params\_first, …) | Refits the GEE model using a sequence of values for the dependence parameters. | | [`plot_added_variable`](statsmodels.genmod.generalized_estimating_equations.geeresults.plot_added_variable#statsmodels.genmod.generalized_estimating_equations.GEEResults.plot_added_variable "statsmodels.genmod.generalized_estimating_equations.GEEResults.plot_added_variable")(focus\_exog[, …]) | Create an added variable plot for a fitted regression model. | | [`plot_ceres_residuals`](statsmodels.genmod.generalized_estimating_equations.geeresults.plot_ceres_residuals#statsmodels.genmod.generalized_estimating_equations.GEEResults.plot_ceres_residuals "statsmodels.genmod.generalized_estimating_equations.GEEResults.plot_ceres_residuals")(focus\_exog[, frac, …]) | Produces a CERES (Conditional Expectation Partial Residuals) plot for a fitted regression model. | | [`plot_isotropic_dependence`](statsmodels.genmod.generalized_estimating_equations.geeresults.plot_isotropic_dependence#statsmodels.genmod.generalized_estimating_equations.GEEResults.plot_isotropic_dependence "statsmodels.genmod.generalized_estimating_equations.GEEResults.plot_isotropic_dependence")([ax, xpoints, min\_n]) | Create a plot of the pairwise products of within-group residuals against the corresponding time differences. | | [`plot_partial_residuals`](statsmodels.genmod.generalized_estimating_equations.geeresults.plot_partial_residuals#statsmodels.genmod.generalized_estimating_equations.GEEResults.plot_partial_residuals "statsmodels.genmod.generalized_estimating_equations.GEEResults.plot_partial_residuals")(focus\_exog[, ax]) | Create a partial residual, or ‘component plus residual’ plot for a fited regression model. | | [`predict`](statsmodels.genmod.generalized_estimating_equations.geeresults.predict#statsmodels.genmod.generalized_estimating_equations.GEEResults.predict "statsmodels.genmod.generalized_estimating_equations.GEEResults.predict")([exog, transform]) | Call self.model.predict with self.params as the first argument. | | [`pvalues`](statsmodels.genmod.generalized_estimating_equations.geeresults.pvalues#statsmodels.genmod.generalized_estimating_equations.GEEResults.pvalues "statsmodels.genmod.generalized_estimating_equations.GEEResults.pvalues")() | | | [`remove_data`](statsmodels.genmod.generalized_estimating_equations.geeresults.remove_data#statsmodels.genmod.generalized_estimating_equations.GEEResults.remove_data "statsmodels.genmod.generalized_estimating_equations.GEEResults.remove_data")() | remove data arrays, all nobs arrays from result and model | | [`resid`](statsmodels.genmod.generalized_estimating_equations.geeresults.resid#statsmodels.genmod.generalized_estimating_equations.GEEResults.resid "statsmodels.genmod.generalized_estimating_equations.GEEResults.resid")() | Returns the residuals, the endogeneous data minus the fitted values from the model. | | [`resid_anscombe`](statsmodels.genmod.generalized_estimating_equations.geeresults.resid_anscombe#statsmodels.genmod.generalized_estimating_equations.GEEResults.resid_anscombe "statsmodels.genmod.generalized_estimating_equations.GEEResults.resid_anscombe")() | | | [`resid_centered`](statsmodels.genmod.generalized_estimating_equations.geeresults.resid_centered#statsmodels.genmod.generalized_estimating_equations.GEEResults.resid_centered "statsmodels.genmod.generalized_estimating_equations.GEEResults.resid_centered")() | Returns the residuals centered within each group. | | [`resid_centered_split`](statsmodels.genmod.generalized_estimating_equations.geeresults.resid_centered_split#statsmodels.genmod.generalized_estimating_equations.GEEResults.resid_centered_split "statsmodels.genmod.generalized_estimating_equations.GEEResults.resid_centered_split")() | Returns the residuals centered within each group. | | [`resid_deviance`](statsmodels.genmod.generalized_estimating_equations.geeresults.resid_deviance#statsmodels.genmod.generalized_estimating_equations.GEEResults.resid_deviance "statsmodels.genmod.generalized_estimating_equations.GEEResults.resid_deviance")() | | | [`resid_pearson`](statsmodels.genmod.generalized_estimating_equations.geeresults.resid_pearson#statsmodels.genmod.generalized_estimating_equations.GEEResults.resid_pearson "statsmodels.genmod.generalized_estimating_equations.GEEResults.resid_pearson")() | | | [`resid_response`](statsmodels.genmod.generalized_estimating_equations.geeresults.resid_response#statsmodels.genmod.generalized_estimating_equations.GEEResults.resid_response "statsmodels.genmod.generalized_estimating_equations.GEEResults.resid_response")() | | | [`resid_split`](statsmodels.genmod.generalized_estimating_equations.geeresults.resid_split#statsmodels.genmod.generalized_estimating_equations.GEEResults.resid_split "statsmodels.genmod.generalized_estimating_equations.GEEResults.resid_split")() | Returns the residuals, the endogeneous data minus the fitted values from the model. | | [`resid_working`](statsmodels.genmod.generalized_estimating_equations.geeresults.resid_working#statsmodels.genmod.generalized_estimating_equations.GEEResults.resid_working "statsmodels.genmod.generalized_estimating_equations.GEEResults.resid_working")() | | | [`save`](statsmodels.genmod.generalized_estimating_equations.geeresults.save#statsmodels.genmod.generalized_estimating_equations.GEEResults.save "statsmodels.genmod.generalized_estimating_equations.GEEResults.save")(fname[, remove\_data]) | save a pickle of this instance | | [`sensitivity_params`](statsmodels.genmod.generalized_estimating_equations.geeresults.sensitivity_params#statsmodels.genmod.generalized_estimating_equations.GEEResults.sensitivity_params "statsmodels.genmod.generalized_estimating_equations.GEEResults.sensitivity_params")(dep\_params\_first, …) | Refits the GEE model using a sequence of values for the dependence parameters. | | [`split_centered_resid`](statsmodels.genmod.generalized_estimating_equations.geeresults.split_centered_resid#statsmodels.genmod.generalized_estimating_equations.GEEResults.split_centered_resid "statsmodels.genmod.generalized_estimating_equations.GEEResults.split_centered_resid")() | Returns the residuals centered within each group. | | [`split_resid`](statsmodels.genmod.generalized_estimating_equations.geeresults.split_resid#statsmodels.genmod.generalized_estimating_equations.GEEResults.split_resid "statsmodels.genmod.generalized_estimating_equations.GEEResults.split_resid")() | Returns the residuals, the endogeneous data minus the fitted values from the model. | | [`standard_errors`](statsmodels.genmod.generalized_estimating_equations.geeresults.standard_errors#statsmodels.genmod.generalized_estimating_equations.GEEResults.standard_errors "statsmodels.genmod.generalized_estimating_equations.GEEResults.standard_errors")([cov\_type]) | This is a convenience function that returns the standard errors for any covariance type. | | [`summary`](statsmodels.genmod.generalized_estimating_equations.geeresults.summary#statsmodels.genmod.generalized_estimating_equations.GEEResults.summary "statsmodels.genmod.generalized_estimating_equations.GEEResults.summary")([yname, xname, title, alpha]) | Summarize the GEE regression results | | [`t_test`](statsmodels.genmod.generalized_estimating_equations.geeresults.t_test#statsmodels.genmod.generalized_estimating_equations.GEEResults.t_test "statsmodels.genmod.generalized_estimating_equations.GEEResults.t_test")(r\_matrix[, cov\_p, scale, use\_t]) | Compute a t-test for a each linear hypothesis of the form Rb = q | | [`t_test_pairwise`](statsmodels.genmod.generalized_estimating_equations.geeresults.t_test_pairwise#statsmodels.genmod.generalized_estimating_equations.GEEResults.t_test_pairwise "statsmodels.genmod.generalized_estimating_equations.GEEResults.t_test_pairwise")(term\_name[, method, alpha, …]) | perform pairwise t\_test with multiple testing corrected p-values | | [`tvalues`](statsmodels.genmod.generalized_estimating_equations.geeresults.tvalues#statsmodels.genmod.generalized_estimating_equations.GEEResults.tvalues "statsmodels.genmod.generalized_estimating_equations.GEEResults.tvalues")() | Return the t-statistic for a given parameter estimate. | | [`wald_test`](statsmodels.genmod.generalized_estimating_equations.geeresults.wald_test#statsmodels.genmod.generalized_estimating_equations.GEEResults.wald_test "statsmodels.genmod.generalized_estimating_equations.GEEResults.wald_test")(r\_matrix[, cov\_p, scale, invcov, …]) | Compute a Wald-test for a joint linear hypothesis. | | [`wald_test_terms`](statsmodels.genmod.generalized_estimating_equations.geeresults.wald_test_terms#statsmodels.genmod.generalized_estimating_equations.GEEResults.wald_test_terms "statsmodels.genmod.generalized_estimating_equations.GEEResults.wald_test_terms")([skip\_single, …]) | Compute a sequence of Wald tests for terms over multiple columns | #### Attributes | | | | --- | --- | | `use_t` | |
programming_docs
statsmodels statsmodels.stats.power.TTestIndPower.power statsmodels.stats.power.TTestIndPower.power =========================================== `TTestIndPower.power(effect_size, nobs1, alpha, ratio=1, df=None, alternative='two-sided')` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/power.html#TTestIndPower.power) Calculate the power of a t-test for two independent sample | Parameters: | * **effect\_size** (*float*) – standardized effect size, difference between the two means divided by the standard deviation. `effect_size` has to be positive. * **nobs1** (*int* *or* *float*) – number of observations of sample 1. The number of observations of sample two is ratio times the size of sample 1, i.e. `nobs2 = nobs1 * ratio` * **alpha** (*float in interval* *(**0**,**1**)*) – significance level, e.g. 0.05, is the probability of a type I error, that is wrong rejections if the Null Hypothesis is true. * **ratio** (*float*) – ratio of the number of observations in sample 2 relative to sample 1. see description of nobs1 The default for ratio is 1; to solve for ratio given the other arguments, it has to be explicitly set to None. * **df** (*int* *or* *float*) – degrees of freedom. By default this is None, and the df from the ttest with pooled variance is used, `df = (nobs1 - 1 + nobs2 - 1)` * **alternative** (*string**,* *'two-sided'* *(**default**)**,* *'larger'**,* *'smaller'*) – extra argument to choose whether the power is calculated for a two-sided (default) or one sided test. The one-sided test can be either ‘larger’, ‘smaller’. | | Returns: | **power** – Power of the test, e.g. 0.8, is one minus the probability of a type II error. Power is the probability that the test correctly rejects the Null Hypothesis if the Alternative Hypothesis is true. | | Return type: | float | statsmodels statsmodels.sandbox.regression.gmm.LinearIVGMM.fitgmm statsmodels.sandbox.regression.gmm.LinearIVGMM.fitgmm ===================================================== `LinearIVGMM.fitgmm(start, weights=None, optim_method=None, **kwds)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/regression/gmm.html#LinearIVGMM.fitgmm) estimate parameters using GMM for linear model Uses closed form expression instead of nonlinear optimizers | Parameters: | * **start** (*not used*) – starting values for minimization, not used, only for consistency of method signature * **weights** (*array*) – weighting matrix for moment conditions. If weights is None, then the identity matrix is used * **optim\_method** (*not used**,*) – optimization method, not used, only for consistency of method signature * **\*\*kwds** (*keyword arguments*) – not used, will be silently ignored (for compatibility with generic) | | Returns: | **paramest** – estimated parameters | | Return type: | array | statsmodels statsmodels.tsa.statespace.sarimax.SARIMAXResults.mafreq statsmodels.tsa.statespace.sarimax.SARIMAXResults.mafreq ======================================================== `SARIMAXResults.mafreq()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/tsa/statespace/sarimax.html#SARIMAXResults.mafreq) (array) Frequency of the roots of the reduced form moving average lag polynomial statsmodels statsmodels.tsa.holtwinters.HoltWintersResults.initialize statsmodels.tsa.holtwinters.HoltWintersResults.initialize ========================================================= `HoltWintersResults.initialize(model, params, **kwd)` statsmodels statsmodels.tsa.statespace.sarimax.SARIMAXResults.info_criteria statsmodels.tsa.statespace.sarimax.SARIMAXResults.info\_criteria ================================================================ `SARIMAXResults.info_criteria(criteria, method='standard')` Information criteria | Parameters: | * **criteria** (*{'aic'**,* *'bic'**,* *'hqic'}*) – The information criteria to compute. * **method** (*{'standard'**,* *'lutkepohl'}*) – The method for information criteria computation. Default is ‘standard’ method; ‘lutkepohl’ computes the information criteria as in Lütkepohl (2007). See Notes for formulas. | #### Notes The `‘standard’` formulas are: \[\begin{split}AIC & = -2 \log L(Y\_n | \hat \psi) + 2 k \\ BIC & = -2 \log L(Y\_n | \hat \psi) + k \log n \\ HQIC & = -2 \log L(Y\_n | \hat \psi) + 2 k \log \log n \\\end{split}\] where \(\hat \psi\) are the maximum likelihood estimates of the parameters, \(n\) is the number of observations, and `k` is the number of estimated parameters. Note that the `‘standard’` formulas are returned from the `aic`, `bic`, and `hqic` results attributes. The `‘lutkepohl’` formuals are (Lütkepohl, 2010): \[\begin{split}AIC\_L & = \log | Q | + \frac{2 k}{n} \\ BIC\_L & = \log | Q | + \frac{k \log n}{n} \\ HQIC\_L & = \log | Q | + \frac{2 k \log \log n}{n} \\\end{split}\] where \(Q\) is the state covariance matrix. Note that the Lütkepohl definitions do not apply to all state space models, and should be used with care outside of SARIMAX and VARMAX models. #### References | | | | --- | --- | | [\*] | Lütkepohl, Helmut. 2007. *New Introduction to Multiple Time* *Series Analysis.* Berlin: Springer. | statsmodels statsmodels.genmod.generalized_estimating_equations.GEEMargins.conf_int statsmodels.genmod.generalized\_estimating\_equations.GEEMargins.conf\_int ========================================================================== `GEEMargins.conf_int(alpha=0.05)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_estimating_equations.html#GEEMargins.conf_int) Returns the confidence intervals of the marginal effects | Parameters: | **alpha** (*float*) – Number between 0 and 1. The confidence intervals have the probability 1-alpha. | | Returns: | **conf\_int** – An array with lower, upper confidence intervals for the marginal effects. | | Return type: | ndarray | statsmodels statsmodels.genmod.generalized_estimating_equations.GEE.predict statsmodels.genmod.generalized\_estimating\_equations.GEE.predict ================================================================= `GEE.predict(params, exog=None, offset=None, exposure=None, linear=False)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/generalized_estimating_equations.html#GEE.predict) Return predicted values for a marginal regression model fit using GEE. | Parameters: | * **params** (*array-like*) – Parameters / coefficients of a marginal regression model. * **exog** (*array-like**,* *optional*) – Design / exogenous data. If exog is None, model exog is used. * **offset** (*array-like**,* *optional*) – Offset for exog if provided. If offset is None, model offset is used. * **exposure** (*array-like**,* *optional*) – Exposure for exog, if exposure is None, model exposure is used. Only allowed if link function is the logarithm. * **linear** (*bool*) – If True, returns the linear predicted values. If False, returns the value of the inverse of the model’s link function at the linear predicted values. | | Returns: | | | Return type: | An array of fitted values | #### Notes Using log(V) as the offset is equivalent to using V as the exposure. If exposure U and offset V are both provided, then log(U) + V is added to the linear predictor. statsmodels statsmodels.discrete.discrete_model.NegativeBinomialResults.llr statsmodels.discrete.discrete\_model.NegativeBinomialResults.llr ================================================================ `NegativeBinomialResults.llr()` statsmodels statsmodels.genmod.families.family.InverseGaussian.loglike statsmodels.genmod.families.family.InverseGaussian.loglike ========================================================== `InverseGaussian.loglike(endog, mu, var_weights=1.0, freq_weights=1.0, scale=1.0)` The log-likelihood function in terms of the fitted mean response. | Parameters: | * **endog** (*array*) – Usually the endogenous response variable. * **mu** (*array*) – Usually but not always the fitted mean response variable. * **var\_weights** (*array-like*) – 1d array of variance (analytic) weights. The default is 1. * **freq\_weights** (*array-like*) – 1d array of frequency weights. The default is 1. * **scale** (*float*) – The scale parameter. The default is 1. | | Returns: | **ll** – The value of the loglikelihood evaluated at (endog, mu, var\_weights, freq\_weights, scale) as defined below. | | Return type: | float | #### Notes Where \(ll\_i\) is the by-observation log-likelihood: \[ll = \sum(ll\_i \* freq\\_weights\_i)\] `ll_i` is defined for each family. endog and mu are not restricted to `endog` and `mu` respectively. For instance, you could call both `loglike(endog, endog)` and `loglike(endog, mu)` to get the log-likelihood ratio. statsmodels statsmodels.sandbox.regression.gmm.IVRegressionResults.f_test statsmodels.sandbox.regression.gmm.IVRegressionResults.f\_test ============================================================== `IVRegressionResults.f_test(r_matrix, cov_p=None, scale=1.0, invcov=None)` Compute the F-test for a joint linear hypothesis. This is a special case of `wald_test` that always uses the F distribution. | Parameters: | * **r\_matrix** (*array-like**,* *str**, or* *tuple*) – + array : An r x k array where r is the number of restrictions to test and k is the number of regressors. It is assumed that the linear combination is equal to zero. + str : The full hypotheses to test can be given as a string. See the examples. + tuple : A tuple of arrays in the form (R, q), `q` can be either a scalar or a length k row vector. * **cov\_p** (*array-like**,* *optional*) – An alternative estimate for the parameter covariance matrix. If None is given, self.normalized\_cov\_params is used. * **scale** (*float**,* *optional*) – Default is 1.0 for no scaling. * **invcov** (*array-like**,* *optional*) – A q x q array to specify an inverse covariance matrix based on a restrictions matrix. | | Returns: | **res** – The results for the test are attributes of this results instance. | | Return type: | ContrastResults instance | #### Examples ``` >>> import numpy as np >>> import statsmodels.api as sm >>> data = sm.datasets.longley.load() >>> data.exog = sm.add_constant(data.exog) >>> results = sm.OLS(data.endog, data.exog).fit() >>> A = np.identity(len(results.params)) >>> A = A[1:,:] ``` This tests that each coefficient is jointly statistically significantly different from zero. ``` >>> print(results.f_test(A)) <F test: F=array([[ 330.28533923]]), p=4.984030528700946e-10, df_denom=9, df_num=6> ``` Compare this to ``` >>> results.fvalue 330.2853392346658 >>> results.f_pvalue 4.98403096572e-10 ``` ``` >>> B = np.array(([0,0,1,-1,0,0,0],[0,0,0,0,0,1,-1])) ``` This tests that the coefficient on the 2nd and 3rd regressors are equal and jointly that the coefficient on the 5th and 6th regressors are equal. ``` >>> print(results.f_test(B)) <F test: F=array([[ 9.74046187]]), p=0.005605288531708235, df_denom=9, df_num=2> ``` Alternatively, you can specify the hypothesis tests using a string ``` >>> from statsmodels.datasets import longley >>> from statsmodels.formula.api import ols >>> dta = longley.load_pandas().data >>> formula = 'TOTEMP ~ GNPDEFL + GNP + UNEMP + ARMED + POP + YEAR' >>> results = ols(formula, dta).fit() >>> hypotheses = '(GNPDEFL = GNP), (UNEMP = 2), (YEAR/1829 = 1)' >>> f_test = results.f_test(hypotheses) >>> print(f_test) <F test: F=array([[ 144.17976065]]), p=6.322026217355609e-08, df_denom=9, df_num=3> ``` See also [`statsmodels.stats.contrast.ContrastResults`](http://www.statsmodels.org/stable/dev/generated/statsmodels.stats.contrast.ContrastResults.html#statsmodels.stats.contrast.ContrastResults "statsmodels.stats.contrast.ContrastResults"), [`wald_test`](statsmodels.sandbox.regression.gmm.ivregressionresults.wald_test#statsmodels.sandbox.regression.gmm.IVRegressionResults.wald_test "statsmodels.sandbox.regression.gmm.IVRegressionResults.wald_test"), [`t_test`](statsmodels.sandbox.regression.gmm.ivregressionresults.t_test#statsmodels.sandbox.regression.gmm.IVRegressionResults.t_test "statsmodels.sandbox.regression.gmm.IVRegressionResults.t_test"), [`patsy.DesignInfo.linear_constraint`](http://patsy.readthedocs.io/en/latest/API-reference.html#patsy.DesignInfo.linear_constraint "(in patsy v0.5.0+dev)") #### Notes The matrix `r_matrix` is assumed to be non-singular. More precisely, r\_matrix (pX pX.T) r\_matrix.T is assumed invertible. Here, pX is the generalized inverse of the design matrix of the model. There can be problems in non-OLS models where the rank of the covariance of the noise is not full. statsmodels statsmodels.stats.contingency_tables.StratifiedTable.risk_pooled statsmodels.stats.contingency\_tables.StratifiedTable.risk\_pooled ================================================================== `StratifiedTable.risk_pooled()` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/stats/contingency_tables.html#StratifiedTable.risk_pooled) statsmodels statsmodels.genmod.families.links.Log.inverse statsmodels.genmod.families.links.Log.inverse ============================================= `Log.inverse(z)` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/genmod/families/links.html#Log.inverse) Inverse of log transform link function | Parameters: | **z** (*array*) – The inverse of the link function at `p` | | Returns: | **p** – The mean probabilities given the value of the inverse `z` | | Return type: | array | #### Notes g^{-1}(z) = exp(z) statsmodels statsmodels.tsa.holtwinters.ExponentialSmoothing.information statsmodels.tsa.holtwinters.ExponentialSmoothing.information ============================================================ `ExponentialSmoothing.information(params)` Fisher information matrix of model Returns -Hessian of loglike evaluated at params. statsmodels statsmodels.sandbox.distributions.extras.SkewNorm_gen statsmodels.sandbox.distributions.extras.SkewNorm\_gen ====================================================== `class statsmodels.sandbox.distributions.extras.SkewNorm_gen` [[source]](http://www.statsmodels.org/stable/_modules/statsmodels/sandbox/distributions/extras.html#SkewNorm_gen) univariate Skew-Normal distribution of Azzalini class follows scipy.stats.distributions pattern but with \_\_init\_\_ #### Methods | | | | --- | --- | | [`cdf`](statsmodels.sandbox.distributions.extras.skewnorm_gen.cdf#statsmodels.sandbox.distributions.extras.SkewNorm_gen.cdf "statsmodels.sandbox.distributions.extras.SkewNorm_gen.cdf")(x, \*args, \*\*kwds) | Cumulative distribution function of the given RV. | | [`entropy`](statsmodels.sandbox.distributions.extras.skewnorm_gen.entropy#statsmodels.sandbox.distributions.extras.SkewNorm_gen.entropy "statsmodels.sandbox.distributions.extras.SkewNorm_gen.entropy")(\*args, \*\*kwds) | Differential entropy of the RV. | | [`expect`](statsmodels.sandbox.distributions.extras.skewnorm_gen.expect#statsmodels.sandbox.distributions.extras.SkewNorm_gen.expect "statsmodels.sandbox.distributions.extras.SkewNorm_gen.expect")([func, args, loc, scale, lb, ub, …]) | Calculate expected value of a function with respect to the distribution. | | [`fit`](statsmodels.sandbox.distributions.extras.skewnorm_gen.fit#statsmodels.sandbox.distributions.extras.SkewNorm_gen.fit "statsmodels.sandbox.distributions.extras.SkewNorm_gen.fit")(data, \*args, \*\*kwds) | Return MLEs for shape (if applicable), location, and scale parameters from data. | | [`fit_loc_scale`](statsmodels.sandbox.distributions.extras.skewnorm_gen.fit_loc_scale#statsmodels.sandbox.distributions.extras.SkewNorm_gen.fit_loc_scale "statsmodels.sandbox.distributions.extras.SkewNorm_gen.fit_loc_scale")(data, \*args) | Estimate loc and scale parameters from data using 1st and 2nd moments. | | [`freeze`](statsmodels.sandbox.distributions.extras.skewnorm_gen.freeze#statsmodels.sandbox.distributions.extras.SkewNorm_gen.freeze "statsmodels.sandbox.distributions.extras.SkewNorm_gen.freeze")(\*args, \*\*kwds) | Freeze the distribution for the given arguments. | | [`interval`](statsmodels.sandbox.distributions.extras.skewnorm_gen.interval#statsmodels.sandbox.distributions.extras.SkewNorm_gen.interval "statsmodels.sandbox.distributions.extras.SkewNorm_gen.interval")(alpha, \*args, \*\*kwds) | Confidence interval with equal areas around the median. | | [`isf`](statsmodels.sandbox.distributions.extras.skewnorm_gen.isf#statsmodels.sandbox.distributions.extras.SkewNorm_gen.isf "statsmodels.sandbox.distributions.extras.SkewNorm_gen.isf")(q, \*args, \*\*kwds) | Inverse survival function (inverse of `sf`) at q of the given RV. | | [`logcdf`](statsmodels.sandbox.distributions.extras.skewnorm_gen.logcdf#statsmodels.sandbox.distributions.extras.SkewNorm_gen.logcdf "statsmodels.sandbox.distributions.extras.SkewNorm_gen.logcdf")(x, \*args, \*\*kwds) | Log of the cumulative distribution function at x of the given RV. | | [`logpdf`](statsmodels.sandbox.distributions.extras.skewnorm_gen.logpdf#statsmodels.sandbox.distributions.extras.SkewNorm_gen.logpdf "statsmodels.sandbox.distributions.extras.SkewNorm_gen.logpdf")(x, \*args, \*\*kwds) | Log of the probability density function at x of the given RV. | | [`logsf`](statsmodels.sandbox.distributions.extras.skewnorm_gen.logsf#statsmodels.sandbox.distributions.extras.SkewNorm_gen.logsf "statsmodels.sandbox.distributions.extras.SkewNorm_gen.logsf")(x, \*args, \*\*kwds) | Log of the survival function of the given RV. | | [`mean`](statsmodels.sandbox.distributions.extras.skewnorm_gen.mean#statsmodels.sandbox.distributions.extras.SkewNorm_gen.mean "statsmodels.sandbox.distributions.extras.SkewNorm_gen.mean")(\*args, \*\*kwds) | Mean of the distribution. | | [`median`](statsmodels.sandbox.distributions.extras.skewnorm_gen.median#statsmodels.sandbox.distributions.extras.SkewNorm_gen.median "statsmodels.sandbox.distributions.extras.SkewNorm_gen.median")(\*args, \*\*kwds) | Median of the distribution. | | [`moment`](statsmodels.sandbox.distributions.extras.skewnorm_gen.moment#statsmodels.sandbox.distributions.extras.SkewNorm_gen.moment "statsmodels.sandbox.distributions.extras.SkewNorm_gen.moment")(n, \*args, \*\*kwds) | n-th order non-central moment of distribution. | | [`nnlf`](statsmodels.sandbox.distributions.extras.skewnorm_gen.nnlf#statsmodels.sandbox.distributions.extras.SkewNorm_gen.nnlf "statsmodels.sandbox.distributions.extras.SkewNorm_gen.nnlf")(theta, x) | Return negative loglikelihood function. | | [`pdf`](statsmodels.sandbox.distributions.extras.skewnorm_gen.pdf#statsmodels.sandbox.distributions.extras.SkewNorm_gen.pdf "statsmodels.sandbox.distributions.extras.SkewNorm_gen.pdf")(x, \*args, \*\*kwds) | Probability density function at x of the given RV. | | [`ppf`](statsmodels.sandbox.distributions.extras.skewnorm_gen.ppf#statsmodels.sandbox.distributions.extras.SkewNorm_gen.ppf "statsmodels.sandbox.distributions.extras.SkewNorm_gen.ppf")(q, \*args, \*\*kwds) | Percent point function (inverse of `cdf`) at q of the given RV. | | [`rvs`](statsmodels.sandbox.distributions.extras.skewnorm_gen.rvs#statsmodels.sandbox.distributions.extras.SkewNorm_gen.rvs "statsmodels.sandbox.distributions.extras.SkewNorm_gen.rvs")(\*args, \*\*kwds) | Random variates of given type. | | [`sf`](statsmodels.sandbox.distributions.extras.skewnorm_gen.sf#statsmodels.sandbox.distributions.extras.SkewNorm_gen.sf "statsmodels.sandbox.distributions.extras.SkewNorm_gen.sf")(x, \*args, \*\*kwds) | Survival function (1 - `cdf`) at x of the given RV. | | [`stats`](statsmodels.sandbox.distributions.extras.skewnorm_gen.stats#statsmodels.sandbox.distributions.extras.SkewNorm_gen.stats "statsmodels.sandbox.distributions.extras.SkewNorm_gen.stats")(\*args, \*\*kwds) | Some statistics of the given RV. | | [`std`](statsmodels.sandbox.distributions.extras.skewnorm_gen.std#statsmodels.sandbox.distributions.extras.SkewNorm_gen.std "statsmodels.sandbox.distributions.extras.SkewNorm_gen.std")(\*args, \*\*kwds) | Standard deviation of the distribution. | | [`var`](statsmodels.sandbox.distributions.extras.skewnorm_gen.var#statsmodels.sandbox.distributions.extras.SkewNorm_gen.var "statsmodels.sandbox.distributions.extras.SkewNorm_gen.var")(\*args, \*\*kwds) | Variance of the distribution. | #### Attributes | | | | --- | --- | | `random_state` | Get or set the RandomState object for generating random variates. |
programming_docs