B
    W0d/                @  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(m)Z)m*Z*m+Z+m,Z,m-Z- ddl.m/Z/m0Z0 ddl1m2Z2 ddl3m4Z4 ddl5m6Z6 ddl7m8Z8m9Z9 ddl:m;  m<Z= ddl>m?Z?m@Z@mAZAmBZBmCZC ddlDmEZE ddlFmGZG ddlHmIZImJZJ ddlKmLZLmMZM ddlNmOZOmPZPmQZQmRZRmSZSmTZTmUZUmVZVmWZWmXZXmYZY ddlZm[Z[m\Z\m]Z]m^Z^ ddl_m`Z`maZambZb er(ddlcmdZdmeZe ddlfmgZg ddlDmhZh G dd de9ZiG d d! d!eiZjG d"d# d#eiZkG d$d% d%eiZlG d&d' d'elZmekj em_ G d(d) d)ejemZnd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FrameOrSeriesFrameOrSeriesUnion)import_optional_dependency)function)doc)ensure_float64is_bool
is_integeris_list_like	is_scalarneeds_i8_conversion)ABCDataFrame	ABCSeries)notna)	factorize)ResamplerWindowApply)	DataErrorSelectionMixin)DatetimeIndexIndex
MultiIndexPeriodIndexTimedeltaIndex)ArrayManager)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)BaseIndexerFixedWindowIndexerGroupbyIndexerVariableWindowIndexer)'generate_manual_numpy_nan_agg_with_axisgenerate_numba_apply_funcgenerate_numba_table_func)	DataFrameSeries)BaseGrouper)Blockc               @  s  e Zd ZU dZg Zded< e Zded< ded< dUd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 d!ZdVd"d#Zdd$d%d&Zd'd( Zddd)d*Zd+d, Zd-d.d/d0d1Zd2d2dd3d4d5Ze	d6d7 Zd2d2d2d8d9d:Zd;dd<d=ZdWd>dd?d@dAdBZdXd>ddCd@dDdEZdYd>ddCd@dFdGZdCdHdIdJdCdKdLdMZdZdNddOdPdQdRZdSdT ZeZdS )[
BaseWindowz7Provides utilities for performing windowing operations.z	list[str]_attributeszfrozenset[Hashable]
exclusionsr!   _onNFr   single)	selectionr   z
int | Noneboolz
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)rI   rN   rO   windowrJ   rK   	_win_typeZ_get_axis_numberrM   rP   _win_freq_i8indexrD   columns
isinstancer!   r   
ValueErrorZ
_selectionvalidate)selfrI   rQ   rJ   rK   rL   rM   rN   rO   rP   rF    rZ   L/var/www/html/venv/lib/python3.7/site-packages/pandas/core/window/rolling.py__init__t   s,    


zBaseWindow.__init__c             C  s$   | j d k	rtjdtd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)rS   warningswarnFutureWarningrR   )rY   rZ   rZ   r[   rL      s    
zBaseWindow.win_type)returnc             C  s   t jdtdd | jd k	S )NzFis_datetimelike is deprecated and will be removed in a future version.r]   )r^   )r`   ra   rb   rS   )rY   rZ   rZ   r[   is_datetimelike   s
    zBaseWindow.is_datetimelikeNonec             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)tablerE   z!method must be 'table' or 'single)rK   r   rW   rJ   r   rQ   rO   rV   rI   r   r   	TypeErrortyper6   inspect	signatureget_window_bounds
parameterskeys__name__rP   )rY   Zget_window_bounds_signatureZexpected_signaturerZ   rZ   r[   rX      s0    





zBaseWindow.validate)rI   rc   c             C  sv   | j dk	r:t| j ts:|jdkr:|j|j| j gdd}| jdkrr|jddgdgd	}|j	d
dd}|j
 |_
|S )zA
        Split data into blocks & return conformed data.
        Nr]   F)rU   copy   integerfloatr   )includeexcludefloat64)rq   )rN   rV   r!   ndimreindexrU   
differencerM   Zselect_dtypesastype_mgrconsolidate)rY   rI   rZ   rZ   r[   _create_data   s     
zBaseWindow._create_datac          	     s   |dkr j }t ( tddt  fdd jD }W d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ignorerL   c               s   i | ]}t  ||qS rZ   )getattr).0attr)rY   rZ   r[   
<dictcomp>   s    z'BaseWindow._gotitem.<locals>.<dictcomp>r]   rF   )
rI   r`   catch_warningsfilterwarningsrb   rB   rx   r   r   rj   )rY   keyrx   subsetkwargsrF   Znew_winrZ   )rY   r[   _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__rI   AttributeErrorrj   rp   )rY   r   rZ   rZ   r[   __getattr__  s    

zBaseWindow.__getattr__c             C  s
   | j  S )N)rI   _dir_additions)rY   rZ   rZ   r[   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_name)rY   rZ   r[   	<genexpr>  s   z&BaseWindow.__repr__.<locals>.<genexpr>,z [])rB   joinrj   rp   )rY   Z
