
    M/Ph*S                     j    d Z ddlmZ ddlZddlmZ ddlmZ  G d d          Z	 G d d	          Z
dS )
aV  
Author: Austin Adams

This class implements Oaxaca-Blinder Decomposition. It returns
a OaxacaResults Class:

OaxacaBlinder:
Two-Fold (two_fold)
Three-Fold (three_fold)

OaxacaResults:
Table Summary (summary)

Oaxaca-Blinder is a statistical method that is used to explain
the differences between two mean values. The idea is to show
from two mean values what can be explained by the data and
what cannot by using OLS regression frameworks.

"The original use by Oaxaca's was to explain the wage
differential between two different groups of workers,
but the method has since been applied to numerous other
topics." (Wikipedia)

The model is designed to accept two endogenous response variables
and two exogenous explanitory variables. They are then fit using
the specific type of decomposition that you want.

The method was famously used in Card and Krueger's paper
"School Quality and Black-White Relative Earnings: A Direct Assessment" (1992)

General reference for Oaxaca-Blinder:

B. Jann "The Blinder-Oaxaca decomposition for linear
regression models," The Stata Journal, 2008.

Econometrics references for regression models:

E. M. Kitagawa  "Components of a Difference Between Two Rates"
Journal of the American Statistical Association, 1955.

A. S. Blinder "Wage Discrimination: Reduced Form and Structural
Estimates," The Journal of Human Resources, 1973.
    )dedentN)OLS)add_constantc                   D    e Zd ZdZ	 	 	 	 ddZddZdd
Z	 	 	 	 	 ddZdS )OaxacaBlinderae	  
    Class to perform Oaxaca-Blinder Decomposition.

    Parameters
    ----------
    endog : array_like
        The endogenous variable or the dependent variable that you are trying
        to explain.
    exog : array_like
        The exogenous variable(s) or the independent variable(s) that you are
        using to explain the endogenous variable.
    bifurcate : {int, str}
        The column of the exogenous variable(s) on which to split. This would
        generally be the group that you wish to explain the two means for.
        Int of the column for a NumPy array or int/string for the name of
        the column in Pandas.
    hasconst : bool, optional
        Indicates whether the two exogenous variables include a user-supplied
        constant. If True, a constant is assumed. If False, a constant is added
        at the start. If nothing is supplied, then True is assumed.
    swap : bool, optional
        Imitates the STATA Oaxaca command by allowing users to choose to swap
        groups. Unlike STATA, this is assumed to be True instead of False
    cov_type : str, optional
        See regression.linear_model.RegressionResults for a description of the
        available covariance estimators
    cov_kwds : dict, optional
        See linear_model.RegressionResults.get_robustcov_results for a
        description required keywords for alternative covariance estimators

    Notes
    -----
    Please check if your data includes at constant. This will still run, but
    will return incorrect values if set incorrectly.

    You can access the models by using their code as an attribute, e.g.,
    _t_model for the total model, _f_model for the first model, _s_model for
    the second model.

    Examples
    --------
    >>> import numpy as np
    >>> import statsmodels.api as sm
    >>> data = sm.datasets.ccards.load()

    '3' is the column of which we want to explain or which indicates
    the two groups. In this case, it is if you rent.

    >>> model = sm.OaxacaBlinder(df.endog, df.exog, 3, hasconst = False)
    >>> model.two_fold().summary()
    Oaxaca-Blinder Two-fold Effects
    Unexplained Effect: 27.94091
    Explained Effect: 130.80954
    Gap: 158.75044

    >>> model.three_fold().summary()
    Oaxaca-Blinder Three-fold Effects
    Endowments Effect: 321.74824
    Coefficient Effect: 75.45371
    Interaction Effect: -238.45151
    Gap: 158.75044
    T	nonrobustNc                 P   t          t          |                                        d          dk    rB|j                            |          }t          j        |          t          j        |          }}d | _        || _        || _	        || _
        t          j        ||d          | _        || _        || _        |d d |f         }t          j        ||f          }t          j        |          }	|| _        |t          j        |d d |f         |	d         k                       }
|t          j        |d d |f         |	d         k                       }|t          j        |d d df         |	d         k                       }|t          j        |d d df         |	d         k                       }t          j        |
|d          }
t          j        ||d          }|d d df         }|d d df         }|d d df         | _        t)          |          t)          |          c| _        | _        |                                |                                z
  | _        |rX| j        dk     rM||}}||
}}
|                                |                                z
  | _        |	d         |	d         c|	d<   |	d<   |	| _        |du rXt5          |
