
    M/Ph7                     p    d Z ddlmZ ddlZddlmZ ddZddZddZ	ddZ
ddZddZddZd ZddZdS )zy
Statistical tests to be used in conjunction with the models

Notes
-----
These functions have not been formally tested.
    )statsN)ValueWarningc                     t          j        |           } t          j        | d|          }t          j        |dz  |          t          j        | dz  |          z  }|S )a  
    Calculates the Durbin-Watson statistic.

    Parameters
    ----------
    resids : array_like
        Data for which to compute the Durbin-Watson statistic. Usually
        regression model residuals.
    axis : int, optional
        Axis to use if data has more than 1 dimension. Default is 0.

    Returns
    -------
    dw : float, array_like
        The Durbin-Watson statistic.

    Notes
    -----
    The null hypothesis of the test is that there is no serial correlation
    in the residuals.
    The Durbin-Watson test statistic is defined as:

    .. math::

       \sum_{t=2}^T((e_t - e_{t-1})^2)/\sum_{t=1}^Te_t^2

    The test statistic is approximately equal to 2*(1-r) where ``r`` is the
    sample autocorrelation of the residuals. Thus, for r == 0, indicating no
    serial correlation, the test statistic equals 2. This statistic will
    always be between 0 and 4. The closer to 0 the statistic, the more
    evidence for positive serial correlation. The closer to 4, the more
    evidence for negative serial correlation.
       axis   )npasarraydiffsum)residsr   diff_residsdws       [/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/stats/stattools.pydurbin_watsonr      s_    D ZF'&!$///K	QT	*	*	*RVFAID-I-I-I	IBI    c                     t          j        |           } | j        |         }|dk     r?ddlm}  |dt          |          z  t                     t           j        t           j        fS t          j	        | |          S )z
    Omnibus test for normality

    Parameters
    ----------
    resid : array_like
    axis : int, optional
        Default is 0

    Returns
    -------
    Chi^2 score, two-tail probability
       r   )warnzPomni_normtest is not valid with less than 8 observations; %i samples were given.r   )
r
   r   shapewarningsr   intr   nanr   
normaltest)r   r   nr   s       r   omni_normtestr   6   s      ZFTA1uu!!!!!! #%(VV,-9	; 	; 	;vrv~F....r   c                    t          j        t          j        | t                              } | j        dk     rt          d          t          j        | |          }dt          j        | |          z   }| j	        |         }|dz  |dz  d|dz
  dz  z  z   z  }t          j
                            |d          }||||fS )a  
    The Jarque-Bera test of normality.

    Parameters
    ----------
    resids : array_like
        Data to test for normality. Usually regression model residuals that
        are mean 0.
    axis : int, optional
        Axis to use if data has more than 1 dimension. Default is 0.

    Returns
    -------
    JB : {float, ndarray}
        The Jarque-Bera test statistic.
    JBpv : {float, ndarray}
        The pvalue of the test statistic.
    skew : {float, ndarray}
        Estimated skewness of the data.
    kurtosis : {float, ndarray}
        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 :math:`\chi^2_2`
    distribution.

    The test statistic is defined

    .. math:: 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.
    dtyper	   z'resids must contain at least 2 elementsr            @g      ?)r
   
atleast_1dr   floatsize
ValueErrorr   skewkurtosisr   chi2sf)r   r   r'   r(   r   jbjb_pvs          r   jarque_berar-   Q   s    P ]2:fE:::;;F{QBCCC:f4(((D5>&t4444H 	TA
b&TQY&X\a,?!??	@BJMM"a  EudH$$r   c                    ||                                  } d}t          j        | |          } t          j        | g d|          \  }}}|                     |          }| j        f}|9t          |j                  }|                    |d           t          |          }t          j
        ||          }t          j
        ||          }t          j        t          j        | |z
  dz  |                    }	t          j        | |          }
||z   d|z  z
  ||z
  z  }||z
  t          j        t          | |z
            |          z  }||z
  |	z  }|
