HOME


sh-3ll 1.0
DIR:/usr/local/lib64/python3.6/site-packages/pandas/core/window/__pycache__/
Upload File :
Current File : //usr/local/lib64/python3.6/site-packages/pandas/core/window/__pycache__/rolling.cpython-36.pyc
3

���hn�@sFdZddlmZddlmZddlZddlmZddlm	Z	m
Z
mZmZm
Z
mZmZmZddlZddlmZmZddljjjZddlmZmZmZdd	lm Z dd
l!m"Z#ddl$m%Z%m&Z&m'Z'm(Z(ddl)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1dd
l2m3Z3m4Z4m5Z5m6Z6m7Z7ddl8m9Z9m:Z:m;Z;m<Z<ddl=j>j?Z@ddlAmBZBddlCmDZDmEZEmFZFddlGmHZHmIZIddlJmKZKmLZLmMZMmNZNmOZOddlPmQZQmRZRmSZSmTZTddlUmVZVeWd�dd�ZXeWeeWeWeWeWeWd�dd�ZYe	e	d�dd�ZZGdd�de:e<e;�Z[Gd d!�d!e[�Z\Gd"d#�d#e[�Z]Gd$d%�d%e]�Z^Gd&d'�d'e^�Z_e\je__Gd(d)�d)eKe_�Z`dS)*zc
Provide a generic structure to support window functions,
similar to how we have a Groupby object.
�)�	timedelta)�partialN)�dedent)�Callable�Dict�List�Optional�Set�Tuple�Type�Union)�
BaseOffset�	to_offset)�Axis�
FrameOrSeries�Scalar)�import_optional_dependency)�function)�Appender�Substitution�cache_readonly�doc)�ensure_float64�is_bool�is_float_dtype�
is_integer�is_integer_dtype�is_list_like�	is_scalar�needs_i8_conversion)�ABCDataFrame�ABCDatetimeIndex�ABCPeriodIndex�	ABCSeries�ABCTimedeltaIndex)�	DataError�PandasObject�SelectionMixin�ShallowMixin)�
extract_array)�Index�
MultiIndex�ensure_index)�NUMBA_FUNC_CACHE�maybe_use_numba)�WindowGroupByMixin�
_doc_template�_flex_binary_moment�_shared_docs�zsqrt)�BaseIndexer�FixedWindowIndexer�GroupbyRollingIndexer�VariableWindowIndexer)�generate_numba_apply_func)�returncCs t|�st|�}t|dd�S)z�
    Calculate an offset necessary to have the window label to be centered.

    Parameters
    ----------
    window: ndarray or int
        window weights or window

    Returns
    -------
    int
    �g@)r�len�int)�window�r>�</tmp/pip-build-5_djhm0z/pandas/pandas/core/window/rolling.py�calculate_center_offset;s
r@)r=�min_periods�
num_values�required_min_periods�floorr9cCsb|dkr|}n
t||�}||kr6td|�d|����n"||krH|d}n|dkrXtd��t||�S)a�
    Calculate final minimum periods value for rolling aggregations.

    Parameters
    ----------
    window : passed window value
    min_periods : passed min periods value
    num_values : total number of values
    required_min_periods : required min periods per aggregation function
    floor : required min periods per aggregation function

    Returns
    -------
    min_periods : int
    Nzmin_periods z must be <= window r:rzmin_periods must be >= 0)�max�
ValueError)r=rArBrCrDr>r>r?�calculate_min_periodsMs

rG)�cfuncr9csd�fdd�	}|S)z�
    Wrap weighted rolling cython function with min periods argument.

    Parameters
    ----------
    cfunc : function
        Cython weighted rolling function

    Returns
    -------
    function
    Ncs|dkrt|�}�|||�S)N)r;)�argr=rA)rHr>r?�func~sz$get_weighted_roll_func.<locals>.func)Nr>)rHrJr>)rHr?�get_weighted_roll_funcpsrKc
@seZdZUdddddddgZeee�ZeedQe	e
eee
ee
e
eeefe
ed�dd
�Zedd��Zee
ed�dd��Zedd��Zeed�dd��Zdd�dd�Zeedd�dd��Ze	d�dd�ZdRdd �Zed!�d"d#�Zd$d%�Zed&�d'd(�ZdSe
eed)�d*d+�Z eed�d,d-��Z!ed�d.d/�Z"d0d1�Z#dTe
e$j%e$j%d2�d3d4�Z&dUd5d6�Z'dVe	d�d7d8�Z(e$j%d�d9d:�Z)ee*d;�d<d=�Z+ee*d>�d?d@�Z,eed�dAdB�Z-dWe*eeeee
eedD�dEdF�Z.dGdH�Z/e/Z0e1dI�e2dJ<e1dK�e2dL<e1dM�e2dN<e1dO�e2dP<dS)X�_Windowr=rA�center�win_type�axis�on�closedNFr)�objrArMrNrOrPrQc	
Ks`|jj|	�||_||_||_||_||_||_||_d|_	|dk	rN|j
|�nd|_|j�dS)N)
�__dict__�updaterRrPrQr=rArMrN�win_freqZ_get_axis_numberrO�validate)
�selfrRr=rArMrNrOrPrQ�kwargsr>r>r?�__init__�s
z_Window.__init__cCstS)N)�Window)rWr>r>r?�_constructor�sz_Window._constructor)r9cCsdS)Nr>)rWr>r>r?�is_datetimelike�sz_Window.is_datetimelikecCsdS)Nr>)rWr>r>r?�_on�sz_Window._oncCs
|jdkS)N�freq)rN)rWr>r>r?�is_freq_type�sz_Window.is_freq_typecCs�|jdk	rt|j�rtd��|jdk	r<t|j�r<td��|jdk	rX|jd	krXtd��t|jtt	f�szt
dt|�����t|jt
�r�|j|j�dS)
Nzcenter must be a booleanzmin_periods must be an integer�right�both�left�neitherz3closed must be 'right', 'left', 'both' or 'neither'zinvalid type: )r`rarbrc)rMrrFrArrQ�
isinstancerRr#r �	TypeError�typer=r4�%_validate_get_window_bounds_signature)rWr>r>r?rV�sz_Window.validate)r=r9cCsFtj|j�jj�}tjt�j�jj�}||krBtt|�j�d���dS)z{
        Validate that the passed BaseIndexer subclass has
        a get_window_bounds with the correct signature.
        z? does not implement the correct signature for get_window_boundsN)	�inspect�	signature�get_window_boundsZ
parameters�keysr4rFrf�__name__)r=Zget_window_bounds_signatureZexpected_signaturer>r>r?rg�sz-_Window._validate_get_window_bounds_signature)rRcCsT|jdk	r<t|jt�r<|jdkr<|j|jj|jg�dd�}|jdd�j�}||fS)zA
        Split data into blocks & return conformed data.
        N�F)�columns�copy)ro)	rPrdr*�ndim�reindexrn�
differenceZ_to_dict_of_blocks�values)rWrR�blocksr>r>r?�_create_blocks�s

