U
    +if_Q                    @  s  d Z ddlmZ ddlZddlmZ ddlmZ ddlZddl	m
Z
 ddlmZmZmZmZ ddlZddlZddlmZmZ ddlm  m  mZ dd	lmZmZmZmZ dd
l m!Z! ddl"m#Z$ ddl%m&Z& ddl'm(Z( ddl)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/ ddl0m1Z1m2Z2 ddl3m4Z4 ddl5m6Z6 ddl7m8Z8 ddl9m:Z: ddl;m<Z< ddl=m>Z>m?Z? ddl@mA  mBZC ddlDmEZEmFZFmGZGmHZH ddlImJZJmKZKmLZLmMZMmNZN ddlOmPZP ddlQmRZRmSZS ddlTmUZUmVZV ddlWmXZXmYZYmZZZm[Z[m\Z\m]Z]m^Z^m_Z_m`Z`maZambZb ddlcmdZdmeZemfZf erLddlgmhZhmiZi ddljmkZk ddllmmZm dd lnmoZo G d!d" d"e?ZpG d#d$ d$epZqG d%d& d&epZrG d'd( d(epZsG d)d* d*esZterj et_ G d+d, d,eqetZudS )-zc
Provide a generic structure to support window functions,
similar to how we have a Groupby object.
    )annotationsN)	timedelta)partial)dedent)TYPE_CHECKINGAnyCallableHashable)
BaseOffset	to_offset)	ArrayLikeAxisNDFrameTWindowingRankType)import_optional_dependency)function)doc)find_stack_level)ensure_float64is_bool
is_integeris_list_like	is_scalarneeds_i8_conversion)ABCDataFrame	ABCSeries)notna)executor)	factorize)ResamplerWindowApply)ExtensionArray)	DataErrorSelectionMixin)BaseIndexerFixedWindowIndexerGroupbyIndexerVariableWindowIndexer)DatetimeIndexIndex
MultiIndexPeriodIndexTimedeltaIndex)concat)NUMBA_FUNC_CACHEmaybe_use_numba)flex_binary_momentzsqrt)_shared_docsargs_compatcreate_section_headerkwargs_compatkwargs_scipynumba_notestemplate_headertemplate_returnstemplate_see_alsowindow_agg_numba_parameterswindow_apply_parameters)'generate_manual_numpy_nan_agg_with_axisgenerate_numba_apply_funcgenerate_numba_table_func)	DataFrameSeries)NDFrameBaseGrouper)Blockc                   @  s  e Zd ZU dZg Zded< e Zded< ded< dbdddddddddddddZe	dd Z
e	ddddZddddZdddd Zd!d!d"dd#d$d%Zd&d&d'd(d)Zdcd*d+Zdd,d-d.Zd/d0 Zddd1d2Zd3d4 Zd5d!d6d7d8Zd9d9dd:d;d<Ze	d=d> Zd9d9d9d?d@dAZdBddCdDZdddEddFdGdHdIZdedEddJdGdKdLZdfdEddJdGdMdNZdJdOdPdQdJdRdSdTZdgdVddWdXdYdZd[ZdhdVdd\d]d^d_Zd`da Z e Z!dS )i
BaseWindowz7Provides utilities for performing windowing operations.	list[str]_attributeszfrozenset[Hashable]
exclusionsr(   _onNFr   single)	selectionrA   z
int | Nonebool
str | Noner   zstr | Index | Nonestr)objmin_periodscenterwin_typeaxisonclosedmethodc
                C  s   || _ || _|| _|| _|| _|| _|| _|d k	r<||nd | _|	| _	d | _
| jd krz| jdkrn| j j| _q| j j| _nVt| jtr| j| _n@t| j tr| j| j jkrt| j | j | _ntd| j d|
| _|   d S )Nr   zinvalid on specified as z3, must be a column (of DataFrame), an Index or None)rO   rT   rU   windowrP   rQ   	_win_typeZ_get_axis_numberrS   rV   _win_freq_i8indexrI   columns
isinstancer(   r   
ValueErrorZ
_selection	_validate)selfrO   rW   rP   rQ   rR   rS   rT   rU   rV   rK    r`   M/home/mars/bis/venv/lib/python3.8/site-packages/pandas/core/window/rolling.py__init__w   s.    


zBaseWindow.__init__c                 C  s&   | j d k	r tjdtt d dS | jS )Nzawin_type will no longer return 'freq' in a future version. Check the type of self.window instead.
stacklevelfreq)rY   warningswarnFutureWarningr   rX   r_   r`   r`   ra   rR      s    
zBaseWindow.win_typereturnc                 C  s   t jdtt d | jd k	S )NzFis_datetimelike is deprecated and will be removed in a future version.rc   )rf   rg   rh   r   rY   ri   r`   r`   ra   is_datetimelike   s    zBaseWindow.is_datetimelikeNonec                 C  s   t jdtt d |  S )Nz?validate is deprecated and will be removed in a future version.rc   )rf   rg   rh   r   r^   ri   r`   r`   ra   validate   s    zBaseWindow.validatec                 C  s(  | j d k	rt| j std| jd k	r|t| js:tdnB| jdk rNtdn.t| jr|| j| jkr|td| j d| j | jd k	r| jdkrtdt| jt	t
fstd	t|  t| jtrt| jjj }tt jj }||krtt| jj d
| jdkr$tdd S )Nzcenter must be a booleanzmin_periods must be an integerr   zmin_periods must be >= 0zmin_periods z must be <= window )rightZbothleftZneitherz3closed must be 'right', 'left', 'both' or 'neither'zinvalid type: z? does not implement the correct signature for get_window_bounds)tablerJ   z!method must be 'table' or 'single)rQ   r   r]   rP   r   rW   rU   r\   rO   r   r   	TypeErrortyper#   inspect	signatureget_window_bounds
parameterskeys__name__rV   )r_   Zget_window_bounds_signatureZexpected_signaturer`   r`   ra   r^      s8    







zBaseWindow._validate
np.ndarrayint)startendnum_valsrk   c                 C  sZ   t |t |kr0tdt | dt | dn&t ||krVtdt | d| dd S )Nzstart (z) and end (z ) bounds must be the same lengthzstart and end bounds (z)) must be the same length as the object ())lenr]   )r_   r|   r}   r~   r`   r`   ra   _check_window_bounds   s    zBaseWindow._check_window_boundsr   rO   rk   c                 C  st   | j dk	r:t| j ts:|jdkr:|j|j| j gdd}| jdkrp|jdgdgd}|j	d	dd
}|j
 |_
|S )A
        Split data into blocks & return conformed data.
        N   F)r[   copy   numberr   )includeexcludefloat64)r   )rT   r\   r(   ndimreindexr[   
differencerS   Zselect_dtypesastype_mgrconsolidate)r_   rO   r`   r`   ra   _create_data   s     
zBaseWindow._create_datac              	     s   |dkr j }t ( tddt  fdd jD }W 5 Q R X d}|jdkrnt|rb||ksjt|rn|}t	 |fd|i|}|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
        NignorerR   c                   s   i | ]}|t  |qS r`   getattr).0attrri   r`   ra   
<dictcomp>  s      z'BaseWindow._gotitem.<locals>.<dictcomp>r   rK   )
rO   rf   catch_warningsfilterwarningsrh   rG   r   r   r   rs   )r_   keyr   subsetkwargsrK   Znew_winr`   ri   ra   _gotitem  s     