|||fS )a  
    Calculates the four skewness measures in Kim & White

    Parameters
    ----------
    y : array_like
        Data to compute use in the estimator.
    axis : int or None, optional
        Axis along which the skewness measures are computed.  If `None`, the
        entire array is used.

    Returns
    -------
    sk1 : ndarray
          The standard skewness estimator.
    sk2 : ndarray
          Skewness estimator based on quartiles.
    sk3 : ndarray
          Skewness estimator based on mean-median difference, standardized by
          absolute deviation.
    sk4 : ndarray
          Skewness estimator based on mean-median difference, standardized by
          standard deviation.

    Notes
    -----
    The robust skewness measures are defined

    .. math::

        SK_{2}=\frac{\left(q_{.75}-q_{.5}\right)
        -\left(q_{.5}-q_{.25}\right)}{q_{.75}-q_{.25}}

    .. math::

        SK_{3}=\frac{\mu-\hat{q}_{0.5}}
        {\hat{E}\left[\left|y-\hat{\mu}\right|\right]}

    .. math::

        SK_{4}=\frac{\mu-\hat{q}_{0.5}}{\hat{\sigma}}

    .. [*] Tae-Hwan Kim and Halbert White, "On more robust estimation of
       skewness and kurtosis," Finance Research Letters, vol. 1, pp. 56-73,
       March 2004.
    Nr   )      9@      I@     R@r   r   r	          @)ravelr
   sort
percentilemeanr%   listr   inserttuplereshapesqrtr   r'   abs)yr   q1q2q3mur   mu_bq2_bsigmask1sk2sk3sk4s                 r   robust_skewnessrI      sR   ` |GGII
4Aq"4"4"44@@@JBB	
BVIERXT1e:b%  D:b%  DGBGa$h]T2233E
*QT
"
"
"C7S2X"r'
*C7bgc!d(mm$777
7C7e
CS#r         @r0   c                 T   |d|z
  |d|z
  f}t          j        | |          \  }}}}t          j        | | |k                        }t          j        | | |k                       }	t          j        | | |k                        }
t          j        | | |k                       }|	|z
  ||
z
  z  S )a  
    KR3 estimator from Kim & White

    Parameters
    ----------
    y : array_like, 1-d
        Data to compute use in the estimator.
    alpha : float, optional
        Lower cut-off for measuring expectation in tail.
    beta :  float, optional
        Lower cut-off for measuring expectation in center.

    Returns
    -------
    kr3 : float
        Robust kurtosis estimator based on standardized lower- and upper-tail
        expected values

    Notes
    -----
    .. [*] Tae-Hwan Kim and Halbert White, "On more robust estimation of
       skewness and kurtosis," Finance Research Letters, vol. 1, pp. 56-73,
       March 2004.
          Y@)r
   r5   r6   )r=   alphabetaperclower_alphaupper_alpha
lower_beta
upper_betal_alphau_alphal_betau_betas               r   _kr3rX      s    2 55=$5D79}Q7M7M4Kj*gaK())GgaK())GWQq:~&''FWQq:~&''Fg&6/22r   rJ   r0   g      @r/   c                    | \  }}|\  }}t          j        d          }t          j        j        }t          j        j        } |t          j        d          dz            \  }	}
}}}}d|d<   ||z
  ||	z
  z   ||
z
  z  |d<    |t          j        |dz  |dz  f                    \  }}d ||          z  |z  d ||          z  |z  z  |d<    |t          j        |dz  |dz  f                    \  }}d	|z  d	|z  z  |d<   |S )