attrs_listattrsrZ   )rY   r[   __repr__  s    


zBaseWindow.__repr__c             c  s   | j | j}| |}|  }|jt|| j| j| j	d\}}t|t|ksXt
dx,t||D ]\}}|jt|| }|V  qdW d S )N)
num_valuesrJ   rK   rO   z6these should be equal in length from get_window_bounds)_selected_objZset_axisrD   r~   _get_window_indexerrm   lenrJ   rK   rO   AssertionErrorzipZilocslice)rY   rI   indexerstartendseresultrZ   rZ   r[   __iter__$  s    

zBaseWindow.__iter__r   z
np.ndarray)valuesrc   c          
   C  s   t |jr*tdt| j d|j dnFyt|}W n8 ttfk
rn } ztd|j |W d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 implementedzcannot handle this type -> N)r   dtypeNotImplementedErrorrj   rp   r   rW   ri   npisinfanywherenan)rY   r   errinfrZ   rZ   r[   _prep_values8  s    
$
zBaseWindow._prep_valuesr=   )r   rI   rc   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>   )rT   name)pandasr>   rN   rD   equalsrT   r   rI   rU   namesr   Zget_locintersectionr   insert)rY   r   rI   r>   r   Z	extra_colZold_colsZnew_colsZold_locoverlapnew_locrZ   rZ   r[   _insert_on_columnP  s     


zBaseWindow._insert_on_columnc             C  s   t | jjr| jjS d S )N)r   rD   r   Zasi8)rY   rZ   rZ   r[   _index_arrayi  s    zBaseWindow._index_array)outrI   rc   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.rr   r   zNo numeric types to aggregaterw   )shaper   r{   r   )rY   r   rI   rZ   rZ   r[   _resolve_outputp  s    

zBaseWindow._resolve_outputr6   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_sizerK   )r   )rV   rQ   r6   rS   r9   r   rK   r7   )rY   rZ   rZ   r[   r   z  s    

zBaseWindow._get_window_indexerzCallable[..., ArrayLike]r>   )homogeneous_funcr   rc   c          
   C  s   |  | j}|dkr"t|t}y| |j}W n0 ttfk
rb } zt	d|W dd}~X Y nX ||}|j
||j|jdS )z4
        Series version of _apply_blockwise
        countzNo numeric types to aggregateN)rT   r   )r~   r   r   r{   intr   Z_valuesri   r   r   _constructorrT   r   )rY   r   r   rI   r   r   r   rZ   rZ   r[   _apply_series  s    zBaseWindow._apply_seriesr   c       	        s   j jdkr |S j }|dkrFt|t}|j |_|j}ddd fdd}ddd fdd	}t	|t
rjdkr|j|d
d}n|j|d
d}||}||S )zl
        Apply the given function to the DataFrame broken down into homogeneous
        sub-frames.
        rr   r   r   )bvaluesrc   c               s&    t| d| } |}t|d|S )NT)r   r   )r   r   Z
res_values)r   rY   rZ   r[   hfunc  s    z*BaseWindow._apply_blockwise.<locals>.hfunc)r   rc   c               s    | }  | S )N)r   )r   )r   rY   rZ   r[   hfunc2d  s    
z,BaseWindow._apply_blockwise.<locals>.hfunc2dT)Zignore_failures)r   rx   r   r~   r   r{   r   r|   r}   rV   r%   rM   Zapply_2dapplyr   r   )	rY   r   r   rI   Zmgrr   r   Znew_mgrr   rZ   )r   rY   r[   _apply_blockwise  s    
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
        rr   z1method='table' not applicable for Series objects.)rT   rU   )r   rx   rW   r~   r   Zto_numpyrM   r   r   rT   rU   r   )rY   r   r   rI   r   r   r   rZ   rZ   r[   _apply_tablewise  s    zBaseWindow._apply_tablewisezFrameOrSeriesUnion | Nonezbool | NonezFCallable[[FrameOrSeriesUnion, FrameOrSeriesUnion], FrameOrSeriesUnion])targetotherpairwisefuncrc   c             C  sH   |dkr|}|dkrdn|}nt |ttfs4tdt|||t|dS )z]
        Apply the given pairwise function given 2 pandas objects (DataFrame/Series)
        NTz#other must be a DataFrame or Series)r   )rV   r   r   rW   r)   rG   )rY   r   r   r   r   rZ   rZ   r[   _apply_pairwise  s    