d          }
t5          |d          }t5          | j        d          | _        t5          | j        d          | _        t          j        |
d          | _        t          j        |d          | _        t;          ||
                              ||          | _        t;          ||                              ||          | _         d S )	Npandas   axisr   Fprependcov_typecov_kwds)!strtypefindcolumnsget_locnparraytwo_fold_type	bifurcater   r   deleteneumarkexoghasconstcolumn_stackuniquebi_colwhereendoglenlen_flen_smeangapbir   exog_f_meanexog_s_meanr   fit_f_model_s_model)selfr%   r   r   r    swapr   r   r#   r+   exog_fexog_sendog_fendog_ss                 X/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/stats/oaxaca.py__init__zOaxacaBlinder.__init__w   s]    tDzz??))R//,,Y77I(5//28D>>4E!"  yyq999	 aaal#00Yv bhtAAAyL1RU:;;<bhtAAAyL1RU:;;<qqq!t1!5667qqq!t1!5667691555691555!!!Q$-!!!Q$-111a4[
!$Ws7||
DJ<<>>GLLNN2 	(DHqLL&WG#VFF||~~6DHa5"Q%LBqE2a5u!&%888F!&%888F$TY>>>DI'eDDDDL7622276222GV,,00 1 
 
 GV,,00 1 
 
      Gz?c                 ~   | j         | j         }| j        | j        }| j        | j        d| j        z
  g}| j        }| j        }g }g }g }	g }
g }t          d|          D ]F}t          j        | j        | j	        f          }| j
        }t          |          }t          j                            d||          }||         }||         }t          j        ||d          }|t          j        |dd|f         |d         k                       }|t          j        |dd|f         |d         k                       }|t          j        |dddf         |d         k                       }|t          j        |dddf         |d         k                       }t          j        ||d          }t          j        ||d          }|dddf         }|dddf         }|dddf         }| j        }| j        du rDt%          |d          }t%          |d          }t%          |d          }t%          |d          }t'          ||                              | j        | j                  }t'          ||                              | j        | j                  }t          j        |d          }t          j        |d          }|d	k    ru||z
  |j        z  }||j        |j        z
  z  }||z
  |j        |j        z
  z  }|                    |           |                    |           |	                    |           |d
k    rZt          |          }t          |          }|dk    r"|||z   z  |j        z  |||z   z  |j        z  z   } n|dk    rd|j        |j        z   z  } n|dk    r"|d         |j        z  |d         |j        z  z   } n|dk    r7t'          ||                              | j        | j                  }!|!j        } nIt'          ||                              | j        | j                  }!t          j        |!j        |          } ||j        | z
  z  || |j        z
  z  z   }"||z
  | z  }#|                    |"           |
                    |#           Ht5          ||z            t5          |d|z
  z            }%}$|d	k    rt          j        t          j        |          |%|$                   t          j        t          j        |          |%|$                   t          j        t          j        |	          |%|$                   gS |d
k    r\t          j        t          j        |          |%|$                   t          j        t          j        |
          |%|$                   gS dS )z{
        A helper function to calculate the variance/std. Used to keep
        the decomposition functions cleaner
        Nr   r   )highsizer   Fr   r         cottonreimers      ?self_submittednuemark)submitted_nsubmitted_confsubmitted_weightr+   r   ranger   r!   r#   r%   r   r&   randomrandintr   r$   r   r    r   r   r.   r   r   r)   paramsappendintstdsort)&r1   decomp_typenconfrH   r+   r   endow_eff_listcoef_eff_listint_eff_listexp_eff_listunexp_eff_list_r%   r   amountsamplesr   r3   r4   r5   r6   r   r/   r0   r,   r-   	endow_effcoef_effint_effr'   r(   t_params_t_modelunexplained	explainedr=   lows&                                         r7   variancezOaxacaBlinder.variance   s   
 ' A*&D ,%D))  WN	q! U	/ U	/AOT[$*$=>>E9DZZFi''V'DDG'NE=Diia888G"(49#5A#>??@F"(49#5A#>??@FBHU111a4[BqE%9::;GBHU111a4[BqE%9::;GYvyq999FYvyq999FaaadmGaaadmG!!!Q$KE .M}%%%fe<<<%fe<<<#D%888&w>>>7F++// 0  H 7F++// 0  H '&q111K'&q111Ka(;6(/I	&(/HO*KL&4Oho5 %%i000$$X...##G,,,,!!FF H,, % 7(/ I/(/A HH #i//"ho&GHHH"&666(+ho=*1-?@ H
 #i//"5'2266!%  7    H  (HH  #5$//33!%  4    H  "y)DDH*ho.HI8ho#=> );6(B	%%k222##I...DMM3qAH~#6#6c!rw~..s4x899rw}--c$h788rw|,,SX677 
 Arw~..s4x899rw|,,SX677  r9   Fc                    || _         || _        d| _        d}| j        | j        z
  | j        j        z  | _        | j        | j        j        | j        j        z
  z  | _	        | j        | j        z
  | j        j        | j        j        z
  z  | _
        |du r|                     d          }t          | j        | j	        | j
        | j        fd|          S )a  
        Calculates the three-fold Oaxaca Blinder Decompositions

        Parameters
        ----------
        std: boolean, optional
            If true, bootstrapped standard errors will be calculated.
        n: int, optional
            A amount of iterations to calculate the bootstrapped
            standard errors. This defaults to 5000.
        conf: float, optional
            This is the confidence required for the standard error
            calculation. Defaults to .99, but could be anything less
            than or equal to one. One is heavy discouraged, due to the
            extreme outliers inflating the variance.

        Returns
        -------
        OaxacaResults
            A results container for the three-fold decomposition.
        NTr?   std_val)rF   rG   rH   r,   r-   r0   rL   r\   r/   r]   r^   rd   OaxacaResultsr*   )r1   rO   rR   rS   rg   s        r7   