zBaseWindow._gotitem)r   c                 C  sH   || j krt| |S || jkr(| | S tdt| j d| dd S )N'z' object has no attribute ')Z_internal_names_setobject__getattribute__rO   AttributeErrorrs   ry   )r_   r   r`   r`   ra   __getattr__$  s    

zBaseWindow.__getattr__c                 C  s
   | j  S N)rO   _dir_additionsri   r`   r`   ra   r   .  s    zBaseWindow._dir_additionsc                   s4    fdd j D }d|}t j d| dS )z@
        Provide a nice str repr of our rolling object.
        c                 3  s>   | ]6}t  |d d k	r|d dkr| dt  | V  qd S )Nr   _=r   )r   	attr_nameri   r`   ra   	<genexpr>5  s    z&BaseWindow.__repr__.<locals>.<genexpr>,z [])rG   joinrs   ry   )r_   Z
attrs_listattrsr`   ri   ra   __repr__1  s
    

zBaseWindow.__repr__c                 c  s   | j | j}| |}|  }|jt|| j| j| j	d\}}| 
||t| t||D ]\}}|jt|| }|V  q\d S NZ
num_valuesrP   rQ   rU   )_selected_objZset_axisrI   r   _get_window_indexerrv   r   rP   rQ   rU   r   zipZilocslice)r_   rO   indexerr|   r}   seresultr`   r`   ra   __iter__=  s    

zBaseWindow.__iter__r   valuesrk   c              
   C  s   t |jr*tdt| j d|j dndz*t|trJ|jtj	tj
d}nt|}W n8 ttfk
r } ztd|j |W 5 d}~X Y nX t|}| rt|tj
|}|S )z1Convert input to numpy arrays for Cython routineszops for z for this dtype z are not implemented)Zna_valuezcannot handle this type -> N)r   dtypeNotImplementedErrorrs   ry   r\   r    to_numpynpr   nanr   r]   rr   isinfanywhere)r_   r   errinfr`   r`   ra   _prep_valuesN  s    

$
zBaseWindow._prep_valuesr?   )r   rO   rk   c                 C  s   ddl m} | jd k	r| j|js| jj}|| j| jj|d}||jkrT|||< nd||jj	krbnV|| j
jkr| j
j}|j}||}||d | }	t|	}
||
|| n|||< d S )Nr   r@   rZ   name)pandasr@   rT   rI   equalsrZ   r   rO   r[   namesr   Zget_locintersectionr   insert)r_   r   rO   r@   r   Z	extra_colZold_colsZnew_colsZold_locoverlapnew_locr`   r`   ra   _insert_on_columng  s     


zBaseWindow._insert_on_columnc                 C  s   t | jjr| jjS d S r   )r   rI   r   Zasi8ri   r`   r`   ra   _index_array  s    zBaseWindow._index_array)outrO   rk   c                 C  sN   |j d dkr&|j d dkr&tdn|j d dkr>|dS | || |S )zValidate and finalize result.r   r   No numeric types to aggregater   )shaper!   r   r   )r_   r   rO   r`   r`   ra   _resolve_output  s    

zBaseWindow._resolve_outputr#   c                 C  s<   t | jtr| jS | jdk	r0t| j| j| jdS t| jdS )z[
        Return an indexer class that will compute the window start and end bounds
        N)index_arraywindow_sizerQ   )r   )r\   rW   r#   rY   r&   r   rQ   r$   ri   r`   r`   ra   r     s    
zBaseWindow._get_window_indexerzCallable[..., ArrayLike]r@   )homogeneous_funcr   rk   c              
   C  s   |  | j}|dkr"t|t}z| |j}W n0 ttfk
rb } zt	d|W 5 d}~X Y nX ||}|j
||j|jdS )z4
        Series version of _apply_blockwise
        countr   Nr   )r   r   r   r   r{   r   Z_valuesrr   r   r!   _constructorrZ   r   )r_   r   r   rO   r   r   r   r`   r`   ra   _apply_series  s    zBaseWindow._apply_seriesDataFrame | Seriesc              
     sR  j jdkr |S j }|dkrFt|t}|j |_ddd fdd}j	dkrl|j
}g }g }t| D ]B\}}z||}	W n ttfk
r   Y qX ||	 || qt|j||j|j|dd}
j	dkr|
j
}
d	t|  krt|jkrFn n,|j|j|}tjd
| tt d |
|S )zl
        Apply the given function to the DataFrame broken down into homogeneous
        sub-frames.
        r   r   r   r   c                   s    | }  | S r   )r   r   r   r_   r`   ra   hfunc  s    
z*BaseWindow._apply_blockwise.<locals>.hfuncF)rZ   r[   verify_integrityr   zDropping of nuisance columns in rolling operations is deprecated; in a future version this will raise TypeError. Select only valid columns before calling the operation. Dropped columns were rc   )r   r   r   r   r   r   r{   r   r   rS   T	enumerateZ_iter_column_arraysrr   r   appendrs   Z_from_arraysrZ   r[   taker   r   rf   rg   rh   r   r   )r_   r   r   rO   r   ZtakerZ
res_valuesiZarrresZdfZdroppedr`   r   ra   _apply_blockwise  sD    