zBaseWindow._apply_pairwisezCallable[..., Any]ztuple[Callable, str] | None)r   r   numba_cache_keyc               s^     jdk	rjnjdd fdd}jdkrN||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
        **kwargs
            additional arguments for rolling function and window function

        Returns
        -------
        y : type of input
        Nz
np.ndarray)r   c          	     s~   | j dkr|  S  fdd}tjdd4 | jdkrXjdkrXt|j| }n|| }W d Q R X d k	rz t< |S )Nr   c               sD   j t| jjd\}}t|t|ks6td | ||S )N)r   rJ   rK   rO   z6these should be equal in length from get_window_bounds)rm   r   rK   rO   r   )xr   r   )r   rJ   rY   window_indexerrZ   r[   calc  s    
z9BaseWindow._apply.<locals>.homogeneous_func.<locals>.calcr   )allrr   rE   )	sizerq   r   errstaterx   rP   apply_along_axisrM   r'   )r   r   r   )r   rJ   r   rY   r   rZ   r[   r     s    
z+BaseWindow._apply.<locals>.homogeneous_funcrE   )r   rJ   r   rP   r   r   )rY   r   r   r   r   r   rZ   )r   rJ   r   rY   r   r[   _apply  s    
zBaseWindow._applyc             O  s2   t | |||d }|d kr.| j|d||dS |S )N)argsr   F)rawr   r   )r   aggr   )rY   r   r   r   r   rZ   rZ   r[   	aggregate%  s    zBaseWindow.aggregate)NNFNr   NNrE   )N)N)N)N)NN)rp   
__module____qualname____doc__rB   __annotations__	frozensetrC   r\   propertyrL   rd   rX   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rZ   rZ   rZ   r[   rA   m   sF   
       " 	&
 

# ?rA   c                  s   e Zd ZU dZded< ded< dgZdddddd	 fd
dZ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
dd  Z  ZS )#BaseWindowGroupbyz3
    Provide the groupby windowing facilities.
    r?   _grouperrG   	_as_indexT)r   r   )rI   r   r   c              sT   ddl m} t||std|| _|| _|j| jjdd}t j	|f|| d S )Nr   )r?   zMust pass a BaseGrouper object.r   )rU   errors)
pandas.core.groupby.opsr?   rV   rW   r   r   dropr   superr\   )rY   rI   r   r   r   r   r?   )	__class__rZ   r[   r\   7  s    
zBaseWindowGroupby.__init__NzCallable[..., Any]z
str | Noneztuple[Callable, str] | None)r   r   r   rc   c               sJ  t  j|||f|}jj}|j}tjj}|| }	fddjjD }
t|
t|krn|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sF|jttt|d	}|S )
Nc               s&   g | ]}| j jjks|d kr|qS )N)rI   rT   r   )r   r   )rY   rZ   r[   
<listcomp>a  s   z,BaseWindowGroupby._apply.<locals>.<listcomp>r   )rU   r   )r   c               s   g | ]}|  qS rZ   )take)r   c)r   rZ   r[   r   r  s    F)r   verify_integrity)level)r   r   rI   rT   r   rq   r   r   r   codeslevelsindicesr   r   concatenatelistarrayintpr   rV   r"   Zfrom_arraysextendr   Zreset_indexrange)rY   r   r   r   r   r   Zgrouped_object_indexZgrouped_index_nameZgroupby_keysZresult_index_namesZdrop_columnsr   r   group_indicesidxresult_index)r   )r   rY   r[   r   K  s@    