three_foldzOaxacaBlinder.three_fold1  s    , " $t//M ! (M 4=#77
 (4+;;M 4=#77
 $;;mmA&&G^T]DL$(C
 
 
 	
r9   pooledc                    || _         || _        d}|| _        || _        |dk    rP| j        | j        | j        z   z  | j        j        z  | j        | j        | j        z   z  | j        j        z  z   | _	        n5|dk    r#d| j        j        | j        j        z   z  | _	        n|dk    rI|t          d          |d|z
  g}|d         | j        j        z  |d         | j        j        z  z   | _	        n|d	k    rPt          | j        | j                                      | j        | j        
          | _        | j        j        | _	        ngt          | j        | j                                      | j        | j        
          | _        t'          j        | j        j        | j                  | _	        | j        | j        j        | j	        z
  z  | j        | j	        | j        j        z
  z  z   | _        | j        | j        z
  | j	        z  | _        |du r|                     d          }t7          | j        | j        | j        fd|          S )a	  
        Calculates the two-fold or pooled Oaxaca Blinder Decompositions

        Methods
        -------
        std: boolean, optional
            If true, bootstrapped standard errors will be calculated.

        two_fold_type: string, optional
            This method allows for the specific calculation of the
            non-discriminatory model. There are four different types
            available at this time. pooled, cotton, reimers, self_submitted.
            Pooled is assumed and if a non-viable parameter is given,
            pooled will be ran.

            pooled - This type assumes that the pooled model's parameters
            (a normal regression) is the non-discriminatory model.
            This includes the indicator variable. This is generally
            the best idea. If you have economic justification for
            using others, then use others.

            nuemark - This is similar to the pooled type, but the regression
            is not done including the indicator variable.

            cotton - This type uses the adjusted in Cotton (1988), which
            accounts for the undervaluation of one group causing the
            overevalution of another. It uses the sample size weights for
            a linear combination of the two model parameters

            reimers - This type uses a linear combination of the two
            models with both parameters being 50% of the
            non-discriminatory model.

            self_submitted - This allows the user to submit their
            own weights. Please be sure to put the weight of the larger mean
            group only. This should be submitted in the
            submitted_weights variable.

        submitted_weight: int/float, required only for self_submitted,
            This is the submitted weight for the larger mean. If the
            weight for the larger mean is p, then the weight for the
            other mean is 1-p. Only submit the first value.

        n: int, optional
            A amount of iterations to calculate the bootstrapped
            standard errors. This defaults to 5000.
        conf: float, optional
            This is the confidence required for the standard error
            calculation. Defaults to .99, but could be anything less
            than or equal to one. One is heavy discouraged, due to the
            extreme outliers inflating the variance.

        Returns
        -------
        OaxacaResults
            A results container for the two-fold decomposition.
        NrA   rB   rC   rD   zPlease submit weightsr   r   rE   r   Tr@   rf   )rF   rG   r   rH   r'   r(   r/   rL   r0   r_   