an  
    Calculates the expected value of the robust kurtosis measures in Kim and
    White assuming the data are normally distributed.

    Parameters
    ----------
    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

    Returns
    -------
    ekr : ndarray, 4-element
        Contains the expected values of the 4 robust kurtosis measures

    Notes
    -----
    See `robust_kurtosis` for definitions of the robust kurtosis measures
       )g      ?r2   g      @rJ   r"   g      @r   r!   r   r   rL   r	   g       )r
   zerosr   normppfpdfarray)abdgrM   rN   deltagammaexpected_valuer_   r`   r>   r?   r@   q5q6q7q_alphaq_betaq_deltaq_gammas                      r   expected_robust_kurtosisrn      s/   4 KE4LE5Xa[[N
*.C
*.C S*H!I!IA!MNNBBBN1r'b2g.27;N1c"(EEM4%<#@AABBOGVSS\\)E1a##f++o6LMN1s28UU]EEM$BCCDDGWD7N;N1r   Tc                 z   |(|                                  j        dk    r!| j        dk    r|                                 } d}|\  }}|\  }}dddddd	|d
|z
  |d
|z
  f
}	t          j        | |	|          \
  }
}}}}}}}}}|rt          ||          nt          j        d          }t          j        | |d          |d         z
  }||z
  ||
z
  z   ||z
  z  |d         z
  }| j        dk    rt          | ||          }nt          j
        t          || ||          }||d         z  }||z
  ||z
  z  |d         z
  }||||fS )a  
    Calculates the four kurtosis measures in Kim & White

    Parameters
    ----------
    y : array_like
        Data to compute use in the estimator.
    axis : int or None, optional
        Axis along which the kurtosis are computed.  If `None`, the
        entire array is used.
    a 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 exceedance expectations.
    kr4 : ndarray
          Kurtosis measure based on the spread between high and low quantiles.

    Notes
    -----
    The robust kurtosis measures are defined

    .. math::

        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}}

    .. math::

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

    .. math::

        KR_{4}=\frac{\hat{q}_{1-\delta}-\hat{q}_{\delta}}
        {\hat{q}_{1-\gamma}-\hat{q}_{\gamma}}

    where :math:`\hat{q}_{p}` is the estimated quantile at :math:`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.
    Nr   r   g      )@r/   g     B@g     @O@r1   g     U@rL   r   r\   Fr	   r!   )squeezendimr3   r
   r5   rn   r]   r   r(   rX   apply_along_axis)r=   r   rb   rc   excessrM   rN   rd   re   rO   e1e2e3e5e6e7fdf1mdfgf1mgrf   kr1kr2kr3kr4s                            r   robust_kurtosisr   %  s   | 	YY[[""qv{{GGIIKE4LE5$dD$55=%8D13q$DH2J 2J 2J.BBBBb$  1.r2666%'Xa[[  .D%
(
(>!+<
<CGR R"W
-q0A
ACv{{1eT""!$a==>!C"9
#nQ&7
7CS#r   c                    t          j        t          j        |                     } | j        dk    rt	          d          t          j        |           } | j        d         }|dz  dk    r| |dz  dz
           | |dz           z   dz  }n| |dz
  dz           }| |z
  }||dk             }||dk             }|dddf         }||z
  }t          j        |dk    |dk              }t           j        ||<   ||z   }||z  }	t          j	        |dk              }
|
ret          j
        |
|
f          t          j        |
          z
  }|dt          j        |          z  z  }t          j        |          }||	d|
|
 df<   t          j        |	          S )a-  
    Calculates the medcouple robust measure of skew.

    Parameters
    ----------
    y : array_like, 1-d
        Data to compute use in the estimator.

    Returns
    -------
    mc : float
        The medcouple statistic

    Notes
    -----
    The current algorithm requires a O(N**2) memory allocations, and so may
    not work for very large arrays (N>10000).

    .. [*] M. Hubert and E. Vandervieren, "An adjusted boxplot for skewed
       distributions" Computational Statistics & Data Analysis, vol. 52, pp.
       5186-5201, August 2008.
    r   z#y must be squeezable to a 1-d arrayr   r	   g        N)r
   rp   r   rq   r&   r4   r   logical_andinfr   oneseyetriufliplrmedian)r=   r   mfzlowerupperstandardizationis_zerospreadhnum_tiesreplacementss               r   _medcouple_1dr   ~  s   4 	
2:a==!!Av{{>???


A	
A1uzzQ
maQi'1,A!|_	BAa3hKEa3hKE!!!T'NEemOnUc\5C<88G!vOGU]F Avesl##H 0 w(344rvh7G7GGBGL1111y..#/)8)hYZZ
 9Q<<r   c                     t          j        | t           j                  } |!t          |                                           S t          j        t          ||           S )a  
    Calculate the medcouple robust measure of skew.

    Parameters
    ----------
    y : array_like
        Data to compute use in the estimator.
    axis : {int, None}
        Axis along which the medcouple statistic is computed.  If `None`, the
        entire array is used.

    Returns
    -------
    mc : ndarray
        The medcouple statistic with the same shape as `y`, with the specified
        axis removed.

    Notes
    -----
    The current algorithm requires a O(N**2) memory allocations, and so may
    not work for very large arrays (N>10000).

    .. [*] M. Hubert and E. Vandervieren, "An adjusted boxplot for skewed
       distributions" Computational Statistics & Data Analysis, vol. 52, pp.
       5186-5201, August 2008.
    r   )r
   r   doubler   r3   rr   )r=   r   s     r   	medcoupler     sJ    6 	
1BI&&&A|QWWYY'''}dA666r   )r   )rY   rZ   )r   rY   rZ   T)__doc__scipyr   numpyr
   statsmodels.tools.sm_exceptionsr   r   r   r-   rI   rX   rn   r   r   r    r   r   <module>r      s	              8 8 8 8 8 8% % % %P/ / / /64% 4% 4% 4%nI I I IX!3 !3 !3 !3H* * * *ZV V V Vr; ; ;|7 7 7 7 7 7r   