z_Window._create_blockscCsL|dkr|j}|j|�}|j�|jdkrHt|�r:||ksBt|�rH||_|S)a	
        Sub-classes to define. Return a sliced object.

        Parameters
        ----------
        key : str / list of selections
        ndim : 1,2
            requested ndim of result
        subset : object, default None
            subset to act on
        Nrm)rR�
_shallow_copy�_reset_cacherprr�
_selection)rW�keyrp�subsetr>r>r?�_gotitem�s


z_Window._gotitem)�attrcCsH||jkrtj||�S||jkr(||Stdt|�j�d|�d���dS)N�'z' object has no attribute ')Z_internal_names_set�object�__getattribute__rR�AttributeErrorrfrl)rWr|r>r>r?�__getattr__s

z_Window.__getattr__cCs
|jj�S)N)rR�_dir_additions)rWr>r>r?r�
sz_Window._dir_additions)rXcCsdS)z�
        Exists for compatibility, overridden by subclass Window.

        Parameters
        ----------
        kwargs : dict
            ignored, exists for compatibility

        Returns
        -------
        None
        Nr>)rWrXr>r>r?�
_get_win_type
s
z_Window._get_win_type)rNr9cCst|jt�r|jpdS|jS)a
        Return window length.

        Parameters
        ----------
        other :
            ignored, exists for compatibility
        win_type :
            ignored, exists for compatibility

        Returns
        -------
        window : int
        r)rdr=r4rA)rW�otherrNr>r>r?�_get_windows
z_Window._get_windowcCs
t|�jS)N)rfrl)rWr>r>r?�_window_type/sz_Window._window_typecs0�fdd��jD�}dj|�}�j�d|�d�S)z@
        Provide a nice str repr of our rolling object.
        c3s2|]*}t�|d�dk	r|�dt�|���VqdS)N�=)�getattr)�.0�	attr_name)rWr>r?�	<genexpr>8sz#_Window.__repr__.<locals>.<genexpr>�,z [�])�_attributes�joinr�)rWZ
attrs_list�attrsr>)rWr?�__repr__3s


z_Window.__repr__c
cs�|jdd�}|j|j�\}}|j|d�}|jt|�|j|j|jd�\}}t|�t|�ks\t	�x,t
||�D]\}}|jt||�}	|	VqhWdS)N)rN)r=)rBrArMrQ)
r�ru�
_selected_obj�_get_window_indexerrjr;rArMrQ�AssertionError�zipZiloc�slice)
rWr=rtrR�index�start�end�s�e�resultr>r>r?�__iter__?sz_Window.__iter__)rsr9cCs�|dkrt|jdd�}t|j�r*t|�}n�t|j�r>t|�}nlt|j�rdtd|j�d|j�d���nFyt|�}Wn8t	t
fk
r�}zt
d|j���|�WYdd}~XnXtj|�}|j
�r�tj|tj|�}|S)z1Convert input to numpy arrays for Cython routinesNT)Z
extract_numpyzops for z for this dtype z are not implementedzcannot handle this type -> )r)r�r�dtyperrr�NotImplementedErrorr�rFre�np�isinf�any�where�nan)rWrs�err�infr>r>r?�_prep_valuesQs"




$
z_Window._prep_valuescCs^|dkr|j}|j}t|tj�rZ|jdkrFddlm}||||jd�St	|�|||j
d�S|S)z'
        Wrap a single result.
        Nr:r)�Series)�name)r�rn)r�r�rdr��ndarrayrp�pandasr�r�rfrn)rWr��blockrRr�r�r>r>r?�_wrap_resultns
z_Window._wrap_resultcs6ddlm}m}g}x>t||�D]0\}}	|j||	|d�}|jdkrF|S|j|�q W|jj}
|j	dk	r�|j
j|j�r�|j
j
}|j||j
|jj|d��|jdk	r�t|j�}||kr�|jj}
|
j|j�|g�}
|
jt|
��}
�dk	o��r�fdd�|
D�}
|
�std	��t|��s |jd
�S||dd�j|
dd
�S)z�
        Wrap the results.

        Parameters
        ----------
        results : list of ndarrays
        blocks : list of blocks
        obj : conformed data (may be resampled)
        exclude: list of columns to exclude, default to None
        r)r��concat)r�rRr:N)r�r�csg|]}|�kr|�qSr>r>)r��c)�excluder>r?�
<listcomp>�sz)_Window._wrap_results.<locals>.<listcomp>zNo numeric types to aggregate�float64)rOF)rnro)r�r�r�r�r�rp�appendr�rnrPr]�equalsr�r�rRrxr,Zget_indexer�tolist�take�sortedr%r;�astyperq)rW�resultsrtrRr�r�r��finalr�r�rnr�Z	selection�indexerr>)r�r?�
_wrap_results�s0




z_Window._wrap_resultscCs^|j|jdkrtd��t|�}|dkrZtd�g|j}t|d�||j<tj|t|��}|S)z2
        Center the result in the window.
        r:z8Requested axis is larger then no. of argument dimensionsrN)rOrprFr@r�r�ro�tuple)rWr�r=�offsetZlead_indexerr>r>r?�_center_window�sz_Window._center_window)�	func_namer9cCs&tt|d�}|dkr"td|����|S)z�
        Wrap rolling function to check values passed.

        Parameters
        ----------
        func_name : str
            Cython function used to calculate rolling statistics

        Returns
        -------
        func : callable
        Nz7we do not support this function in window_aggregations.)r��window_aggregationsrF)rWr��window_funcr>r>r?�_get_roll_func�s

z_Window._get_roll_func)rJr9cCs>|jst|jt�r"|j|�d��St|j|�d��|j�d�S)z�
        Return a variable or fixed cython function type.

        Variable algorithms do not use window while fixed do.
        �	_variableZ_fixed)�win)r_rdr=r4r�rr�)rWrJr>r>r?�_get_cython_func_type�sz_Window._get_cython_func_typecCs2t|jt�r|jS|jr(t|jj|d�St|d�S)z[
        Return an indexer class that will compute the window start and end bounds
        )�index_array�window_size)r�)rdr=r4r_r7r]�asi8r5)rWr=r>r>r?r��s