&	zBaseWindow._apply_blockwisec                 C  s~   | j jdkrtd| | j }| | }| jdkr>|jn|}||}| jdkrZ|jn|}|j||j	|j
d}| ||S )zT
        Apply the given function to the DataFrame across the entire object
        r   z1method='table' not applicable for Series objects.rZ   r[   )r   r   r]   r   r   r   rS   r   r   rZ   r[   r   )r_   r   r   rO   r   r   r   r`   r`   ra   _apply_tablewise  s    zBaseWindow._apply_tablewiseDataFrame | Series | Nonebool | NoneFCallable[[DataFrame | Series, DataFrame | Series], DataFrame | Series]targetotherpairwisefuncrk   c                 C  sH   |dkr|}|dkrdn|}nt |ttfs4tdt|||t|dS )]
        Apply the given pairwise function given 2 pandas objects (DataFrame/Series)
        NTz#other must be a DataFrame or Series)r   )r\   r   r   r]   r/   rL   )r_   r   r   r   r   r`   r`   ra   _apply_pairwise  s    
zBaseWindow._apply_pairwiser`   Callable[..., Any]tuple[Callable, str] | Nonetuple[Any, ...]r   r   numba_cache_key
numba_argsc                   s`     jdk	rjnjdd fdd}jdkrP||S ||S d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
        name : str,
        numba_cache_key : tuple
            caching key to be used to store a compiled numba func
        numba_args : tuple
            args to be passed when func is a numba func
        **kwargs
            additional arguments for rolling function and window function

        Returns
        -------
        y : type of input
        Nrz   r   c              	     sZ   | j dkr|  S  fdd}tjdd || }W 5 Q R X d k	rV t< |S )Nr   c                   sD   j t| jjd\}}||t|   | ||f S r   )rv   r   rQ   rU   r   )xr|   r}   )r   rP   r   r_   window_indexerr`   ra   calc:  s    
z9BaseWindow._apply.<locals>.homogeneous_func.<locals>.calcr   all)sizer   r   errstater-   r   r   r   r   rP   r   r   r_   r   r`   ra   r   4  s    
z+BaseWindow._apply.<locals>.homogeneous_funcrJ   )r   rP   r   rV   r   r   r_   r   r   r   r   r   r   r`   r  ra   _apply  s    
zBaseWindow._applydict[str, bool] | None)r   numba_cache_key_strengine_kwargsc                 G  s  |   }| jd k	r| jn|j}| | j}| jdkr:|j}| | }|j	dkr^|
dd}|jt||| j| jd\}	}
| |	|
t| t|||}|||	|
|f| }|t||f< | jdkr|jn|}|j	dkr| }|j||j|jd}|S |j||j|jd}| ||S d S )Nr   r   r   r   )r   rP   r   r   r   rS   r   r   r   r   Zreshaperv   r   rQ   rU   r   r   Zgenerate_shared_aggregatorr-   Zsqueezer   rZ   r   r[   r   )r_   r   r  r  Z	func_argsr   rP   rO   r   r|   r}   Z
aggregatorr   r   r`   r`   ra   _numba_applyR  s@    


  
zBaseWindow._numba_applyc                 O  s2   t | |||d }|d kr.| j|d||dS |S )Nargsr   F)rawr  r   )r   aggapplyr_   r   r  r   r   r`   r`   ra   	aggregatez  s    zBaseWindow.aggregate)NNFNr   NNrJ   )N)N)N)N)NNr`   )N)"ry   
__module____qualname____doc__rG   __annotations__	frozensetrH   rb   propertyrR   rl   rn   r^   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r	  r  r  r`   r`   r`   ra   rE   p   sb   
         ,
&
 


  <    E (rE   c                      s   e Zd ZU dZded< ded< dgZded< dd	d
ddd fddZd#ddddd
d fddZd
dddd
d fddZddd fdd Z	d$ fd!d"	Z
  ZS )%BaseWindowGroupbyz3
    Provide the groupby windowing facilities.
    rC   _grouperrL   	_as_indexrF   rG   T)r  r   )rO   r  r  c                  sT   ddl m} t||std|| _|| _|j| jjdd}t j	|f|| d S )Nr   rB   zMust pass a BaseGrouper object.r   r[   errors)
pandas.core.groupby.opsrC   r\   r]   r  r  dropr   superrb   )r_   rO   r  r  r  r   rC   	__class__r`   ra   rb     s    
zBaseWindowGroupby.__init__Nr`   r   rM   r   r   )r   r   r   r   rk   c                   sL  t  j||||f|}jj}|j}tjj}	|	| }
fddjjD }t|t|	krp|j|dd}jj	}tjj
}jj }|rtt| ntjg tjd  fdd|D }|d k	r| }t|tst|g}|t|j	 |t|j
 t|||
dd}||_jsH|jttt|	d	}|S )
Nc                   s&   g | ]}| j jjks|d kr|qS r   )rO   rZ   r   )r   r   ri   r`   ra   
<listcomp>  s    z,BaseWindowGroupby._apply.<locals>.<listcomp>r   r  r   c                   s   g | ]}|  qS r`   )r   r   c)r   r`   ra   r!    s     Fr   r   )level)r  r  rO   rZ   r   r   r  r   r  codeslevelsindicesr   r   concatenatelistarrayintpr   r\   r)   Zfrom_arraysextendr  Zreset_indexrange)r_   r   r   r   r   r   r   Zgrouped_object_indexZgrouped_index_nameZgroupby_keysZresult_index_namesZdrop_columnsr'  r(  group_indicesidxresult_indexr  )r   r_   ra   r    sP    




   zBaseWindowGroupby._applyr   r   r   r   c                   s  |j | jjdd}| |}t |||dk	rtfdd| jj D st	}t