zBaseWindowGroupby._applyr   zFrameOrSeriesUnion | Nonezbool | NonezFCallable[[FrameOrSeriesUnion, FrameOrSeriesUnion], FrameOrSeriesUnion])r   r   r   r   rc   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 }xttt| D ]6}	tt|	|}
t|
\}}|| || qW nr| jj}| jj}| jj }|rtt| ntjg tjd	 |jd
kr8d
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 )z]
        Apply the given pairwise function given 2 pandas objects (DataFrame/Series)
        r   )rU   r   Nc             3  s   | ]}t |t  kV  qd S )N)r   )r   group)r   rZ   r[   r     s    z4BaseWindowGroupby._apply_pairwise.<locals>.<genexpr>c               s   g | ]}  | jqS rZ   )r   ry   rT   )r   Z
gb_indices)r   rZ   r[   r     s   z5BaseWindowGroupby._apply_pairwise.<locals>.<listcomp>c             s  s   | ]}t |V  qd S )N)comZmaybe_make_list)r   pairrZ   rZ   r[   r     s    )r   rr   c               s   g | ]}t | qS rZ   )r   repeatr   )r   r   )r   	repeat_byrZ   r[   r     s    F)r   r   )r   r   r   r~   r   r   r   r   r   r   r&   ro   mapr   r   r   r  r   r   appendr   r   r   r   rx   rU   rV   rT   r"   r   )rY   r   r   r   r   Zold_result_lenZgb_pairsZgroupby_codesZgroupby_levelsZgb_level_pairlabelsr   r   r   Zresult_codesZresult_levelsZresult_namesZ	idx_codesZ
idx_levelsr   )r   )r   r   r  r   r[   r     sT    





z!BaseWindowGroupby._apply_pairwise)rI   rc   c               s:   |j s.tt| jj tj}|	|}t
 |S )zA
        Split data into blocks & return conformed data.
        )emptyr   r   r   r   r   r   r{   Zint64r   r   r~   )rY   rI   Zgroupby_order)r   rZ   r[   r~     s
    
zBaseWindowGroupby._create_datac               s,   | j d k	r| j| j| _t j|||dS )N)r   )rN   rI   Z	set_indexrD   r   r   )rY   r   rx   r   )r   rZ   r[   r     s    
zBaseWindowGroupby._gotitemc             C  s   dS )zW
        Validate that "on" is monotonic; already validated at a higher level.
        NrZ   )rY   rZ   rZ   r[   _validate_monotonic  s    z%BaseWindowGroupby._validate_monotonic)NN)N)rp   r   r   r   r   rB   r\   r   r   r~   r   r  __classcell__rZ   rZ   )r   r[   r   .  s   
 7Tr   c                  sx  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d9d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d.ed eed!eed"edd# d$d/d0d'd:dd2d3d4Zeed.ed eed!eed"edd# d$d5d6d'd;dd2d7d8Z  ZS )<Windowa  
    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 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
    closed : str, default None
        Make the interval closed on the 'right', 'left', 'both' or
        'neither' endpoints. Defaults to 'right'.

        .. versionchanged:: 1.2.0

            The closed parameter with fixed windows is now supported.
    method : str {'single', 'table'}, default 'single'
        Execute the rolling operation per single column or row (``'single'``)
        or over the entire object (``'table'``).

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

        .. versionadded:: 1.3.0

    Returns
    -------
    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>`__.

    If ``win_type=None``, all points are evenly weighted; otherwise, ``win_type``
    can accept a string of any `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.
    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
    rQ   rJ   rK   rL   rM   rN   rO   rP   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   z&window must be an integer 0 or greaterrE   z+'single' is the only supported method type.)r   rX   rV   rL   rH   rW   r   r   _scipy_weight_generatorrQ   r6   r   r   rP   )rY   signal)r   rZ   r[   rX     s    



zWindow.validatez
np.ndarrayr   )r   offsetrc   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.
        rr   z8Requested axis is larger then no. of argument dimensionsr   N)rM   rx   rW   r   r   rq   tuple)rY   r   r  Zlead_indexerrZ   rZ   r[   _center_window  s    zWindow._center_windowNz,Callable[[np.ndarray, int, int], np.ndarray]z
str | Noneztuple[Callable, str] | None)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
        **kwargs
            additional arguments for scipy windows if necessary

        Returns
        -------
        y : type of input
        rr   r]   r   z