z_Window._get_window_indexerr:)rJrM�require_min_periodsrD�is_weightedr��use_numba_cachecs��j|�}	�j|	d���j�j�\}
}t|
�}�j���g}
g}�x`t|
�D�]R\}}y�j|j�}WnPt	t
fk
r�}z0t|t�r�|j
|j�||=wLn
td�|�WYdd}~XnX|jdkr�|
j|j��qL|r�t��nd}tjtjg|��|�s�������fdd�}n����fdd�}tjdd	��6|jd
k�rRtj|�j|�}n||�}tj|�}WdQRX|�r��t|ddf<|�r��j|��}|
j|�qLW�j|
|||�S)
a�
        Rolling statistical measure using supplied function.

        Designed to be used with passed-in Cython array-based functions.

        Parameters
        ----------
        func : callable function to apply
        center : bool
        require_min_periods : int
        floor : int
        is_weighted : bool
        name : str,
            compatibility with groupby.rolling
        use_numba_cache : bool
            whether to cache a numba compiled function. Only available for numba
            enabled methods (so far only apply)
        **kwargs
            additional arguments for rolling function and window function

        Returns
        -------
        y : type of input
        )rNzNo numeric types to aggregateNrcsxtj|�f�}t�jt�s2t��jt|����}nt�j�jt|����}�j	t|��j�j
�jd�\}}�||||�S)N)rBrArMrQ)r��concatenaterdr=r4rGrAr;r�rjrMrQ)�xrAr�r�)�additional_nansrDrJr�rWr=�window_indexerr>r?�calc,s z_Window._apply.<locals>.calccstj|�f�}�|��j�S)N)r�r�rA)r�)r�rJrWr=r>r?r�Ds�ignore)�allr:�
original_func�
rolling_apply)r�r�rur��listr��	enumerater�rsrer�rdr �extendrnr%�sizer�ror@r��arrayr�ZerrstaterpZapply_along_axisrOZasarrayr-r�r�)rWrJrMr�rDr�r�r�rXrNrtrRZ
block_listr�r��i�brsr�r�r�r�r>)r�rDrJr�rWr=r�r?�_apply�sF#



z_Window._applycOs4|j|f|�|�\}}|dkr0|j|d||d�S|S)NF)�raw�argsrX)�
_aggregate�apply)rWrJr�rXr��howr>r>r?�	aggregateYsz_Window.aggregatea8
    Calculate %(name)s sum of given DataFrame or Series.

    Parameters
    ----------
    *args, **kwargs
        For compatibility with other %(name)s methods. Has no effect
        on the computed value.

    Returns
    -------
    Series or DataFrame
        Same type as the input, with the same index, containing the
        %(name)s sum.

    See Also
    --------
    pandas.Series.sum : Reducing sum for Series.
    pandas.DataFrame.sum : Reducing sum for DataFrame.

    Examples
    --------
    >>> s = pd.Series([1, 2, 3, 4, 5])
    >>> s
    0    1
    1    2
    2    3
    3    4
    4    5
    dtype: int64

    >>> s.rolling(3).sum()
    0     NaN
    1     NaN
    2     6.0
    3     9.0
    4    12.0
    dtype: float64

    >>> s.expanding(3).sum()
    0     NaN
    1     NaN
    2     6.0
    3    10.0
    4    15.0
    dtype: float64

    >>> s.rolling(3, center=True).sum()
    0     NaN
    1     6.0
    2     9.0
    3    12.0
    4     NaN
    dtype: float64

    For DataFrame, each %(name)s sum is computed column-wise.

    >>> df = pd.DataFrame({"A": s, "B": s ** 2})
    >>> df
       A   B
    0  1   1
    1  2   4
    2  3   9
    3  4  16
    4  5  25

    >>> df.rolling(3).sum()
          A     B
    0   NaN   NaN
    1   NaN   NaN
    2   6.0  14.0
    3   9.0  29.0
    4  12.0  50.0
    �suma�
    Calculate the %(name)s mean of the values.

    Parameters
    ----------
    *args
        Under Review.
    **kwargs
        Under Review.

    Returns
    -------
    Series or DataFrame
        Returned object type is determined by the caller of the %(name)s
        calculation.

    See Also
    --------
    pandas.Series.%(name)s : Calling object with Series data.
    pandas.DataFrame.%(name)s : Calling object with DataFrames.
    pandas.Series.mean : Equivalent method for Series.
    pandas.DataFrame.mean : Equivalent method for DataFrame.

    Examples
    --------
    The below examples will show rolling mean calculations with window sizes of
    two and three, respectively.

    >>> s = pd.Series([1, 2, 3, 4])
    >>> s.rolling(2).mean()
    0    NaN
    1    1.5
    2    2.5
    3    3.5
    dtype: float64

    >>> s.rolling(3).mean()
    0    NaN
    1    NaN
    2    2.0
    3    3.0
    dtype: float64
    �meana�
    Calculate unbiased %(name)s variance.
    %(versionadded)s
    Normalized by N-1 by default. This can be changed using the `ddof`
    argument.

    Parameters
    ----------
    ddof : int, default 1
        Delta Degrees of Freedom.  The divisor used in calculations
        is ``N - ddof``, where ``N`` represents the number of elements.
    *args, **kwargs
        For NumPy compatibility. No additional arguments are used.

    Returns
    -------
    Series or DataFrame
        Returns the same object type as the caller of the %(name)s calculation.

    See Also
    --------
    pandas.Series.%(name)s : Calling object with Series data.
    pandas.DataFrame.%(name)s : Calling object with DataFrames.
    pandas.Series.var : Equivalent method for Series.
    pandas.DataFrame.var : Equivalent method for DataFrame.
    numpy.var : Equivalent method for Numpy array.

    Notes
    -----
    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 1 period is required for the rolling calculation.

    Examples
    --------
    >>> s = pd.Series([5, 5, 6, 7, 5, 5, 5])
    >>> s.rolling(3).var()
    0         NaN
    1         NaN
    2    0.333333
    3    1.000000
    4    1.000000
    5    1.333333
    6    0.000000
    dtype: float64

    >>> 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
    �vara�
    Calculate %(name)s standard deviation.
    %(versionadded)s
    Normalized by N-1 by default. This can be changed using the `ddof`
    argument.

    Parameters
    ----------
    ddof : int, default 1
        Delta Degrees of Freedom.  The divisor used in calculations
        is ``N - ddof``, where ``N`` represents the number of elements.
    *args, **kwargs
        For NumPy compatibility. No additional arguments are used.

    Returns
    -------
    Series or DataFrame
        Returns the same object type as the caller of the %(name)s calculation.

    See Also
    --------
    pandas.Series.%(name)s : Calling object with Series data.
    pandas.DataFrame.%(name)s : Calling object with DataFrames.
    pandas.Series.std : Equivalent method for Series.
    pandas.DataFrame.std : Equivalent method for DataFrame.
    numpy.std : Equivalent method for Numpy array.

    Notes
    -----
    The default `ddof` of 1 used in Series.std is different than the default
    `ddof` of 0 in numpy.std.

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

    Examples
    --------
    >>> s = pd.Series([5, 5, 6, 7, 5, 5, 5])
    >>> s.rolling(3).std()
    0         NaN
    1         NaN
    2    0.577350
    3    1.000000
    4    1.000000
    5    1.154701
    6    0.000000
    dtype: float64

    >>> 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
    �std)NNFNrNN)N)NN)N)NN)N)rr:FNF)3rl�
__module__�__qualname__r�r�str�setZ
exclusionsr	rrr<�boolrrr*rY�propertyr[r\r]r_rV�staticmethodr4rgrur{r�r�rr�r�r�r�r�r�r�r�r�r�r�rr�r�r�r�r��aggrr2r>r>r>r?rL�sp
4


4
 gJ
+
9
9rLcseZdZdZ�fdd�Zeeeefd�dd�Z	d$e
eeefejd�d	d
�Z
ed�Zed�Zeed
eedddd�dd��ZeZedd�eed�dd���Zedd�eed�dd���Zeddd�eed�d%dd ���Zeddd�eed!�d&d"d#���Z�ZS)'rZa
    Provide rolling window calculations.

    Parameters
    ----------
    window : int, offset, or BaseIndexer subclass
        Size of the moving window. This is the number of observations used for
        calculating the statistic. Each window will be a fixed size.

        If its an offset then this will be the time period of each window. Each
        window will be a variable sized based on the observations included in
        the time-period. This is only valid for datetimelike indexes.

        If a BaseIndexer subclass is passed, calculates the window boundaries
        based on the defined ``get_window_bounds`` method. Additional rolling
        keyword arguments, namely `min_periods`, `center`, and
        `closed` will be passed to `get_window_bounds`.
    min_periods : int, default None
        Minimum number of observations in window required to have a value
        (otherwise result is NA). For a window that is specified by an offset,
        `min_periods` will default to 1. Otherwise, `min_periods` will default
        to the size of the window.
    center : bool, default False
        Set the labels at the center of the window.
    win_type : str, default None
        Provide a window type. If ``None``, all points are evenly weighted.
        See the notes below for further information.
    on : str, optional
        For a DataFrame, a datetime-like column or MultiIndex level on which
        to calculate the rolling window, rather than the DataFrame's index.
        Provided integer column is ignored and excluded from result since
        an integer index is not used to calculate the rolling window.
    axis : int or str, default 0
    closed : str, default None
        Make the interval closed on the 'right', 'left', 'both' or
        'neither' endpoints.
        For offset-based windows, it defaults to 'right'.
        For fixed windows, defaults to 'both'. Remaining cases not implemented
        for fixed windows.

    Returns
    -------
    a Window or Rolling sub-classed for the particular operation

    See Also
    --------
    expanding : Provides expanding transformations.
    ewm : Provides exponential weighted functions.

    Notes
    -----
    By default, the result is set to the right edge of the window. This can be
    changed to the center of the window by setting ``center=True``.

    To learn more about the offsets & frequency strings, please see `this link
    <https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__.

    The recognized win_types are:

    * ``boxcar``
    * ``triang``
    * ``blackman``
    * ``hamming``
    * ``bartlett``
    * ``parzen``
    * ``bohman``
    * ``blackmanharris``
    * ``nuttall``
    * ``barthann``
    * ``kaiser`` (needs parameter: beta)
    * ``gaussian`` (needs parameter: std)
    * ``general_gaussian`` (needs parameters: power, width)
    * ``slepian`` (needs parameter: width)
    * ``exponential`` (needs parameter: tau), center is set to None.

    If ``win_type=None`` all points are evenly weighted. To learn more about
    different window types see `scipy.signal window functions
    <https://docs.scipy.org/doc/scipy/reference/signal.html#window-functions>`__.

    Certain window types require additional parameters to be passed. Please see
    the third example below on how to add the additional parameters.

    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

    Rolling sum with a window length of 2, using the 'triang'
    window type.

    >>> df.rolling(2, win_type='triang').sum()
         B
    0  NaN
    1  0.5
    2  1.5
    3  NaN
    4  NaN

    Rolling sum with a window length of 2, using the 'gaussian'
    window type (note how we need to specify std).

    >>> df.rolling(2, win_type='gaussian').sum(std=3)
              B
    0       NaN
    1  0.986207
    2  2.958621
    3       NaN
    4       NaN

    Rolling sum with a window length of 2, min_periods defaults
    to the window length.

    >>> df.rolling(2).sum()
         B
    0  NaN
    1  1.0
    2  3.0
    3  NaN
    4  NaN

    Same as above, but explicitly set the min_periods

    >>> df.rolling(2, min_periods=1).sum()
         B
    0  0.0
    1  1.0
    2  3.0
    3  2.0
    4  4.0

    Same as above, but with forward-looking windows

    >>> indexer = pd.api.indexers.FixedForwardWindowIndexer(window_size=2)
    >>> df.rolling(window=indexer, min_periods=1).sum()
         B
    0  1.0
    1  3.0
    2  2.0
    3  4.0
    4  4.0

    A ragged (meaning not-a-regular frequency), time-indexed DataFrame

    >>> df = pd.DataFrame({'B': [0, 1, 2, np.nan, 4]},
    ...                   index = [pd.Timestamp('20130101 09:00:00'),
    ...                            pd.Timestamp('20130101 09:00:02'),
    ...                            pd.Timestamp('20130101 09:00:03'),
    ...                            pd.Timestamp('20130101 09:00:05'),
    ...                            pd.Timestamp('20130101 09:00:06')])

    >>> df
                           B
    2013-01-01 09:00:00  0.0
    2013-01-01 09:00:02  1.0
    2013-01-01 09:00:03  2.0
    2013-01-01 09:00:05  NaN
    2013-01-01 09:00:06  4.0

    Contrasting to an integer rolling window, this will roll a variable
    length window corresponding to the time period.
    The default for min_periods is 1.

    >>> df.rolling('2s').sum()
                           B
    2013-01-01 09:00:00  0.0
    2013-01-01 09:00:02  1.0
    2013-01-01 09:00:03  3.0
    2013-01-01 09:00:05  NaN
    2013-01-01 09:00:06  4.0
    cs�t�j�|j}t|t�r$td��n�t|tttj	f�r8n|t