fdd| jj D dd | jj D }g }g }ttt| D ]6}	tt|	|}
t|
\}}|| || qnr| jj}| jj}| jj }|rtt| ntjg tjd	 |jd
kr4d
n
t	|j fdd|D }tjtrtjj}tjj}tjj}n$tj\}}|g}|g}jjg}|| }|| }| jj| }t|||dd}|_S )r   r   r  Nc                 3  s   | ]}t |t  kV  qd S r   )r   )r   group)r   r`   ra   r     s    z4BaseWindowGroupby._apply_pairwise.<locals>.<genexpr>c                   s   g | ]}  | jqS r`   )r   r   rZ   )r   Z
gb_indices)r   r`   ra   r!    s   z5BaseWindowGroupby._apply_pairwise.<locals>.<listcomp>c                 s  s   | ]}t |V  qd S r   )comZmaybe_make_list)r   pairr`   r`   ra   r     s    r"  r   c                   s   g | ]}t | qS r`   )r   repeatr   r#  )r   	repeat_byr`   ra   r!    s    Fr%  )r  r  r   r   r  r   r   r)  r   r   r,   rx   mapr+  r   r   r6  r,  r   r   r'  r(  r*  r-  r   r[   r\   rZ   r)   r   )r_   r   r   r   r   Zold_result_lenZgb_pairsZgroupby_codesZgroupby_levelsZgb_level_pairlabelsr'  r(  r0  Zresult_codesZresult_levelsZresult_namesZ	idx_codesZ
idx_levelsr2  r  )r   r   r7  r   ra   r     sj    







   z!BaseWindowGroupby._apply_pairwiser   r   c                   s:   |j s.tt| jj tj}|	|}t
 |S )r   )emptyr   r*  r+  r  r)  r   r   Zint64r   r  r   )r_   rO   Zgroupby_orderr  r`   ra   r   1  s    
zBaseWindowGroupby._create_datac                   s*   | j d k	r| j| j}t j|||dS )N)r   )rT   rO   Z	set_indexrI   r  r   )r_   r   r   r   r  r`   ra   r   ?  s    
zBaseWindowGroupby._gotitem)NNr`   )N)ry   r  r  r  r  rG   rb   r  r   r   r   __classcell__r`   r`   r  ra   r    s   
   =Tr  c                      sz  e Zd ZdZdddddddd	gZ fd
dZddddddZd;dddddddZee	d e
de
ddddd d! ZeZeeed"eed#eed$edd% d&d'd(d)
d*d+ Zeeed"eed#eed$edd% d&d,d-d)
d.d/ Zeed0ed"eed#eed$edd% d&d1d2d)d<dd4d5d6Zeed0ed"eed#eed$edd% d&d7d8d)d=dd4d9d:Z  ZS )>Windowa  
    Provide rolling window calculations.

    Parameters
    ----------
    window : int, offset, or BaseIndexer subclass
        Size of the moving window.

        If an integer, the fixed number of observations used for
        each window.

        If an offset, 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.
        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>`__.

        If a BaseIndexer subclass, 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 ``np.nan``.

        For a window that is specified by an offset, ``min_periods`` will default to 1.

        For a window that is specified by an integer, ``min_periods`` will default
        to the size of the window.

    center : bool, default False
        If False, set the window labels as the right edge of the window index.

        If True, set the window labels as the center of the window index.

    win_type : str, default None
        If ``None``, all points are evenly weighted.

        If a string, it must be a valid `scipy.signal window function
        <https://docs.scipy.org/doc/scipy/reference/signal.windows.html#module-scipy.signal.windows>`__.

        Certain Scipy window types require additional parameters to be passed
        in the aggregation function. The additional parameters must match
        the keywords specified in the Scipy window type method signature.

    on : str, optional
        For a DataFrame, a column label or Index 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
        If ``0`` or ``'index'``, roll across the rows.

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

    closed : str, default None
        If ``'right'``, the first point in the window is excluded from calculations.

        If ``'left'``, the last point in the window is excluded from calculations.

        If ``'both'``, the no points in the window are excluded from calculations.

        If ``'neither'``, the first and last points in the window are excluded
        from calculations.

        Default ``None`` (``'right'``).

        .. versionchanged:: 1.2.0

            The closed parameter with fixed windows is now supported.

    method : str {'single', 'table'}, default 'single'

        .. versionadded:: 1.3.0

        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.

    Returns
    -------
    ``Window`` subclass if a ``win_type`` is passed

    ``Rolling`` subclass if ``win_type`` is not passed

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

    Notes
    -----
    See :ref:`Windowing Operations <window.generic>` 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

    **window**

    Rolling sum with a window length of 2 observations.

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

    Rolling sum with a window span of 2 seconds.

    >>> df_time = 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_time
                           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

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

    Rolling sum with forward looking windows with 2 observations.

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

    **min_periods**

    Rolling sum with a window length of 2 observations, but only needs a minimum of 1
    observation to calculate a value.

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

    **center**

    Rolling sum with the result assigned to the center of the window index.

    >>> df.rolling(3, min_periods=1, center=True).sum()
         B
    0  1.0
    1  3.0
    2  3.0
    3  6.0
    4  4.0

    >>> df.rolling(3, min_periods=1, center=False).sum()
         B
    0  0.0
    1  1.0
    2  3.0
    3  3.0
    4  6.0

    **win_type**

    Rolling sum with a window length of 2, using the Scipy ``'gaussian'``
    window type. ``std`` is required in the aggregation function.

    >>> df.rolling(2, win_type='gaussian').sum(std=3)
              B
    0       NaN
    1  0.986207
    2  2.958621
    3       NaN
    4       NaN
    rW   rP   rQ   rR   rS   rT   rU   rV   c                   s   t    t| jts&td| j tddd}t|| jd | _| jd kr\td| j t| j	t