ValueErrorr   r%   r   r.   r   r   r`   r   r   r   r   r,   r-   ra   rb   rd   rh   r*   )r1   rO   r   rH   rR   rS   rg   s          r7   two_foldzOaxacaBlinder.two_fold^  sF   B "* 0H$$
dj4:569MMtzDJ67$-:NNPDMM i''4=#7$-:N#NODMM...' !8999 0!6F2FG #dm&::"1%(<<= MM
 i''
DL99== >  DM !M0DMM  
DI66:: ;  DM Idm&:DNKKDM  4t} DE1E!EFH *T-==N$;;mmA&&Gt~tx8!W
 
 
 	
r9   )TTr   N)r:   r;   )FNN)Frj   NNN)__name__
__module____qualname____doc__r8   rd   ri   rm    r9   r7   r   r   7   s        = =H ?
 ?
 ?
 ?
Bw w w wr+
 +
 +
 +
^ 
n
 n
 n
 n
 n
 n
r9   r   c                        e Zd ZdZddZd ZdS )rh   a,  
    This class summarizes the fit of the OaxacaBlinder model.

    Use .summary() to get a table of the fitted values or
    use .params to receive a list of the values
    use .std to receive a list of the standard errors

    If a two-fold model was fitted, this will return
    unexplained effect, explained effect, and the
    mean gap. The list will always be of the following order
    and type. If standard error was asked for, then standard error
    calculations will also be included for each variable after each
    calculated effect.

    unexplained : float
        This is the effect that cannot be explained by the data at hand.
        This does not mean it cannot be explained with more.
    explained : float
        This is the effect that can be explained using the data.
    gap : float
        This is the gap in the mean differences of the two groups.

    If a three-fold model was fitted, this will
    return characteristic effect, coefficient effect
    interaction effect, and the mean gap. The list will
    be of the following order and type. If standard error was asked
    for, then standard error calculations will also be included for
    each variable after each calculated effect.

    endowment effect : float
        This is the effect due to the group differences in
        predictors
    coefficient effect : float
        This is the effect due to differences of the coefficients
        of the two groups
    interaction effect : float
        This is the effect due to differences in both effects
        existing at the same time between the two groups.
    gap : float
        This is the gap in the mean differences of the two groups.

    Attributes
    ----------
    params
        A list of all values for the fitted models.
    std
        A list of standard error calculations.
    Nc                 0    || _         || _        || _        d S N)rL   rO   
model_type)r1   resultsrv   rg   s       r7   r8   zOaxacaResults.__init__  s    $r9   c                 x   | j         dk    r| j        Jt          t          d| j        d         dd| j        d         dd| j        d         d                     njt          t          d	                    | j        d         | j        d         | j        d         | j        d         | j        d                                        | j         d
k    r| j        Zt          t          d| j        d         dd| j        d         dd| j        d         dd| j        d
         d                     dS t          t          d| j        d         dd| j        d         dd| j        d         dd| j        d         dd| j        d         dd| j        d         dd| j        d
         d                     dS dS )zG
        Print a summary table with the Oaxaca-Blinder effects
        r@   NzT                Oaxaca-Blinder Two-fold Effects
                Unexplained Effect: r   z.5fz#
                Explained Effect: r   z
                Gap: a                  Oaxaca-Blinder Two-fold Effects
                Unexplained Effect: {:.5f}
                Unexplained Standard Error: {:.5f}
                Explained Effect: {:.5f}
                Explained Standard Error: {:.5f}
                Gap: {:.5f}r?   zT                Oaxaca-Blinder Three-fold Effects
                Endowment Effect: z%
                Coefficient Effect: z%
                Interaction Effect: z+
                Endowment Standard Error: z-
                Coefficient Standard Error: z-
                Interaction Standard Error: )rv   rO   printr   rL   format)r1   s    r7   summaryzOaxacaResults.summary  s    ?ax-%)[^- - - $(;q>- - - k!n	- - -       &v KN HQK KN HQK KN      " ?ax-#';q>- - - &*[^- - - &*[^	- - -
 k!n- - - 	 	 	 	 	 -#';q>- - - ,08A;- - - &*[^	- - -
 .2Xa[- - - &*[^- - - .2Xa[- - - k!n- - -
 
      r9   ru   )rn   ro   rp   rq   r8   r{   rr   r9   r7   rh   rh     sB        / /b% % % %
: : : : :r9   rh   )rq   textwrapr   numpyr   #statsmodels.regression.linear_modelr   statsmodels.tools.toolsr   r   rh   rr   r9   r7   <module>r      s   * *V           3 3 3 3 3 3 0 0 0 0 0 0U
 U
 U
 U
 U
 U
 U
 U
pq q q q q q q q q qr9   