a
    DBìjÅl  ã                   @  sê   d dl mZ d dlmZ d dlmZmZmZmZ d dl	m
Z
mZ d dlmZmZmZ d dlmZmZmZmZmZmZmZmZmZ d dlmZmZ erÄd dlmZmZm Z  d d	l!m"Z"m#Z# d d
l$m%Z% G dd„ deƒZ&G dd„ dee&ƒZ'dS )é    )Úannotations)Údedent)ÚTYPE_CHECKINGÚAnyÚCallableÚLiteral)Údeprecate_kwargÚdoc)ÚBaseIndexerÚExpandingIndexerÚGroupbyIndexer)	Ú_shared_docsÚcreate_section_headerÚkwargs_numeric_onlyÚnumba_notesÚtemplate_headerÚtemplate_returnsÚtemplate_see_alsoÚwindow_agg_numba_parametersÚwindow_apply_parameters)ÚBaseWindowGroupbyÚRollingAndExpandingMixin)ÚAxisÚQuantileInterpolationÚWindowingRankType)Ú	DataFrameÚSeries)ÚNDFramec                      s˜  e Zd ZU dZg d¢Zded< d›d	d
ddddœ‡ fdd„Zddœdd„Zee	d e
dƒe
dƒddd�‡ fdd„ƒZeZeeedƒeedƒeedƒe
d ƒd!d"d#d$�
dœd&d'œ‡ fd(d)„ƒZeeed*ƒeedƒeedƒeedƒe
d+ƒd!d,d-d$�d�d.d&d/d0d1d2d3œ‡ fd4d5„ƒZeeed*ƒeeƒ edƒeedƒeed6ƒeedƒe
d7ƒd!d8d8d$�džd&d/d0d9œ‡ fd:d;„ƒZeeed*ƒeeƒ edƒeedƒeed6ƒeedƒe
d<ƒd!d=d>d$�dŸd&d/d0d9œ‡ fd?d@„ƒZeeed*ƒeeƒ edƒeedƒeed6ƒeedƒe
dAƒd!dBdCd$�d d&d/d0d9œ‡ fdDdE„ƒZeeed*ƒeeƒ edƒeedƒeed6ƒeedƒe
dFƒd!dGdGd$�d¡d&d/d0d9œ‡ fdHdI„ƒZeeed*ƒeeƒ edƒeedƒeed6ƒeedƒe
dJƒd!dKdKd$�d¢d&d/d0d9œ‡ fdLdM„ƒZeeed*ƒe
dNƒ dOdd¡eedPƒedƒeedƒdQeed6ƒe
dRƒ dOdd¡edƒe
dSƒ dOdd¡d!dTdUd$�d£d
d&d/d0dVœ‡ fdWdX„ƒZeeed*ƒe
dNƒ dOdd¡eedPƒedƒeedƒdYeed6ƒe
dZƒ dOdd¡edƒe
d[ƒ dOdd¡d!d\d]d$�d¤d
d&d/d0dVœ‡ fd^d_„ƒZeeed*ƒe
dNƒ dOdd¡eedƒeedƒeed6ƒd`edƒe
daƒ dOdd¡d!dbdcd$�d¥d
d&ddœ‡ fdedf„ƒZeeed*ƒeedƒeedƒdgeed6ƒdhedƒe
diƒd!djdkd$�d¦d&d'œ‡ fdldm„ƒZ eeed*ƒeedƒeedƒdneed6ƒdoedƒe
dpƒ dOdd¡d!dqdrd$�d§d&d'œ‡ fdsdt„ƒZ!eeed*ƒe
duƒ dOdd¡eedƒeedƒeedƒe
dvƒd!dwdwd$�e"dwdxdy�d¨d{d|d&d}œ‡ fd~d„ƒƒZ#eed€ed*ƒe
d�ƒ dOdd¡eedƒeedƒeedƒe
d‚ƒ dOdd¡d!dƒdƒd$�d©d†d&d&d&d‡œ‡ fdˆd‰„ƒZ$eeed*ƒe
dŠƒ dOdd¡eedƒeedƒeedƒe
d‹ƒd!dŒd�d$�dªdŽd�d
d&d�œ‡ fd‘d’„ƒZ%eeed*ƒe
d“ƒ dOdd¡eedƒeedƒe
d”ƒ dOdd¡eed6ƒe
d•ƒedƒe
d–ƒd!d—d˜d$�d«dŽd�d
d&d�œ‡ fd™dš„ƒZ&‡  Z'S )¬Ú	Expandingaï  
    Provide expanding window calculations.

    Parameters
    ----------
    min_periods : int, default 1
        Minimum number of observations in window required to have a value;
        otherwise, result is ``np.nan``.

    axis : int or str, default 0
        If ``0`` or ``'index'``, roll across the rows.

        If ``1`` or ``'columns'``, roll across the columns.

        For `Series` this parameter is unused and defaults to 0.

    method : str {'single', 'table'}, default 'single'
        Execute the rolling operation per single column or row (``'single'``)
        or over the entire object (``'table'``).

        This argument is only implemented when specifying ``engine='numba'``
        in the method call.

        .. versionadded:: 1.3.0

    Returns
    -------
    pandas.api.typing.Expanding

    See Also
    --------
    rolling : Provides rolling window calculations.
    ewm : Provides exponential weighted functions.

    Notes
    -----
    See :ref:`Windowing Operations <window.expanding>` for further usage details
    and examples.

    Examples
    --------
    >>> df = pd.DataFrame({"B": [0, 1, 2, np.nan, 4]})
    >>> df
         B
    0  0.0
    1  1.0
    2  2.0
    3  NaN
    4  4.0

    **min_periods**

    Expanding sum with 1 vs 3 observations needed to calculate a value.

    >>> df.expanding(1).sum()
         B
    0  0.0
    1  1.0
    2  3.0
    3  3.0
    4  7.0
    >>> df.expanding(3).sum()
         B
    0  NaN
    1  NaN
    2  3.0
    3  3.0
    4  7.0
    )Úmin_periodsÚaxisÚmethodz	list[str]Ú_attributesé   r   ÚsingleNr   Úintr   ÚstrÚNone)Úobjr   r    r!   Úreturnc                   s   t ƒ j|||||d� d S )N)r(   r   r    r!   Ú	selection)ÚsuperÚ__init__)Úselfr(   r   r    r!   r*   ©Ú	__class__© ú[/mnt/bigstor/www/usecases/.venv/lib/python3.9/site-packages/pandas/core/window/expanding.pyr,   |   s    ûzExpanding.__init__r
   ©r)   c                 C  s   t ƒ S )z[
        Return an indexer class that will compute the window start and end bounds
        )r   )r-   r0   r0   r1   Ú_get_window_indexerŒ   s    zExpanding._get_window_indexerÚ	aggregatez£
        See Also
        --------
        pandas.DataFrame.aggregate : Similar DataFrame method.
        pandas.Series.aggregate : Similar Series method.
        aœ  
        Examples
        --------
        >>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]})
        >>> df
           A  B  C
        0  1  4  7
        1  2  5  8
        2  3  6  9

        >>> df.ewm(alpha=0.5).mean()
                  A         B         C
        0  1.000000  4.000000  7.000000
        1  1.666667  4.666667  7.666667
        2  2.428571  5.428571  8.428571
        zSeries/DataframeÚ )Zsee_alsoZexamplesÚklassr    c                   s   t ƒ j|g|¢R i |¤ŽS )N)r+   r4   )r-   ÚfuncÚargsÚkwargsr.   r0   r1   r4   ’   s     zExpanding.aggregateZReturnszSee AlsoZExampleszÍ        >>> ser = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
        >>> ser.expanding().count()
        a    1.0
        b    2.0
        c    3.0
        d    4.0
        dtype: float64
        Z	expandingzcount of non NaN observationsÚcount)Zwindow_methodZaggregation_descriptionZ
agg_methodFÚbool©Únumeric_onlyc                   s   t ƒ j|d�S ©Nr<   )r+   r:   ©r-   r=   r.   r0   r1   r:   ¶   s    zExpanding.countZ
Parameterszì        >>> ser = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
        >>> ser.expanding().apply(lambda s: s.max() - 2 * s.min())
        a   -1.0
        b    0.0
        c    1.0
        d    2.0
        dtype: float64
        zcustom aggregation functionÚapplyzCallable[..., Any]z!Literal['cython', 'numba'] | Nonezdict[str, bool] | Noneztuple[Any, ...] | Nonezdict[str, Any] | None)r7   ÚrawÚengineÚengine_kwargsr8   r9   c                   s   t ƒ j||||||d�S )N)rA   rB   rC   r8   r9   )r+   r@   )r-   r7   rA   rB   rC   r8   r9   r.   r0   r1   r@   Ï   s    !úzExpanding.applyZNoteszÏ        >>> ser = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
        >>> ser.expanding().sum()
        a     1.0
        b     3.0
        c     6.0
        d    10.0
        dtype: float64
        Úsum©r=   rB   rC   c                   s   t ƒ j|||d�S ©NrE   )r+   rD   ©r-   r=   rB   rC   r.   r0   r1   rD   ù   s
    !ýzExpanding.sumzË        >>> ser = pd.Series([3, 2, 1, 4], index=['a', 'b', 'c', 'd'])
        >>> ser.expanding().max()
        a    3.0
        b    3.0
        c    3.0
        d    4.0
        dtype: float64
        ÚmaximumÚmaxc                   s   t ƒ j|||d�S rF   )r+   rI   rG   r.   r0   r1   rI      s
    !ýzExpanding.maxzË        >>> ser = pd.Series([2, 3, 4, 1], index=['a', 'b', 'c', 'd'])
        >>> ser.expanding().min()
        a    2.0
        b    2.0
        c    2.0
        d    1.0
        dtype: float64
        ÚminimumÚminc                   s   t ƒ j|||d�S rF   )r+   rK   rG   r.   r0   r1   rK   G  s
    !ýzExpanding.minzÌ        >>> ser = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
        >>> ser.expanding().mean()
        a    1.0
        b    1.5
        c    2.0
        d    2.5
        dtype: float64
        Úmeanc                   s   t ƒ j|||d�S rF   )r+   rL   rG   r.   r0   r1   rL   n  s
    !ýzExpanding.meanzÎ        >>> ser = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
        >>> ser.expanding().median()
        a    1.0
        b    1.5
        c    2.0
        d    2.5
        dtype: float64
        Úmedianc                   s   t ƒ j|||d�S rF   )r+   rM   rG   r.   r0   r1   rM   •  s
    !ýzExpanding.medianz¼
        ddof : int, default 1
            Delta Degrees of Freedom.  The divisor used in calculations
            is ``N - ddof``, where ``N`` represents the number of elements.

        Ú
z1.4z/numpy.std : Equivalent method for NumPy array.
zÛ
        The default ``ddof`` of 1 used in :meth:`Series.std` is different
        than the default ``ddof`` of 0 in :func:`numpy.std`.

        A minimum of one period is required for the rolling calculation.

        a  
        >>> s = pd.Series([5, 5, 6, 7, 5, 5, 5])

        >>> s.expanding(3).std()
        0         NaN
        1         NaN
        2    0.577350
        3    0.957427
        4    0.894427
        5    0.836660
        6    0.786796
        dtype: float64
        zstandard deviationÚstd©Úddofr=   rB   rC   c                   s   t ƒ j||||d�S ©NrP   )r+   rO   ©r-   rQ   r=   rB   rC   r.   r0   r1   rO   ¼  s    5üzExpanding.stdz/numpy.var : Equivalent method for NumPy array.
zÛ
        The default ``ddof`` of 1 used in :meth:`Series.var` is different
        than the default ``ddof`` of 0 in :func:`numpy.var`.

        A minimum of one period is required for the rolling calculation.

        a  
        >>> s = pd.Series([5, 5, 6, 7, 5, 5, 5])

        >>> s.expanding(3).var()
        0         NaN
        1         NaN
        2    0.333333
        3    0.916667
        4    0.800000
        5    0.700000
        6    0.619048
        dtype: float64
        ZvarianceÚvarc                   s   t ƒ j||||d�S rR   )r+   rT   rS   r.   r0   r1   rT   ø  s    5üzExpanding.varz:A minimum of one period is required for the calculation.

zÁ
        >>> s = pd.Series([0, 1, 2, 3])

        >>> s.expanding().sem()
        0         NaN
        1    0.707107
        2    0.707107
        3    0.745356
        dtype: float64
        zstandard error of meanÚsem©rQ   r=   c                   s   t ƒ j||d�S )NrV   )r+   rU   )r-   rQ   r=   r.   r0   r1   rU   4  s    #zExpanding.semz:scipy.stats.skew : Third moment of a probability density.
zEA minimum of three periods is required for the rolling calculation.

a           >>> ser = pd.Series([-1, 0, 2, -1, 2], index=['a', 'b', 'c', 'd', 'e'])
        >>> ser.expanding().skew()
        a         NaN
        b         NaN
        c    0.935220
        d    1.414214
        e    0.315356
        dtype: float64
        zunbiased skewnessÚskewc                   s   t ƒ j|d�S r>   )r+   rW   r?   r.   r0   r1   rW   Y  s    zExpanding.skewz/scipy.stats.kurtosis : Reference SciPy method.
z<A minimum of four periods is required for the calculation.

a[  
        The example below will show a rolling calculation with a window size of
        four matching the equivalent function call using `scipy.stats`.

        >>> arr = [1, 2, 3, 4, 999]
        >>> import scipy.stats
        >>> print(f"{{scipy.stats.kurtosis(arr[:-1], bias=False):.6f}}")
        -1.200000
        >>> print(f"{{scipy.stats.kurtosis(arr, bias=False):.6f}}")
        4.999874
        >>> s = pd.Series(arr)
        >>> s.expanding(4).kurt()
        0         NaN
        1         NaN
        2         NaN
        3   -1.200000
        4    4.999874
        dtype: float64
        z,Fisher's definition of kurtosis without biasÚkurtc                   s   t ƒ j|d�S r>   )r+   rX   r?   r.   r0   r1   rX   x  s    &zExpanding.kurtaæ  
        quantile : float
            Quantile to compute. 0 <= quantile <= 1.

            .. deprecated:: 2.1.0
                This will be renamed to 'q' in a future version.
        interpolation : {{'linear', 'lower', 'higher', 'midpoint', 'nearest'}}
            This optional parameter specifies the interpolation method to use,
            when the desired quantile lies between two data points `i` and `j`:

                * linear: `i + (j - i) * fraction`, where `fraction` is the
                  fractional part of the index surrounded by `i` and `j`.
                * lower: `i`.
                * higher: `j`.
                * nearest: `i` or `j` whichever is nearest.
                * midpoint: (`i` + `j`) / 2.
        a          >>> ser = pd.Series([1, 2, 3, 4, 5, 6], index=['a', 'b', 'c', 'd', 'e', 'f'])
        >>> ser.expanding(min_periods=4).quantile(.25)
        a     NaN
        b     NaN
        c     NaN
        d    1.75
        e    2.00
        f    2.25
        dtype: float64
        ÚquantileÚq)Zold_arg_nameZnew_arg_nameÚlinearÚfloatr   ©rZ   Úinterpolationr=   c                   s   t ƒ j|||d�S )Nr]   )r+   rY   )r-   rZ   r^   r=   r.   r0   r1   rY      s
    4ýzExpanding.quantilez.. versionadded:: 1.4.0 

a  
        method : {{'average', 'min', 'max'}}, default 'average'
            How to rank the group of records that have the same value (i.e. ties):

            * average: average rank of the group
            * min: lowest rank in the group
            * max: highest rank in the group

        ascending : bool, default True
            Whether or not the elements should be ranked in ascending order.
        pct : bool, default False
            Whether or not to display the returned rankings in percentile
            form.
        a+  
        >>> s = pd.Series([1, 4, 2, 3, 5, 3])
        >>> s.expanding().rank()
        0    1.0
        1    2.0
        2    2.0
        3    3.0
        4    5.0
        5    3.5
        dtype: float64

        >>> s.expanding().rank(method="max")
        0    1.0
        1    2.0
        2    2.0
        3    3.0
        4    5.0
        5    4.0
        dtype: float64

        >>> s.expanding().rank(method="min")
        0    1.0
        1    2.0
        2    2.0
        3    3.0
        4    5.0
        5    3.0
        dtype: float64
        ÚrankÚaverageTr   ©r!   Ú	ascendingÚpctr=   c                   s   t ƒ j||||d�S )Nra   )r+   r_   )r-   r!   rb   rc   r=   r.   r0   r1   r_   Ú  s    DüzExpanding.ranka   
        other : Series or DataFrame, optional
            If not supplied then will default to self and produce pairwise
            output.
        pairwise : bool, default None
            If False then only matching columns between self and other will be
            used and the output will be a DataFrame.
            If True then all pairwise combinations will be calculated and the
            output will be a MultiIndexed DataFrame in the case of DataFrame
            inputs. In the case of missing elements, only complete pairwise
            observations will be used.
        ddof : int, default 1
            Delta Degrees of Freedom.  The divisor used in calculations
            is ``N - ddof``, where ``N`` represents the number of elements.
        a0          >>> ser1 = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
        >>> ser2 = pd.Series([10, 11, 13, 16], index=['a', 'b', 'c', 'd'])
        >>> ser1.expanding().cov(ser2)
        a         NaN
        b    0.500000
        c    1.500000
        d    3.333333
        dtype: float64
        zsample covarianceÚcovzDataFrame | Series | Nonezbool | None©ÚotherÚpairwiserQ   r=   c                   s   t ƒ j||||d�S ©Nre   )r+   rd   ©r-   rf   rg   rQ   r=   r.   r0   r1   rd   %  s    1üzExpanding.covaN  
        other : Series or DataFrame, optional
            If not supplied then will default to self and produce pairwise
            output.
        pairwise : bool, default None
            If False then only matching columns between self and other will be
            used and the output will be a DataFrame.
            If True then all pairwise combinations will be calculated and the
            output will be a MultiIndexed DataFrame in the case of DataFrame
            inputs. In the case of missing elements, only complete pairwise
            observations will be used.
        z�
        cov : Similar method to calculate covariance.
        numpy.corrcoef : NumPy Pearson's correlation calculation.
        ao  
        This function uses Pearson's definition of correlation
        (https://en.wikipedia.org/wiki/Pearson_correlation_coefficient).

        When `other` is not specified, the output will be self correlation (e.g.
        all 1's), except for :class:`~pandas.DataFrame` inputs with `pairwise`
        set to `True`.

        Function will return ``NaN`` for correlations of equal valued sequences;
        this is the result of a 0/0 division error.

        When `pairwise` is set to `False`, only matching columns between `self` and
        `other` will be used.

        When `pairwise` is set to `True`, the output will be a MultiIndex DataFrame
        with the original index on the first level, and the `other` DataFrame
        columns on the second level.

        In the case of missing elements, only complete pairwise observations
        will be used.

        a1          >>> ser1 = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
        >>> ser2 = pd.Series([10, 11, 13, 16], index=['a', 'b', 'c', 'd'])
        >>> ser1.expanding().corr(ser2)
        a         NaN
        b    1.000000
        c    0.981981
        d    0.975900
        dtype: float64
        ZcorrelationÚcorrc                   s   t ƒ j||||d�S rh   )r+   rj   ri   r.   r0   r1   rj   ]  s    LüzExpanding.corr)r#   r   r$   N)F)FNNNN)FNN)FNN)FNN)FNN)FNN)r#   FNN)r#   FNN)r#   F)F)F)r[   F)r`   TFF)NNr#   F)NNr#   F)(Ú__name__Ú