rrtdnt| j	r| j	dk rtd| jdkrtd	d S )
NzInvalid win_type zscipy.signalz,Scipy is required to generate window weight.)extraz6BaseIndexer subclasses not implemented with win_types.r   &window must be an integer 0 or greaterrJ   z+'single' is the only supported method type.)r  r^   r\   rR   rN   r]   r   r   _scipy_weight_generatorrW   r#   r   r   rV   )r_   signalr  r`   ra   r^   #  s$    
 

zWindow._validaterz   r{   )r   offsetrk   c                 C  sV   | j |jd krtd|dkrRtdg|j }t|d|| j < t|t| }|S )zT
        Center the result in the window for weighted rolling aggregations.
        r   z8Requested axis is larger then no. of argument dimensionsr   N)rS   r   r]   r   r   r   tuple)r_   r   rA  Zlead_indexerr`   r`   ra   _center_window9  s    zWindow._center_windowNr`   z,Callable[[np.ndarray, int, int], np.ndarray]rM   r   r   r   c                   sN   j jf|jr&td d nddd fdd}||S )a  
        Rolling with weights statistical measure using supplied function.

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

        Parameters
        ----------
        func : callable function to apply
        name : str,
        use_numba_cache : tuple
            unused
        numba_args : tuple
            unused
        **kwargs
            additional arguments for scipy windows if necessary

        Returns
        -------
        y : type of input
        r   r   r   rz   r   c              	     s`   | j dkr|  S  fdd}tjdd t|| }W 5 Q R X jr\|}|S )Nr   c                   s6   t t jg }t | |f}  | jp2tS r   )r   r,  r   r*  rP   r   )r   Zadditional_nansr   rA  r_   rW   r`   ra   r   n  s    z5Window._apply.<locals>.homogeneous_func.<locals>.calcr   r   )r   r   r   r   ZasarrayrQ   rC  r  rD  r`   ra   r   h  s    
z'Window._apply.<locals>.homogeneous_func)r?  rW   rQ   r   r   r  r`   rD  ra   r  F  s    zWindow._applyr  z
        See Also
        --------
        pandas.DataFrame.aggregate : Similar DataFrame method.
        pandas.Series.aggregate : Similar Series method.
        at  
        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
        zSeries/DataFrame Zsee_alsoZexamplesklassrS   c                 O  s(   t | |||d }|d kr$|| }|S )Nr
  )r   r  r  r`   r`   ra   r  ~  s     zWindow.aggregate
ParametersReturnsSee Alsor  rollingzweighted window sumsumZwindow_methodZaggregation_descriptionZ
agg_methodc                 O  s*   t d|| tj}| j|fddi|S )NrL  r   )nvvalidate_window_funcwindow_aggregationsZroll_weighted_sumr  r_   r  r   window_funcr`   r`   ra   rL    s    z
Window.sumzweighted window meanmeanc                 O  s*   t d|| tj}| j|fddi|S )NrS  r   )rN  rO  rP  Zroll_weighted_meanr  rQ  r`   r`   ra   rS    s    zWindow.meanz.. versionadded:: 1.0.0 

zweighted window variancevarr   ddofc                 O  s>   t d|| ttj|d}|dd  | j|fddi|S )NrT  rU  r   )rN  rO  r   rP  Zroll_weighted_varpopr  )r_   rV  r  r   rR  r`   r`   ra   rT    s    z
Window.varz"weighted window standard deviationstdc                 O  s(   t d|| t| jf |dd|S )NrX  )rV  r   )rN  rO  r0   rT  r_   rV  r  r   r`   r`   ra   rX    s    z
Window.std)NNr`   )r   )r   )ry   r  r  r  rG   r^   rC  r  r   r1   r   r  r  r7   r3   r5   r8   r9   rL  rS  rT  rX  r;  r`   r`   r  ra   r<  I  s    P   8
	





r<  c                   @  s\  e Zd Zdd Zd@ddddd	d
dddZddddddddZddddddddZddddddddZddddddddZddddddddZ	dAdddddZ
dBdddd ddd!d"d#ZdCdddd ddd!d$d%Zd&d' ZdDd d(d)d*Zd+d, ZdEd.d/d0d1d2ZdFd5ddd6d7d8ZdGd9d:d d;d<d=ZdHd9d:d d;d>d?ZdS )IRollingAndExpandingMixinc                 C  s   t j}| j|ddS )Nr   )r   )rP  roll_sumr  )r_   rR  r`   r`   ra   r     s    zRollingAndExpandingMixin.countFNr   rL   rM   r  tuple[Any, ...] | Nonedict[str, Any] | Noner   r  enginer  r  r   c                 C  s   |d krd}|d kri }t |s(tdd }d}t|r|dkrHtdt| j}	|}| jdkr~t||||	}
||	 df}qt||||	 d}
||	 df}n2|d	kr|d k	rtd
| ||||}
ntd| j	|
||dS )Nr`   z'raw parameter must be `True` or `False`Fz.raw must be `True` when using the numba enginerJ   Z_apply_singler  Z_apply_table)cythonNz+cython engine does not accept engine_kwargsz)engine must be either 'numba' or 'cython')r   r   )
r   r]   r.   rs   ry   rV   r=   r>   _generate_cython_apply_funcr  )r_   r   r  r_  r  r  r   r   r   Zcaller_name
apply_funcr`   r`   ra   r    sL    	

      zRollingAndExpandingMixin.applyr   zdict[str, Any]z?Callable[[np.ndarray, np.ndarray, np.ndarray, int], np.ndarray])r  r   r  r   rk   c                   s8   ddl m  ttj||||d|f fdd	}|S )Nr   r   )r  r   r  r   c                   s    |s | j d} | |||S )N)rZ   )rI   )r   beginr}   rP   r  r@   r_   rR  r`   ra   rb  :  s    zHRollingAndExpandingMixin._generate_cython_apply_func.<locals>.apply_func)r   r@   r   rP  Z
roll_apply)r_   r  r   r  r   rb  r`   rd  ra   ra  )  s    z4RollingAndExpandingMixin._generate_cython_apply_funcr_  r  c                O  sr   t d|| t|rV| jdkr<ttj}| j|d||dS ddlm	} | 
|d|S tj}| j|fddi|S )	NrL  rq   Tr  r_  r  r   )sliding_sumZrolling_sumr   )rN  rO  r.   rV   r<   r   Znansumr  pandas.core._numba.kernelsrg  r	  rP  r[  r  )r_   r_  r  r  r   r   rg  rR  r`   r`   ra   rL  B  s    