np.ndarray)r   c          	     s|   | j dkr|  S  fdd}tjdd0 | jdkrNt|j| }nt|| }W d Q R X jrx	|}|S )Nr   c               s6   t t jg }t | |f}  | jp2tS )N)r   r   r   r   rJ   r   )r   Zadditional_nans)r   r  rY   rQ   rZ   r[   r     s    z5Window._apply.<locals>.homogeneous_func.<locals>.calcr   )r   rr   )
r   rq   r   r   rx   r   rM   ZasarrayrK   r  )r   r   r   )r   r  rY   rQ   rZ   r[   r     s    

z'Window._apply.<locals>.homogeneous_func)r  rQ   rK   r   r   )rY   r   r   r   r   r   rZ   )r   r  rY   rQ   r[   r     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 )see_alsoexamplesklassrM   c             O  s(   t | |||d }|d kr$|| }|S )N)r   r   )r   r   )rY   r   r   r   r   rZ   rZ   r[   r     s     zWindow.aggregate
ParametersReturnszSee Alsorollingzweighted window sumsum)window_methodaggregation_description
agg_methodc             O  s*   t d|| tj}| j|fddi|S )Nr  r   )nvvalidate_window_funcwindow_aggregationsZroll_weighted_sumr   )rY   r   r   window_funcrZ   rZ   r[   r  /  s    z
Window.sumzweighted window meanmeanc             O  s*   t d|| tj}| j|fddi|S )Nr   r   )r  r  r  Zroll_weighted_meanr   )rY   r   r   r  rZ   rZ   r[   r   C  s    zWindow.meanz.. versionadded:: 1.0.0 

zweighted window variancevarrr   )ddofc             O  s>   t d|| ttj|d}|dd  | j|fddi|S )Nr!  )r"  r   )r  r  r   r  Zroll_weighted_varpopr   )rY   r"  r   r   r  rZ   rZ   r[   r!  W  s    z
Window.varz"weighted window standard deviationstdc             O  s(   t d|| t| jf |dd|S )Nr$  )r"  r   )r  r  r*   r!  )rY   r"  r   r   rZ   rZ   r[   r$  j  s    z
Window.std)NN)rr   )rr   )rp   r   r   r   rB   rX   r  r   r   r+   r   r   r   r1   r-   r/   r2   r3   r  r   r!  r$  r  rZ   rZ   )r   r[   r	    s    * 1





r	  c               @  s0  e Zd Zdd Zd9d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	d:dddddZ
d;d d!d"d#Zd<d d!d$d%Zd&d' Zd=d d!d(d)Zd*d+ Zd>d-d.d/d0d1Zd?d2d3d d4d5d6Zd@d2d3d d4d7d8ZdS )ARollingAndExpandingMixinc             C  s   t j}| j|ddS )Nr   )r   )r  roll_sumr   )rY   r  rZ   rZ   r[   r   }  s    zRollingAndExpandingMixin.countFNzCallable[..., Any]rG   z
str | Nonezdict[str, bool] | Noneztuple[Any, ...] | Nonezdict[str, Any] | None)r   r   engineengine_kwargsr   r   c       
      C  s   |d krd}|d kri }t |s(tdd }t|r|dkrDtdt| j}| jdkrxt|||||}	|| df}qt||||| d}	|| df}n2|d	kr|d k	rtd