|�r�|dkrPtd��tddd�ddl
j}t|jt�s�td|j����t||jd�dkr�td|j����ntd|����dS)	Nz6BaseIndexer subclasses not implemented with win_types.rzwindow must be > 0 Zscipyz,Scipy is required to generate window weight.)�extrazInvalid win_type zInvalid window )�superrVr=rdr4r�r�r�r�r�rrFr�scipy.signal�signalrNr�r�)rWr=�sig)�	__class__r>r?rVs$



zWindow.validate)rXr9cs �fdd�}dd��||j|�S)z�
        Extract arguments for the window type, provide validation for it
        and return the validated window type.

        Parameters
        ----------
        kwargs : dict

        Returns
        -------
        win_type : str, or tuple
        csZdgdgddgdgdgd�}||krV�||||�}|dkrH|jdd�t|g|�S|S)	N�betar��power�width�tau)ZkaiserZgaussianZgeneral_gaussianZslepian�exponentialr�r)�insertr�)rNrXZarg_mapZwin_args)�	_pop_argsr>r?�_validate_win_type.s
z0Window._get_win_type.<locals>._validate_win_typecSs@g}x6|D].}||kr(t|�d|����|j|j|��q
W|S)Nz window requires )rFr��pop)rNZ	arg_namesrXZall_args�nr>r>r?r�Bs
z'Window._get_win_type.<locals>._pop_args)rN)rWrXr�r>)r�r?r� szWindow._get_win_typeN)rNr9cCsR|j}t|tttjf�r(tj|�jt	�St
|�rNddlj}|j
||d�jt	�SdS)a/
        Get the window, weights.

        Parameters
        ----------
        other :
            ignored, exists for compatibility
        win_type : str, or tuple
            type of window to create

        Returns
        -------
        window : ndarray
            the window, weights
        rNF)r=rdr�r�r�r��comZasarray_tuplesafer��floatrr�r�Z