zRollingAndExpandingMixin.sumc                O  st   t d|| t|rX| jdkr<ttj}| j|d||dS ddlm	} | 
|d|dS tj}| j|fddi|S )	Nmaxrq   Trf  r   sliding_min_maxZrolling_maxr   )rN  rO  r.   rV   r<   r   Znanmaxr  rh  rk  r	  rP  roll_maxr  r_   r_  r  r  r   r   rk  rR  r`   r`   ra   ri  Z  s&    

   zRollingAndExpandingMixin.maxc                O  st   t d|| t|rX| jdkr<ttj}| j|d||dS ddlm	} | 
|d|dS tj}| j|fd	di|S )
Nminrq   Trf  r   rj  Zrolling_minFr   )rN  rO  r.   rV   r<   r   Znanminr  rh  rk  r	  rP  roll_minr  rm  r`   r`   ra   rn  t  s&    

   zRollingAndExpandingMixin.minc                O  sr   t d|| t|rV| jdkr<ttj}| j|d||dS ddlm	} | 
|d|S tj}| j|fddi|S )	NrS  rq   Trf  r   )sliding_meanZrolling_meanr   )rN  rO  r.   rV   r<   r   Znanmeanr  rh  rp  r	  rP  	roll_meanr  )r_   r_  r  r  r   r   rp  rR  r`   r`   ra   rS    s    

zRollingAndExpandingMixin.meanc                 K  sR   t |r6| jdkrttj}ntj}| j|d||dS tj}| j|fddi|S )Nrq   Trf  r   median)	r.   rV   r<   r   Z	nanmedianr  rP  Zroll_median_cr  )r_   r_  r  r   r   rR  r`   r`   ra   rr    s    
zRollingAndExpandingMixin.medianr   r{   rV  r_  r  c                  st   t d|| t|rJ| jdkr*tdn ddlm} t| |d| S t	j
 fdd}| j|fd	di|S )
NrX  rq   z%std not supported with method='table'r   sliding_varZrolling_stdc                   s   t | ||| dS )NrU  )r0   )r   rc  r}   rP   rV  rR  r`   ra   
zsqrt_func  s    z0RollingAndExpandingMixin.std.<locals>.zsqrt_funcr   )rN  rO  r.   rV   r   rh  ru  r0   r	  rP  roll_varr  )r_   rV  r_  r  r  r   ru  rw  r`   rv  ra   rX    s"    

zRollingAndExpandingMixin.stdc                O  sj   t d|| t|rF| jdkr*tdnddlm} | |d||S tt	j
|d}| j|fddi|S )	NrT  rq   z%var not supported with method='table'r   rt  Zrolling_varrU  r   )rN  rO  r.   rV   r   rh  ru  r	  r   rP  rx  r  )r_   rV  r_  r  r  r   ru  rR  r`   r`   ra   rT    s&    

   zRollingAndExpandingMixin.varc                 K  s   t j}| j|fddi|S )Nr   skew)rP  Z	roll_skewr  r_   r   rR  r`   r`   ra   ry    s    zRollingAndExpandingMixin.skewrU  c                 O  s   | j |||  | d S N      ?rX  r   powrY  r`   r`   ra   sem  s    zRollingAndExpandingMixin.semc                 K  s   t j}| j|fddi|S )Nr   kurt)rP  Z	roll_kurtr  rz  r`   r`   ra   r    s    zRollingAndExpandingMixin.kurtlinearfloatrN   quantileinterpolationc                 K  sF   |dkrt j}n |dkr t j}ntt j||d}| j|fddi|S )Ng      ?g        r  r   r  )rP  rl  ro  r   Zroll_quantiler  )r_   r  r  r   rR  r`   r`   ra   r    s    z!RollingAndExpandingMixin.quantileaverageTr   rV   	ascendingpctc                 K  s(   t tj|||d}| j|fddi|S )N)rV   r  Z
percentiler   rank)r   rP  Z	roll_rankr  )r_   rV   r  r  r   rR  r`   r`   ra   r    s    zRollingAndExpandingMixin.rankr   r   r   r   rV  c                   s.   ddl m   fdd}j|||S )Nr   r   c              	     s    | } |} }jd k	r,jn|j}|jt||jjd\}}||t| t	j
ddr t|| |||}t||||}	t||||}
tt|| t	j||d}||	|
  ||   }W 5 Q R X  || j| jdS )Nr   r   r   r   r   )r   r   rP   r   rv   r   rQ   rU   r   r   r   rP  rq  r[  r   r   r   rZ   r   )r   yx_arrayy_arrayr   rP   r|   r}   mean_x_ymean_xmean_y	count_x_yr   r@   rV  r_   r`   ra   cov_func+  s>    


      "z.RollingAndExpandingMixin.cov.<locals>.cov_funcr   r@   r   r   )r_   r   r   rV  r   r  r`   r  ra   cov"  s    zRollingAndExpandingMixin.covc                   s.   ddl m   fdd}j|||S )Nr   r   c              	     s0   | } |} }jd k	r,jn|j}|jt||jjd\}}||t| t	j