| ||||}	ntd| j	|	|dS )NrZ   z'raw parameter must be `True` or `False`Fz.raw must be `True` when using the numba enginerE   Z_apply_singler   Z_apply_table)cythonNz+cython engine does not accept engine_kwargsz)engine must be either 'numba' or 'cython')r   )
r   rW   r(   rj   rp   rP   r;   r<   _generate_cython_apply_funcr   )
rY   r   r   r'  r(  r   r   r   Zcaller_name
apply_funcrZ   rZ   r[   r     s4    	

zRollingAndExpandingMixin.applyztuple[Any, ...]zdict[str, Any]z?Callable[[np.ndarray, np.ndarray, np.ndarray, int], np.ndarray])r   r   r   r   rc   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 jd} | |||S )N)rT   )rI   rT   )r   beginr   rJ   r   )r>   rY   r  rZ   r[   r+    s    zHRollingAndExpandingMixin._generate_cython_apply_func.<locals>.apply_func)r   r>   r   r  Z
roll_apply)rY   r   r   r   r   r+  rZ   )r>   rY   r  r[   r*    s    z4RollingAndExpandingMixin._generate_cython_apply_func)r'  r(  c            O  s`   t d|| t|rD| jdkr,ttj}ntj}| j|d||dS tj	}| j
|fddi|S )Nr  rh   T)r   r'  r(  r   )r  r  r(   rP   r:   r   Znansumr   r  r&  r   )rY   r'  r(  r   r   r   r  rZ   rZ   r[   r    s    
zRollingAndExpandingMixin.sumc            O  s`   t d|| t|rD| jdkr,ttj}ntj}| j|d||dS tj	}| j
|fddi|S )Nmaxrh   T)r   r'  r(  r   )r  r  r(   rP   r:   r   Znanmaxr   r  roll_maxr   )rY   r'  r(  r   r   r   r  rZ   rZ   r[   r-    s    
zRollingAndExpandingMixin.maxc            O  s`   t d|| t|rD| jdkr,ttj}ntj}| j|d||dS tj	}| j
|fddi|S )Nminrh   T)r   r'  r(  r   )r  r  r(   rP   r:   r   Znanminr   r  roll_minr   )rY   r'  r(  r   r   r   r  rZ   rZ   r[   r/    s    
zRollingAndExpandingMixin.minc            O  s`   t d|| t|rD| jdkr,ttj}ntj}| j|d||dS tj	}| j
|fddi|S )Nr   rh   T)r   r'  r(  r   )r  r  r(   rP   r:   r   Znanmeanr   r  	roll_meanr   )rY   r'  r(  r   r   r   r  rZ   rZ   r[   r   
  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 )Nrh   T)r   r'  r(  r   median)	r(   rP   r:   r   Z	nanmedianr   r  Zroll_median_cr   )rY   r'  r(  r   r   r  rZ   rZ   r[   r2  !  s    
zRollingAndExpandingMixin.medianrr   r   )r"  c               s8   t d|| tj fdd}| j|fddi|S )Nr$  c               s   t | ||| dS )N)r"  )r*   )r   r,  r   rJ   )r"  r  rZ   r[   
zsqrt_func:  s    z0RollingAndExpandingMixin.std.<locals>.zsqrt_funcr   )r  r  r  roll_varr   )rY   r"  r   r   r3  rZ   )r"  r  r[   r$  6  s    zRollingAndExpandingMixin.stdc             O  s2   t d|| ttj|d}| j|fddi|S )Nr!  )r"  r   )r  r  r   r  r4  r   )rY   r"  r   r   r  rZ   rZ   r[   r!  C  s    zRollingAndExpandingMixin.varc             K  s   t j}| j|fddi|S )Nr   skew)r  Z	roll_skewr   )rY   r   r  rZ   rZ   r[   r5  L  s
    zRollingAndExpandingMixin.skewc             O  s   | j |||  | d S )Ng      ?)r$  r   pow)rY   r"  r   r   rZ   rZ   r[   semT  s    zRollingAndExpandingMixin.semc             K  s   t j}| j|fddi|S )Nr   kurt)r  Z	roll_kurtr   )rY   r   r  rZ   rZ   r[   r8  W  s
    zRollingAndExpandingMixin.kurtlinearrt   rH   )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   r:  )r  r.  r0  r   Zroll_quantiler   )rY   r:  r;  r   r  rZ   rZ   r[   r:  _  s    z!RollingAndExpandingMixin.quantilezFrameOrSeriesUnion | Nonezbool | None)r   r   r"  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|kshtdt	j
ddr t|| |||}t||||}	t||||}
tt|| t	j||d}||	|
  ||   }W d Q R X  || j| jdS )N)r   rJ   rK   rO   z6these should be equal in length from get_window_boundsr   )r   r   )rT   r   )r   r   rJ   r   rm   r   rK   rO   r   r   r   r  r1  r&  r   r{   rw   rT   r   )r   yx_arrayy_arrayr   rJ   r   r   mean_x_ymean_xmean_y	count_x_yr   )r>   r"  rY   rZ   r[   cov_funcv  s,    


"z.RollingAndExpandingMixin.cov.<locals>.cov_func)r   r>   r   r   )rY   r   r   r"  r   rC  rZ   )r>   r"  rY   r[   covm  s     zRollingAndExpandingMixin.covc               s.   ddl m   fdd}j|||S )Nr   )r>   c          	     s6   | } |} }jd k	r,jn|j}|jt||jjd\}}t|t|kshtdt	j
dd t|| |||}t||||}	t||||}
tt|| t	j||d}t||||}t||||}||	|
  ||   }|| d }|| }W d Q R X  || j| jdS )N)r   rJ   rK   rO   z6these should be equal in length from get_window_boundsr   )r   r   g      ?)rT   r   )r   r   rJ   r   rm   r   rK   rO   r   r   r   r  r1  r&  r   r{   rw   r4  rT   r   )r   r<  r=  r>  r   rJ   r   r   r?  r@  rA  rB  Zx_varZy_var	numeratordenominatorr   )r>   r"  rY   rZ   r[   	corr_func  s:    



z0RollingAndExpandingMixin.corr.<locals>.corr_func)r   r>   r   r   )rY   r   r   r"  r   rG  rZ   )r>   r"  rY   r[   corr  s    *zRollingAndExpandingMixin.corr)FNNNN)NN)rr   )rr   )rr   )r9  )NNrr   )NNrr   )rp   r   r   r   r   r*  r  r-  r/  r   r2  r$  r!  r5  r7  r8  r:  rD  rH  rZ   rZ   rZ   r[   r%  |  s:       % 	  )  r%  c                  s   e Zd ZddddddddgZ fd	d
Zdd Z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+d,d-d.d/ fd0d1Zeeed#eeeedeedeed2eede	d3ddddd4d4d d$d$d5d+d,d5 fd6d7Zeeed#eeeedeedeed2ed$d% dd8d9d d$d$d5d+d,d5 fd:d;Zeeed#eeeedeedeed2eede	d<ddddd=d>d d$d$d5d+d,d5 fd?d@Zeeed#eeeedeedeed2eede	dAdddddBdBd d$d$d5d+d,d5 fdCdDZeeed#eeedeedeed2eede	dEdddddFdFd dd+d,d5 fdGdHZeeed#e	dIdddeeedeeddJeed2e	dKdddede	dLdddddMdNd ddOdP fdQdRZeeed#e	dIdddeeedeeddSeed2e	dTdddede	dUdddddVdWd ddOdP fdXdYZeeed#eedeeddZeed2d[dd\d]d  fd^d_Zeeed#e	dIdddeeedeedeed2d`ede	dadddddbdcd ddOdPdddeZ eeed#eedeeddfeed2dgede	dhdddddidjd  fdkdlZ!eeed#e	dmdddeedeedeede	dndddddodod ddqdrds fdtduZ"eeed#e	dvdddeedeeded$d% ddwdxd ddydzdOd{ fd|d}Z#eeed#e	dvdddeedeede	d~dddeed2e	ddddede	dddddddd ddydzdOd{ fddZ$  Z%S )RollingrQ   rJ   rK   rL   rM   rN   rO   rP   c          
     s   t    | jjs$t| jtttfrt| j	t
ttfr|   yt| j	}W n: ttfk
r } ztd| j	 d|W d 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 indexrr   r   z&window must be an integer 0 or greater)r   rX   rI   r  rV   rD   r    r$   r#   rQ   rH   r
   r   r  r   ri   rW   Znanosr_   nrS   rJ   r6   r   )rY   r_   r   )r   rZ   r[   rX     s(    

zRolling.validatec             C  s   | j js| j js|   dS )z@
        Validate monotonic (increasing or decreasing).
        N)rD   Zis_monotonic_increasingZis_monotonic_decreasing_raise_monotonic_error)rY   rZ   rZ   r[   r    s    zRolling._validate_monotonicc             C  s&   | j }| j d krd}t| dd S )NrT   z must be monotonic)rN   rW   )rY   	formattedrZ   rZ   r[   rK    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/Dataframer  )r  r  r  rM   c               s   t  j|f||S )N)r   r   )rY   r   r   r   )r   rZ   r[   r     s    &zRolling.aggregater  zSee AlsoZ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
        
rr   r  zcount of non NaN observationsr   )r  r  r  c               s<   | j d kr.tdt 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.r   )rJ   r`   ra   rb   r   r   )rY   r   )r   rZ   r[   r   5  s    #


zRolling.countr  Nr  zcustom aggregation functionr   FzCallable[..., Any]rG   z
str | Nonezdict[str, bool] | Noneztuple[Any, ...] | Nonezdict[str, Any] | None)r   r   r'  r(  r   r   c               s   t  j||||||dS )N)r   r'  r(  r   r   )r   r   )rY   r   r   r'  r(  r   r   )r   rZ   r[   r   h  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
        r  )r'  r(  c              s&   t d|| t j|||d|S )Nr  )r'  r(  )r  validate_rolling_funcr   r  )rY   r'  r(  r   r   )r   rZ   r[   r    s    GzRolling.summaximumr-  c              s&   t d|| t j|||d|S )Nr-  )r'  r(  )r  rN  r   r-  )rY   r'  r(  r   r   )r   rZ   r[   r-    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
        minimumr/  c              s&   t d|| t j|||d|S )Nr/  )r'  r(  )r  rN  r   r/  )rY   r'  r(  r   r   )r   rZ   r[   r/    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
        r   c              s&   t d|| t j|||d|S )Nr   )r'  r(  )r  rN  r   r   )rY   r'  r(  r   r   )r   rZ   r[   r     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
        r2  c               s   t  jf ||d|S )N)r'  r(  )r   r2  )rY   r'  r(  r   )r   rZ   r[   r2  C  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/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 deviationr$  r   )r"  c               s$   t d|| t jf d|i|S )Nr$  r"  )r  rN  r   r$  )rY   r"  r   r   )r   rZ   r[   r$  i  s    1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variancer!  c               s$   t d|| t jf d|i|S )Nr!  r"  )r  rN  r   r!  )rY   r"  r   r   )r   rZ   r[   r!    s    1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 skewnessr5  c               s   t  jf |S )N)r   r5  )rY   r   )r   rZ   r[   r5    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 meanr7  c             O  s   | j |||  | d S )Ng      ?)r$  r   r6  )rY   r"  r   r   rZ   rZ   r[   r7    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 biasr8  c               s   t  jf |S )N)r   r8  )rY   r   )r   rZ   r[   r8    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:  r9  rt   rH   )r:  r;  c               s   t  jf ||d|S )N)r:  r;  )r   r:  )rY   r:  r;  r   )r   rZ   r[   r:  0  s    0zRolling.quantilea   
        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 covariancerD  zFrameOrSeriesUnion | Nonezbool | None)r   r   r"  c               s   t  jf |||d|S )N)r   r   r"  )r   rD  )rY   r   r   r"  r   )r   rZ   r[   rD  f  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correlationrH  c               s   t  jf |||d|S )N)r   r   r"  )r   rH  )rY   r   r   r"  r   )r   rZ   r[   rH    s    {zRolling.corr)FNNNN)NN)rr   )rr   )rr   )r9  )NNrr   )NNrr   )&rp   r   r   rB   rX   r  rK  r   r+   r   r   r   r1   r-   r2   r3   replacer   r5   r   r,   r4   r.   r0   r  r-  r/  r   r2  r$  r!  r5  r7  r8  r:  rD  rH  r  rZ   rZ   )r   r[   rI    sz  "
     -
 			
  6  rI  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.
    r8   )rc   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   rV   rQ   r6   rj   __dict__rq   dictr   r#  rS   r9   r7   r8   r   r   )rY   rS  r   Zrolling_indexerrQ   r   rZ   rZ   r[   r   	  s(    	

z"RollingGroupby._get_window_indexerc             C  s   | j jr|   dS )z
        Validate that on is monotonic;
        in this case we have to check only for nans, because
        monotonicity was already validated at a higher level.
        N)rD   ZhasnansrK  )rY   rZ   rZ   r[   r  5	  s    z"RollingGroupby._validate_monotonicN)	rp   r   r   r   rI  rB   r   r   r  rZ   rZ   rZ   r[   rR  	  s   !rR  )or   
__future__r   rq   datetimer   	functoolsr   rk   textwrapr   typingr   r   r   r	   r`   numpyr   Zpandas._libs.tslibsr
   r   Z pandas._libs.window.aggregationsZ_libsrQ   Zaggregationsr  Zpandas._typingr   r   r   r   Zpandas.compat._optionalr   Zpandas.compat.numpyr   r  Zpandas.util._decoratorsr   Zpandas.core.dtypes.commonr   r   r   r   r   r   Zpandas.core.dtypes.genericr   r   Zpandas.core.dtypes.missingr   Zpandas.core.algorithmsr   Zpandas.core.applyr   Zpandas.core.baser   r   Zpandas.core.commoncorecommonr   Zpandas.core.indexes.apir    r!   r"   r#   r$   Zpandas.core.internalsr%   Zpandas.core.reshape.concatr&   Zpandas.core.util.numba_r'   r(   Zpandas.core.window.commonr)   r*   Zpandas.core.window.docr+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   Zpandas.core.window.indexersr6   r7   r8   r9   Zpandas.core.window.numba_r:   r;   r<   r   r=   r>   r   r?   r@   rA   r   r	  r%  rI  rR  rZ   rZ   rZ   r[   <module>   sp    4   D J     U      A