__module__Ú__qualname__Ú__doc__r"   Ú__annotations__r,   r3   r	   r   r   r4   Zaggr   r   r   r   r:   r   r@   r   r   r   rD   rI   rK   rL   rM   ÚreplacerO   rT   rU   rW   rX   r   rY   r_   rd   rj   Ú__classcell__r0   r0   r.   r1   r   3   sX  
F    úÿÿãÿìÿê     ù ÿç   üÿç   üÿç   üÿç   üÿç   üÿúÿùÿòÔ0    ûÿúÿùÿòÔ0    ûÿúÿõà"ÿæÿìÝ%ÿîÿÕ-
  üÿñÿâÅ?    ûÿðÿØ,    ûÿóÿûÿÿ½G    ûr   c                   @  s*   e Zd ZdZejej Zddœdd„ZdS )ÚExpandingGroupbyz5
    Provide a expanding groupby implementation.
    r   r2   c                 C  s   t | jjtd�}|S )z“
        Return an indexer class that will compute the window start and end bounds

        Returns
        -------
        GroupbyIndexer
        )Zgroupby_indicesÚwindow_indexer)r   Ú_grouperÚindicesr   )r-   rs   r0   r0   r1   r3   ¸  s
    þz$ExpandingGroupby._get_window_indexerN)rk   rl   rm   rn   r   r"   r   r3   r0   r0   r0   r1   rr   ±  s   rr   N)(Ú
__future__r   Útextwrapr   Útypingr   r   r   r   Zpandas.util._decoratorsr   r	   Zpandas.core.indexers.objectsr
   r   r   Zpandas.core.window.docr   r   r   r   r   r   r   r   r   Zpandas.core.window.rollingr   r   Zpandas._typingr   r   r   Zpandasr   r   Zpandas.core.genericr   r   rr   r0   r0   r0   r1   Ú<module>   s&   ,       