dd t|| |||}t||||}	t||||}
tt|| t	j||d}t||||}t||||}||	|
  ||   }|| d }|| }W 5 Q R X  || j| jdS )Nr   r   r   r   r|  r   )r   r   rP   r   rv   r   rQ   rU   r   r   r   rP  rq  r[  r   r   r   rx  rZ   r   )r   r  r  r  r   rP   r|   r}   r  r  r  r  Zx_varZy_var	numeratordenominatorr   r  r`   ra   	corr_funcT  sb    


              

z0RollingAndExpandingMixin.corr.<locals>.corr_funcr  )r_   r   r   rV  r   r  r`   r  ra   corrJ  s    'zRollingAndExpandingMixin.corr)FNNNN)NN)r   )r   )r   )r  )r  TF)NNr   )NNr   )ry   r  r  r   r  ra  rL  ri  rn  rS  rr  rX  rT  ry  r  r  r  r  r  r  r`   r`   r`   ra   rZ    sb        /          *   rZ  c                      s  e Zd ZU ddddddddgZd	ed
<  fddZ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d(d) d!d*d+d$
dd-d.d/d0d1d2d3 fd4d5Zeeed'ee eedeedeed6eede
d7ddd d!d8d8d$d(d(d9d/d0d9 fd:d;Zeeed'ee eedeedeed6ed(d) d!d<d=d$d(d(d9d/d0d9 fd>d?Zeeed'ee eedeedeed6eede
d@ddd d!dAdBd$d(d(d9d/d0d9 fdCdDZeeed'ee eedeedeed6eede
dEddd d!dFdFd$d(d(d9d/d0d9 fdGdHZeeed'e eedeedeed6eede
dIddd d!dJdJd$dd/d0d9 fdKdLZeeed'e
dMddd eedNeedeeddOeed6e
dPddd ede
dQddd d!dRdSd$dd(d(d9dTd/d0dU fdVdWZeeed'e
dMddd eedNeedeeddXeed6e
dYddd ede
dZddd d!d[d\d$dd(d(d9dTd/d0dU fd]d^Zeeed'eedeedd_eed6d`d!dadbd$ fdcddZ eeed'e
dMddd eeedeedeed6deede
dfddd d!dgdhd$ddTdidjdkZ!eeed'eedeeddleed6dmede
dnddd d!dodpd$ fdqdrZ"eeed'e
dsddd eedeedeede
dtddd d!dudud$ddwddx fdydzZ#eed{ed'e
d|ddd eedeedeede
d}ddd d!d~d~d$ddd.d.d fddZ$eeed'e
dddd eedeeded(d) d!ddd$ddddTd fddZ%eeed'e
dddd eedeede
dddd eed6e
dddd ede
dddd d!ddd$ddddTd fddZ&  Z'S )RollingrW   rP   rQ   rR   rS   rT   rU   rV   rF   rG   c              
     s   t    | jjs$t| jtttfrt| j	t
ttfr|   zt| j	}W n: ttfk
r } ztd| j	 d|W 5 d }~X Y nX t| jtr|j| jjj| jjj  | _n|j| _| jd krd| _n,t| j	trd S t| j	r| j	dk rtdd S )Nzpassed window z, is not compatible with a datetimelike indexr   r   r>  )r  r^   rO   r:  r\   rI   r'   r+   r*   rW   rN   r
   r    _validate_datetimelike_monotonicr   rr   r]   Znanosre   nrY   rP   r#   r   )r_   re   r   r  r`   ra   r^     s2    

zRolling._validatec                 C  s0   | j jr| d | j js,| j js,| d dS )z
        Validate self._on is monotonic (increasing or decreasing) and has
        no NaT values for frequency windows.
        values must not have NaTzvalues must be monotonicN)rI   hasnans_raise_monotonic_erroris_monotonic_increasingis_monotonic_decreasingri   r`   r`   ra   r    s    
z(Rolling._validate_datetimelike_monotonicrN   )msgc                 C  s8   | j }|d kr"| jdkrd}nd}t| d| d S )Nr   rZ   column )rT   rS   r]   )r_   r  rT   r`   r`   ra   r    s    
zRolling._raise_monotonic_errorr  z
        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
        zSeries/DataframerE  rF  c                   s   t  j|f||S r   )r  r  )r_   r   r  r   r  r`   ra   r    s    &zRolling.aggregaterI  rJ  ZExamplesa  
        >>> 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
        
r   rK  zcount of non NaN observationsr   rM  c                   sB   | j d kr4tjdtt d d| _ t  }d | _ n
t  }|S )Nzmin_periods=None will default to the size of window consistent with other methods in a future version. Specify min_periods=0 instead.rc   r   )rP   rf   rg   rh   r   r  r   )r_   r   r  r`   ra   r     s    #
	

zRolling.countrH  Nr  zcustom aggregation functionr  Fr   rL   rM   r  r\  r]  r^  c                   s   t  j||||||dS )N)r  r_  r  r  r   )r  r  )r_   r   r  r_  r  r  r   r  r`   ra   r    s    zRolling.applyZNotesa]  
        >>> 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.rolling(3, center=True).sum()
        0     NaN
        1     6.0
        2     9.0
        3    12.0
        4     NaN
        dtype: float64

        For DataFrame, each 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
        rL  re  c                  s&   t d|| t j|||d|S )NrL  re  )rN  validate_rolling_funcr  rL  r_   r_  r  r  r   r  r`   ra   rL  <  s    GzRolling.summaximumri  c                  s&   t d|| t j|||d|S )Nri  re  )rN  r  r  ri  r  r  r`   ra   ri    s    zRolling.maxz
        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
        minimumrn  c                  s&   t d|| t j|||d|S )Nrn  re  )rN  r  r  rn  r  r  r`   ra   rn    s    &zRolling.mina  
        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
        rS  c                  s&   t d|| t j|||d|S )NrS  re  )rN  r  r  rS  r  r  r`   ra   rS    s    -zRolling.meana  
        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
        rr  c                   s   t  jf ||d|S )Nre  )r  rr  )r_   r_  r  r   r  r`   ra   rr    s    $zRolling.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.