get_window)rWr�rNr=r�r>r>r?r�Ls
zWindow._get_windowz�
    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.rolling(2, win_type="boxcar").agg("mean")
         A    B    C
    0  NaN  NaN  NaN
    1  1.5  4.5  7.5
    2  2.5  5.5  8.5
    r��zSeries/DataFrame)�see_also�examples�versionadded�klassrOcOs*|j|f|�|�\}}|dkr&||�}|S)N)r�)rWrJr�rXr�r�r>r>r?r��s	zWindow.aggregater=)r�r�cOs<tjd||�|jd�}t|�}|j|f|jddd�|��S)Nr�Zroll_weighted_sumT)rMr�r�)�nv�validate_window_funcr�rKr�rM)rWr�rXr�r>r>r?r��s

z
Window.sumr�cOs<tjd||�|jd�}t|�}|j|f|jddd�|��S)Nr�Zroll_weighted_meanT)rMr�r�)rrr�rKr�rM)rWr�rXr�r>r>r?r��s

zWindow.meanz
.. versionadded:: 1.0.0
)r�rr�r:cOsPtjd||�t|jd�|d�}t|�}|jdd�|j|f|jddd�|��S)Nr�Zroll_weighted_var)�ddofr�T)rMr�r�)rrrr�rKr�r�rM)rWr	r�rXr�r>r>r?r��sz
Window.varr�cOs(tjd||�t|jf|dd�|���S)Nr�)r	r�)rrr3r�)rWr	r�rXr>r>r?r��sz
Window.std)NN)r:)r:)rlr�r��__doc__rVrrr�r
r�rr�r�r�r�_agg_see_also_doc�_agg_examples_docrr2r�r�rrr�r�r�r��
__classcell__r>r>)r�r?rZUs81-		

	

rZc@seZdZedd��ZdS)�_RollingcCstS)N)�Rolling)rWr>r>r?r[�sz_Rolling._constructorN)rlr�r�r�r[r>r>r>r?r�src@seZdZed�ed<dd�Zed�ed<d8eeeee	ee
ee	d	�d
d�Zdd
�Zdd�Z
ed�ed<dd�Zed�ed<dd�Zdd�Zed�ed<dd�Zd9dd �Zd:d!d"�Zd#ed$<d%d&�Zed'�ed(<d)d*�Zed+�ed,<d;d.d/�Zd0ed1<d<d2d3�Zed4�ed5<d=d6d7�ZdS)>�_Rolling_and_Expandinga
    The %(name)s count of any non-NaN observations inside the window.

    Returns
    -------
    Series or DataFrame
        Returned object type is determined by the caller of the %(name)s
        calculation.

    See Also
    --------
    pandas.Series.%(name)s : Calling object with Series data.
    pandas.DataFrame.%(name)s : Calling object with DataFrames.
    pandas.DataFrame.count : Count of the full DataFrame.

    Examples
    --------
    >>> s = pd.Series([2, 3, np.nan, 10])
    >>> s.rolling(2).count()
    0    1.0
    1    2.0
    2    1.0
    3    1.0
    dtype: float64
    >>> s.rolling(3).count()
    0    1.0
    1    2.0
    2    2.0
    3    2.0
    dtype: float64
    >>> s.rolling(4).count()
    0    1.0
    1    2.0
    2    2.0
    3    3.0
    dtype: float64
    �countc	Cs�t|jt�st�|j|j�\}}g}xN|D]F}|j�jt�}|j	||j
�|jpRd|j|j
|jd�j�}|j|�q,W|j|||�S)Nr)r=rArMrOrQ)rdr=r4r�rur�Znotnar�r<r[r�rArMrOrQr�r�r�)rWrtrRr�r�r�r>r>r?r�s
z_Rolling_and_Expanding.counta�
    Apply an arbitrary function to each %(name)s window.

    Parameters
    ----------
    func : function
        Must produce a single value from an ndarray input if ``raw=True``
        or a single value from a Series if ``raw=False``. Can also accept a
        Numba JIT function with ``engine='numba'`` specified.

        .. versionchanged:: 1.0.0

    raw : bool, default None
        * ``False`` : passes each row or column as a Series to the
          function.
        * ``True`` : the passed function will receive ndarray
          objects instead.
          If you are just applying a NumPy reduction function this will
          achieve much better performance.
    engine : str, default None
        * ``'cython'`` : Runs rolling apply through C-extensions from cython.
        * ``'numba'`` : Runs rolling apply through JIT compiled code from numba.
          Only available when ``raw`` is set to ``True``.
        * ``None`` : Defaults to ``'cython'`` or globally setting ``compute.use_numba``

          .. versionadded:: 1.0.0

    engine_kwargs : dict, default None
        * For ``'cython'`` engine, there are no accepted ``engine_kwargs``
        * For ``'numba'`` engine, the engine can accept ``nopython``, ``nogil``
          and ``parallel`` dictionary keys. The values must either be ``True`` or
          ``False``. The default ``engine_kwargs`` for the ``'numba'`` engine is
          ``{'nopython': True, 'nogil': False, 'parallel': False}`` and will be
          applied to both the ``func`` and the ``apply`` rolling aggregation.

          .. versionadded:: 1.0.0

    args : tuple, default None
        Positional arguments to be passed into func.
    kwargs : dict, default None
        Keyword arguments to be passed into func.

    Returns
    -------
    Series or DataFrame
        Return type is determined by the caller.

    See Also
    --------
    pandas.Series.%(name)s : Calling object with Series data.
    pandas.DataFrame.%(name)s : Calling object with DataFrame data.
    pandas.Series.apply : Similar method for Series.
    pandas.DataFrame.apply : Similar method for DataFrame.

    Notes
    -----
    See :ref:`stats.rolling_apply` for extended documentation and performance
    considerations for the Numba engine.
    r�FN)r��engine�
engine_kwargsr�rXcCs�|dkrf}|dkri}|jdd�|jdd�t|�s@td��t|�r�|dkrXtd��|df}|tkrrt|}nt||||�}|j}	nR|d
kr�|dk	r�td��|j�}
|jr�t|
�nd	}|j	|||||�}d}	ntd
��|j
||	d	||dk||||d�	S)NZ_levelrDz'raw parameter must be `True` or `False`Fz.raw must be `True` when using the numba enginer��cythonz+cython engine does not accept engine_kwargsrz)engine must be either 'numba' or 'cython'Znumba)rMrDr�r�r�r�r�rX)rN)r�rrFr.r-r8rMr�r@�_generate_cython_apply_funcr�)rWrJr�rrr�rX�	cache_key�
apply_funcrMr=r�r>r>r?r�?sH	
z_Rolling_and_Expanding.applycs>ddlm�t�jd�|||||d��|f���fdd�	}|S)Nr)r�Zroll_generic)r�rXr�r�rJcs"|s�|�jjd�}�||||�S)N)r�)rRr�)rs�beginr�rAr�)r�rWr�r>r?r�szF_Rolling_and_Expanding._generate_cython_apply_func.<locals>.apply_func)r�r�rr�)rWr�rXr�r�rJrr>)r�rWr�r?rxsz2_Rolling_and_Expanding._generate_cython_apply_funccOs@tjd||�|jd�}|jdd�|j|f|jddd�|��S)Nr�Zroll_sumrDr)rMrDr�)rrr�r�r�rM)rWr�rXr�r>r>r?r��s