aK  
        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.

        The implementation is susceptible to floating point imprecision as
        shown in the example below.

        a&  
        >>> s = pd.Series([5, 5, 6, 7, 5, 5, 5])
        >>> s.rolling(3).std()
        0             NaN
        1             NaN
        2    5.773503e-01
        3    1.000000e+00
        4    1.000000e+00
        5    1.154701e+00
        6    2.580957e-08
        dtype: float64
        zstandard deviationrX  r{   rs  c                  s(   t d|| t jf |||d|S )NrX  rs  )rN  r  r  rX  r_   rV  r_  r  r  r   r  r`   ra   rX    s    9  zRolling.stdz/numpy.var : Equivalent method for NumPy array.
aK  
        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.

        The implementation is susceptible to floating point imprecision as
        shown in the example below.

        a&  
        >>> s = pd.Series([5, 5, 6, 7, 5, 5, 5])
        >>> s.rolling(3).var()
        0             NaN
        1             NaN
        2    3.333333e-01
        3    1.000000e+00
        4    1.000000e+00
        5    1.333333e+00
        6    6.661338e-16
        dtype: float64
        ZvariancerT  c                  s(   t d|| t jf |||d|S )NrT  rs  )rN  r  r  rT  r  r  r`   ra   rT  ]  s    9  zRolling.varz:scipy.stats.skew : Third moment of a probability density.
zDA minimum of three periods is required for the rolling calculation.
zunbiased skewnessry  c                   s   t  jf |S r   )r  ry  r_   r   r  r`   ra   ry    s    zRolling.skewz:A minimum of one period is required for the calculation.

z
        >>> s = pd.Series([0, 1, 2, 3])
        >>> s.rolling(2, min_periods=1).sem()
        0         NaN
        1    0.707107
        2    0.707107
        3    0.707107
        dtype: float64
        zstandard error of meanr  rU  c                 O  s   | j |||  | d S r{  r}  rY  r`   r`   ra   r    s    #zRolling.semz/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[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
        z,Fisher's definition of kurtosis without biasr  c                   s   t  jf |S r   )r  r  r  r  r`   ra   r    s    &zRolling.kurta  
        quantile : float
            Quantile to compute. 0 <= quantile <= 1.
        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.
        ae  
        >>> 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
        r  r  r  r  c                   s   t  jf ||d|S )Nr  )r  r  )r_   r  r  r   r  r`   ra   r    s    0zRolling.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.rolling(3).rank()
        0    NaN
        1    NaN
        2    2.0
        3    2.0
        4    3.0
        5    1.5
        dtype: float64

        >>> s.rolling(3).rank(method="max")
        0    NaN
        1    NaN
        2    2.0
        3    2.0
        4    3.0
        5    2.0
        dtype: float64

        >>> s.rolling(3).rank(method="min")
        0    NaN
        1    NaN
        2    2.0
        3    2.0
        4    3.0
        5    1.0
        dtype: float64
        r  r  Tr   r  c                   s   t  jf |||d|S )Nr  )r  r  )r_   rV   r  r  r   r  r`   ra   r  0	  s    DzRolling.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.
        zsample covariancer  r   r   r  c                   s   t  jf |||d|S Nr  )r  r  r_   r   r   rV  r   r  r`   ra   r  {	  s    $zRolling.covz
        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.

        a   
        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
        Zcorrelationr  c                   s   t  jf |||d|S r  )r  r  r  r  r`   ra   r  	  s    {zRolling.corr)FNNNN)NN)r   )r   )r   )r  )r  TF)NNr   )NNr   )(ry   r  r  rG   r  r^   r  r  r   r1   r   r  r  r7   r3   r8   r9   replacer   r;   r  r2   r:   r4   r6   rL  ri  rn  rS  rr  rX  rT  ry  r  r  r  r  r  r  r;  r`   r`   r  ra   r  ~  s  
"
	%  "
      .  /C


  "
  )
       
    3   
    3   
  "  %    /    ?     
   	      7  8v   r  c                   @  s2   e Zd ZdZejej ZddddZdd ZdS )	RollingGroupbyz3
    Provide a rolling groupby implementation.
    r%   rj   c                 C  s   d}| j }t| jtrNt| j}| jj }t|ts:t|	dd | j}n | j
dk	rdt}| j
}n
t}| j}t||| jj||d}|S )z
        Return an indexer class that will compute the window start and end bounds

        Returns
        -------
        GroupbyIndexer
        Nr   )r   r   Zgroupby_indicesr   indexer_kwargs)r   r\   rW   r#   rs   __dict__r   dictAssertionErrorrW  rY   r&   r$   r%   r  r)  )r_   r  r   Zrolling_indexerrW   r   r`   r`   ra   r   )
  s*    	

z"RollingGroupby._get_window_indexerc                 C  sj   | j jr| d | jj D ]F}| j |}|js|js| j	dkrHdn| j	}t
d| d| dqdS )zC
        Validate that each group in self._on is monotonic
        r  NrZ   zEach group within z' must be monotonic. Sort the values in z first.)rI   r  r  r  r)  r   r   r  r  rT   r]   )r_   r0  Zgroup_onrT   r`   r`   ra   r  J
  s    
z/RollingGroupby._validate_datetimelike_monotonicN)	ry   r  r  r  r  rG   r  r   r  r`   r`   r`   ra   r  "
  s   !r  )vr  
__future__r   r   datetimer   	functoolsr   rt   textwrapr   typingr   r   r   r	   rf   numpyr   Zpandas._libs.tslibsr
   r   Z pandas._libs.window.aggregationsZ_libsrW   ZaggregationsrP  Zpandas._typingr   r   r   r   Zpandas.compat._optionalr   Zpandas.compat.numpyr   rN  Zpandas.util._decoratorsr   Zpandas.util._exceptionsr   Zpandas.core.dtypes.commonr   r   r   r   r   r   Zpandas.core.dtypes.genericr   r   Zpandas.core.dtypes.missingr   Zpandas.core._numbar   Zpandas.core.algorithmsr   Zpandas.core.applyr   Zpandas.core.arraysr    Zpandas.core.baser!   r"   Zpandas.core.commoncorecommonr4  Zpandas.core.indexers.objectsr#   r$   r%   r&   Zpandas.core.indexes.apir'   r(   r)   r*   r+   Zpandas.core.reshape.concatr,   Zpandas.core.util.numba_r-   r.   Zpandas.core.window.commonr/   r0   Zpandas.core.window.docr1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   Zpandas.core.window.numba_r<   r=   r>   r   r?   r@   Zpandas.core.genericrA   r  rC   Zpandas.core.internalsrD   rE   r  r<  rZ  r  r  r`   r`   r`   ra   <module>   s|    4     G   /          (