z_Rolling_and_Expanding.sumz�
    Calculate the %(name)s maximum.

    Parameters
    ----------
    *args, **kwargs
        Arguments and keyword arguments to be passed into func.
    rEcOs2tjd||�|jd�}|j|f|jdd�|��S)NrE�roll_max)rMr�)rrr�r�rM)rWr�rXr�r>r>r?rE�s
z_Rolling_and_Expanding.maxa�
    Calculate the %(name)s minimum.

    Parameters
    ----------
    **kwargs
        Under Review.

    Returns
    -------
    Series or DataFrame
        Returned object type is determined by the caller of the %(name)s
        calculation.

    See Also
    --------
    pandas.Series.%(name)s : Calling object with a Series.
    pandas.DataFrame.%(name)s : Calling object with a DataFrame.
    pandas.Series.min : Similar method for Series.
    pandas.DataFrame.min : Similar method for DataFrame.

    Examples
    --------
    Performing a rolling minimum with a window size of 3.

    >>> s = pd.Series([4, 3, 5, 2, 6])
    >>> s.rolling(3).min()
    0    NaN
    1    NaN
    2    3.0
    3    2.0
    4    2.0
    dtype: float64
    �mincOs2tjd||�|jd�}|j|f|jdd�|��S)Nr�roll_min)rMr�)rrr�r�rM)rWr�rXr�r>r>r?r�s
z_Rolling_and_Expanding.mincOs2tjd||�|jd�}|j|f|jdd�|��S)Nr�Z	roll_mean)rMr�)rrr�r�rM)rWr�rXr�r>r>r?r��s
z_Rolling_and_Expanding.meana.
    Calculate the %(name)s median.

    Parameters
    ----------
    **kwargs
        For compatibility with other %(name)s methods. Has no effect
        on the computed median.

    Returns
    -------
    Series or DataFrame
        Returned type is the same as the original object.

    See Also
    --------
    pandas.Series.%(name)s : Calling object with Series data.
    pandas.DataFrame.%(name)s : Calling object with DataFrames.
    pandas.Series.median : Equivalent method for Series.
    pandas.DataFrame.median : Equivalent method for DataFrame.

    Examples
    --------
    Compute the rolling median of a series with a window size of 3.

    >>> s = pd.Series([0, 1, 2, 3, 4])
    >>> s.rolling(3).median()
    0    NaN
    1    NaN
    2    1.0
    3    2.0
    4    3.0
    dtype: float64
    �mediancKs$|jd�}|j|f|jdd�|��S)NZ
roll_median_cr)rMr�)r�r�rM)rWrXr�r>r>r?r�s
z_Rolling_and_Expanding.medianr:csPtjd||�|jdd�|jd����fdd�}|j|f|jdd�d�|��S)Nr�r��roll_varcst�||||�d��S)N)r	)r3)rsrr�rA)r	r�r>r?�
zsqrt_funcsz._Rolling_and_Expanding.std.<locals>.zsqrt_funcr:)rMr�r�r	)rrr�r�r�rM)rWr	r�rXrr>)r	r�r?r��s
z_Rolling_and_Expanding.stdcOsJtjd||�|jdd�t|jd�|d�}|j|f|jdd|d�|��S)Nr�r�r)r	r:)rMr�r�r	)rrr�rr�r�rM)rWr	r�rXr�r>r>r?r�sz_Rolling_and_Expanding.varz�
    Unbiased %(name)s skewness.

    Parameters
    ----------
    **kwargs
        Keyword arguments to be passed into func.
    �skewcKs2|jd�}|jdd�|j|f|jddd�|��S)NZ	roll_skewr��r)rMr�r�)r�r�r�rM)rWrXr�r>r>r?r(s
z_Rolling_and_Expanding.skewa
    Calculate unbiased %(name)s kurtosis.

    This function uses Fisher's definition of kurtosis without bias.

    Parameters
    ----------
    **kwargs
        Under Review.

    Returns
    -------
    Series or DataFrame
        Returned object type is determined by the caller of the %(name)s
        calculation.

    See Also
    --------
    pandas.Series.%(name)s : Calling object with Series data.
    pandas.DataFrame.%(name)s : Calling object with DataFrames.
    pandas.Series.kurt : Equivalent method for Series.
    pandas.DataFrame.kurt : Equivalent method for DataFrame.
    scipy.stats.skew : Third moment of a probability density.
    scipy.stats.kurtosis : Reference SciPy method.

    Notes
    -----
    A minimum of 4 periods is required for the %(name)s calculation.
    �kurtcKs2|jd�}|jdd�|j|f|jddd�|��S)NZ	roll_kurtr��r!)rMr�r�)r�r�r�rM)rWrXr�r>r>r?r!Ss
z_Rolling_and_Expanding.kurta�
    Calculate the %(name)s quantile.

    Parameters
    ----------
    quantile : float
        Quantile to compute. 0 <= quantile <= 1.
    interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'}
        .. versionadded:: 0.23.0

        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.
    **kwargs
        For compatibility with other %(name)s methods. Has no effect on
        the result.

    Returns
    -------
    Series or DataFrame
        Returned object type is determined by the caller of the %(name)s
        calculation.

    See Also
    --------
    pandas.Series.quantile : Computes value at the given quantile over all data
        in Series.
    pandas.DataFrame.quantile : Computes values at the given quantile over
        requested axis in DataFrame.

    Examples
    --------
    >>> s = pd.Series([1, 2, 3, 4])
    >>> s.rolling(2).quantile(.4, interpolation='lower')
    0    NaN
    1    1.0
    2    2.0
    3    3.0
    dtype: float64

    >>> s.rolling(2).quantile(.4, interpolation='midpoint')
    0    NaN
    1    1.5
    2    2.5
    3    3.5
    dtype: float64
    �quantile�linearcKsl|dkr|jd�}n.|dkr(|jd�}nt|jd�|j�||d�}||d<||d<|j|f|jdd	�|��S)
Ng�?rgrZ
roll_quantile)r�r#�
interpolationr#r%)rMr�)r�rr�r�r�rM)rWr#r%rXr�r>r>r?r#�sz_Rolling_and_Expanding.quantilea�
        Calculate the %(name)s sample covariance.

        Parameters
        ----------
        other : Series, DataFrame, or ndarray, 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.
        **kwargs
            Keyword arguments to be passed into func.
    �covcs~|dkr�j}|dkrdn|}�j|�}t�jt�r<�j�n�jrJ�j�n
�j|������fdd�}t�j|j|t	|�d�S)NTcsn|jd�}|jd�}���fdd�}||j�d�jd�jf��}||�}|||�||�||�|S)Nr�cs|j��j�jd�jf��S)N)rM)�rollingrArMr�)r�)rXrWr=r>r?�<lambda>�sz>_Rolling_and_Expanding.cov.<locals>._get_cov.<locals>.<lambda>r)r=rArM)r�r'rMr)�X�Yr�rZbias_adj)r	rXrWr=r>r?�_get_cov�s

z,_Rolling_and_Expanding.cov.<locals>._get_cov)�pairwise)
r�rvrdr=r4r_rUr�r1r�)rWr�r,r	rXr+r>)r	rXrWr=r?r&�s

z_Rolling_and_Expanding.cova

    Calculate %(name)s correlation.

    Parameters
    ----------
    other : Series, DataFrame, or ndarray, optional
        If not supplied then will default to self.
    pairwise : bool, default None
        Calculate pairwise combinations of columns within a
        DataFrame. If `other` is not specified, defaults to `True`,
        otherwise defaults to `False`.
        Not relevant for :class:`~pandas.Series`.
    **kwargs
        Unused.

    Returns
    -------
    Series or DataFrame
        Returned object type is determined by the caller of the
        %(name)s calculation.

    See Also
    --------
    pandas.Series.%(name)s : Calling object with Series data.
    pandas.DataFrame.%(name)s : Calling object with DataFrames.
    pandas.Series.corr : Equivalent method for Series.
    pandas.DataFrame.corr : Equivalent method for DataFrame.
    cov : Similar method to calculate covariance.
    numpy.corrcoef : NumPy Pearson's correlation calculation.

    Notes
    -----
    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.

    Examples
    --------
    The below example shows a rolling calculation with a window size of
    four matching the equivalent function call using :meth:`numpy.corrcoef`.

    >>> v1 = [3, 3, 3, 5, 8]
    >>> v2 = [3, 4, 4, 4, 8]
    >>> # numpy returns a 2X2 array, the correlation coefficient
    >>> # is the number at entry [0][1]
    >>> print(f"{np.corrcoef(v1[:-1], v2[:-1])[0][1]:.6f}")
    0.333333
    >>> print(f"{np.corrcoef(v1[1:], v2[1:])[0][1]:.6f}")
    0.916949
    >>> s1 = pd.Series(v1)
    >>> s2 = pd.Series(v2)
    >>> s1.rolling(4).corr(s2)
    0         NaN
    1         NaN
    2         NaN
    3    0.333333
    4    0.916949
    dtype: float64

    The below example shows a similar rolling calculation on a
    DataFrame using the pairwise option.

    >>> matrix = np.array([[51., 35.], [49., 30.], [47., 32.],    [46., 31.], [50., 36.]])
    >>> print(np.corrcoef(matrix[:-1,0], matrix[:-1,1]).round(7))
    [[1.         0.6263001]
     [0.6263001  1.       ]]
    >>> print(np.corrcoef(matrix[1:,0], matrix[1:,1]).round(7))
    [[1.         0.5553681]
     [0.5553681  1.        ]]
    >>> df = pd.DataFrame(matrix, columns=['X','Y'])
    >>> df
          X     Y
    0  51.0  35.0
    1  49.0  30.0
    2  47.0  32.0
    3  46.0  31.0
    4  50.0  36.0
    >>> df.rolling(4).corr(pairwise=True)
                X         Y
    0 X       NaN       NaN
      Y       NaN       NaN
    1 X       NaN       NaN
      Y       NaN       NaN
    2 X       NaN       NaN
      Y       NaN       NaN
    3 X  1.000000  0.626300
      Y  0.626300  1.000000
    4 X  1.000000  0.555368
      Y  0.555368  1.000000
    �corrcsz|dkr�j}|dkrdn|}�j|�}t�jt�r<�j�n�jsL�j|�n�j����fdd�}t�j|j|t	|�d�S)NTcsN|j��j�jd�}|j��j�jd�}|j|f��|jf��|jf��S)N)r=rArM)r'rArMr&r�)�ar�)rXrWr=r>r?�	_get_corrds
z._Rolling_and_Expanding.corr.<locals>._get_corr)r,)
r�rvrdr=r4r_r�rUr1r�)rWr�r,rXr/r>)rXrWr=r?r-Us

z_Rolling_and_Expanding.corr)FNNNN)r:)r:)r$)NNr:)NN)rlr�r�rr2rr�rr�rr
r�rr�rErr�rr�r�rr!r#r&r-r>r>r>r?r�sJ%
;
(2
"
"



5

(
'k
rcs�eZdZeed�dd��Zeed�dd��Z�fdd�Zdd	�Z	d
d�Z
ed�Zed
�Z
eedee
dddd��fdd��ZeZedd�eed��fdd���Zedd�eed�dG�fdd�	��Zedd�eed��fdd ���Zedd!d"�ee�eed!��fd#d$����Zedd�eed%��fd&d'���Zedd�eed(��fd)d*���Zedd�eed+��fd,d-���Zeddd.�eed/�dH�fd1d2�	��Zeddd.�eed3�dI�fd4d5�	��Zedd6d"�ee�eed6��fd7d8����Zed9�Zee�edd�eed:��fd;d<����Z edd�eed=�dJ�fd?d@�	��Z!eddAd"�ee�eedA�dK�fdBdC�	���Z"edd�eedD�dL�fdEdF�	��Z#�Z$S)Mr)r9cCst|jtttf�S)N)rdr]r!r$r")rWr>r>r?r\tszRolling.is_datetimelikecCsx|jdkr&|jdkr|jjS|jjSnNt|jt�r8|jSt|jt�rb|j|jjkrbt|j|j�Std|j�d���dS)Nrzinvalid on specified as z3, must be a column (of DataFrame), an Index or None)	rPrOrRr�rnrdr*r rF)rWr>r>r?r]zs


zRolling._oncs�t�j�|jjs|jrpt|jttt	f�rp|j
�|j�}|jrHt
d��|j|_|j|_d|_|jdkr�d|_n6t|jt�r�dSt|j�s�td��n|jdkr�td��|jr�|jdk	r�td��dS)NzCcenter is not implemented for datetimelike and offset based windowsr^r:zwindow must be an integerrzwindow must be non-negativezAclosed only implemented for datetimelike and offset based windows)r�rVrR�emptyr\rdr=r�r
r�_validate_monotonic�_validate_freqrMr�rUZnanosrNrAr4rrFrQ)rWr^)r�r>r?rV�s,




zRolling.validatecCs6|jjp|jjs2|j}|jdkr$d}t|�d���dS)z@
        Validate monotonic (increasing or decreasing).
        Nr�z must be monotonic)r]Zis_monotonic_increasingZis_monotonic_decreasingrPrF)rW�	formattedr>r>r?r1�s

zRolling._validate_monotoniccCsJy
t|j�Sttfk
rD}ztd|j�d��|�WYdd}~XnXdS)z5
        Validate & return window frequency.
        zpassed window z, is not compatible with a datetimelike indexN)rr=rerF)rWr�r>r>r?r2�s
zRolling._validate_freqz�
    See Also
    --------
    pandas.Series.rolling : Calling object with Series data.
    pandas.DataFrame.rolling : Calling object with DataFrame data.
    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.rolling(2).sum()
         A     B     C
    0  NaN   NaN   NaN
    1  3.0   9.0  15.0
    2  5.0  11.0  17.0

    >>> df.rolling(2).agg({"A": "sum", "B": "min"})
         A    B
    0  NaN  NaN
    1  3.0  4.0
    2  5.0  5.0
    r�rzSeries/Dataframe)rrrrrOcst�j|f|�|�S)N)r�r�)rWrJr�rX)r�r>r?r��s	zRolling.aggregater')r�rcs8|jst|jt�r.|jd�}|j||jdd�St�j�S)NZ
roll_countr)rMr�)	r_rdr=r4r�r�rMr�r)rWr�)r�r>r?r�s
z
Rolling.countr�FNcst�j||||||d�S)N)r�rrr�rX)r�r�)rWrJr�rrr�rX)r�r>r?r�sz
Rolling.applyr�cstjd||�t�j||�S)Nr�)r�validate_rolling_funcr�r�)rWr�rX)r�r>r?r�szRolling.sumrE)r�r�cstjd||�t�j||�S)NrE)rr4r�rE)rWr�rX)r�r>r?rEszRolling.maxrcstjd||�t�j||�S)Nr)rr4r�r)rWr�rX)r�r>r?r!szRolling.minr�cstjd||�t�j||�S)Nr�)rr4r�r�)rWr�rX)r�r>r?r�'szRolling.meanrcst�jf|�S)N)r�r)rWrX)r�r>r?r-szRolling.median)r�rr�r:cs$tjd||�t�jfd|i|��S)Nr�r	)rr4r�r�)rWr	r�rX)r�r>r?r�2szRolling.stdr�cs$tjd||�t�jfd|i|��S)Nr�r	)rr4r�r�)rWr	r�rX)r�r>r?r�8szRolling.varrcst�jf|�S)N)r�r)rWrX)r�r>r?r>szRolling.skewa0
    Examples
    --------

    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[1:], bias=False):.6f}")
    3.999946
    >>> s = pd.Series(arr)
    >>> s.rolling(4).kurt()
    0         NaN
    1         NaN
    2         NaN
    3   -1.200000
    4    3.999946
    dtype: float64
    r!cst�jf|�S)N)r�r!)rWrX)r�r>r?r!]szRolling.kurtr#r$cst�jf||d�|��S)N)r#r%)r�r#)rWr#r%rX)r�r>r?r#cszRolling.quantiler&cst�jf|||d�|��S)N)r�r,r	)r�r&)rWr�r,r	rX)r�r>r?r&jszRolling.covr-cst�jf||d�|��S)N)r�r,)r�r-)rWr�r,rX)r�r>r?r-pszRolling.corr)FNNNN)r:)r:)r$)NNr:)NN)%rlr�r�rr�r\r*r]rVr1r2rrrrr2r�r�rrrr�r�r0rErr�rr�r�rZ_agg_docr!r#r&r-r
r>r>)r�r?rssv(











rc	s�eZdZdZdeeeeeeeed�dd�Z	e
d	d
��Zed��fdd
�Z
eed�dd�Zeed�dd�Zd�fdd�	Zdd�Z�ZS)�RollingGroupbyz3
    Provide a rolling groupby implementation.
    rr:FN)rJrMr�rDr�r�r�c	s<tj�|||||||f|�}	dd��jjjD�}
d}�fdd�|
D�}t|�t|
�krp�jj}|j�}
|
|
7}
n|	j	|dd�}	�jjj
}�jjj}�jjjj
�}|r�tjt|���ntjgtjd���fdd�|D�}|dk	�r"|j��}t|t��stj|g�}|jt|j
��|jt|j��t|||
dd	�}||	_|	S)
NcSsg|]
}|j�qSr>)r�)r��groupingr>r>r?r��sz)RollingGroupby._apply.<locals>.<listcomp>cs&g|]}|�jjjks|dkr|�qS)N)rRr��names)r�ry)rWr>r?r��sr�)rn�errors)r�csg|]}|j���qSr>)r�)r�r�)r�r>r?r��sF)r7Zverify_integrity)rr��_groupby�grouperZ
_groupingsr;rRr�r7Zdrop�codes�levels�indicesrsr�r�r�r�Zintpr�rdr+Zfrom_arraysr�)rWrJrMr�rDr�r�r�rXr�Zresult_index_namesZgrouped_object_indexZcolumn_keysZgrouped_index_namer;r<Z
group_indices�idxZresult_indexr>)r�rWr?r�~sH





zRollingGroupby._applycCstS)N)r)rWr>r>r?r[�szRollingGroupby._constructor)rRcs<|js0tjt|jjjj���jtj	�}|j
|�}t�j|�S)zA
        Split data into blocks & return conformed data.
        )
r0r�r�r�r9r:r=rsr�Zint64r�r�ru)rWrRZ
groupby_order)r�r>r?ru�s
zRollingGroupby._create_blocks)rJr9cCs|j|�d��S)z�
        Return the cython function type.

        RollingGroupby needs to always use "variable" algorithms since processing
        the data in group order may not be monotonic with the data which
        "fixed" algorithms assume
        r�)r�)rWrJr>r>r?r��sz$RollingGroupby._get_cython_func_type)r=r9cCsfd}|jj}t|jt�r8t|j�}|jj}|jdd�n|jrDt	}nt
}d}t|||jj
||d�}|S)a
        Return an indexer class that will compute the window start and end bounds

        Parameters
        ----------
        window : int
            window size for FixedWindowIndexer

        Returns
        -------
        GroupbyRollingIndexer
        Nr�)r�r�Zgroupby_indicies�rolling_indexer�indexer_kwargs)r]r�rdr=r4rfrSr�r_r7r5r6r9r=)rWr=r@r�r?r�r>r>r?r��s"
z"RollingGroupby._get_window_indexercs2|jdk	r |jj|j�|_d|_t�j|||d�S)N)rz)rPrRZ	set_indexr]r�r{)rWryrprz)r�r>r?r{	s
zRollingGroupby._gotitemcCsdS)z�
        Validate that on is monotonic;
        we don't care for groupby.rolling
        because we have already validated at a higher
        level.
        Nr>)rWr>r>r?r1
	sz"RollingGroupby._validate_monotonic)rr:FNF)N)rlr�r�r
rr�r<rr�r�r�r[rrur�r6r�r{r1r
r>r>)r�r?r5ys ?
#	r5)ar
�datetimer�	functoolsrrh�textwraprZtypingrrrrr	r
rrZnumpyr�Zpandas._libs.tslibsr
rZ pandas._libs.window.aggregationsZ_libsr=Zaggregationsr�Zpandas._typingrrrZpandas.compat._optionalrZpandas.compat.numpyrrZpandas.util._decoratorsrrrrZpandas.core.dtypes.commonrrrrrrrrZpandas.core.dtypes.genericr r!r"r#r$Zpandas.core.baser%r&r'r(Zpandas.core.common�core�commonrZpandas.core.constructionr)Zpandas.core.indexes.apir*r+r,Zpandas.core.util.numba_r-r.Zpandas.core.window.commonr/r0r1r2r3Zpandas.core.window.indexersr4r5r6r7Zpandas.core.window.numba_r8r<r@rGrKrLrZrrrr5r>r>r>r?�<module>sf((
Ti6