o
    ŀgu                    @  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mZmZmZ ddlm  m  mZ dd	lmZ dd
lmZ ddlm Z m!Z! ddl"m#Z#m$Z$m%Z%m&Z&m'Z' ddl(m)Z) ddl*m+Z+m,Z, ddl-m.Z. ddl/m0Z0 ddl1m2Z2 ddl3m4Z4 ddl5m6Z6 ddl7m8Z8 ddl9m:  m;Z< ddl=m>Z>m?Z?m@Z@mAZA ddlBmCZCmDZDmEZEmFZFmGZG ddlHmIZI ddlJmKZKmLZL ddlMmNZNmOZO ddlPmQZQmRZRmSZSmTZTmUZUmVZVmWZWmXZXmYZYmZZZ ddl[m\Z\m]Z]m^Z^ er(ddl_m`Z`maZambZb ddlcmdZdmeZemfZfmgZgmhZhmiZi ddljmkZkmlZl ddlmmnZn dd lompZp dd!lqmrZr G d"d# d#e8ZsG d$d% d%esZtG d&d' d'esZuG d(d) d)esZvG d*d+ d+evZweuj ew_ G d,d- d-etewZxd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Literal)
BaseOffset	Timedelta	to_offset)import_optional_dependency)	DataError)deprecate_kwargdoc)ensure_float64is_bool
is_integeris_numeric_dtypeneeds_i8_conversion)
ArrowDtype)ABCDataFrame	ABCSeries)notna)executor)	factorize)ResamplerWindowApply)ExtensionArray)SelectionMixin)BaseIndexerFixedWindowIndexerGroupbyIndexerVariableWindowIndexer)DatetimeIndexIndex
MultiIndexPeriodIndexTimedeltaIndex)concat)get_jit_argumentsmaybe_use_numba)flex_binary_momentzsqrt)
_shared_docscreate_section_headerkwargs_numeric_only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)HashableIteratorSized)	ArrayLikeAxisNDFrameTQuantileInterpolationWindowingRankTypenpt)	DataFrameSeries)NDFrameBaseGrouper)dtype_to_unitc                   @  s^  e Zd ZU dZg Zded< e Zded< ded< 						
				dsdddtdd Zdud!d"Z	dvd(d)Z
dwdxd-d.Zdyd2d3Zdzd5d6Zd{d|d7d8Zdwd9d:Zd}d<d=Zd>d? Zd~d@dAZddCdDZddGdHZddJdKZeddMdNZddPdQZddSdTZ	dwddXdYZ		d{dd[d\Z			ddd]d^ZddedfZ			gdddkdlZ	dwddodpZdqdr Z e Z!dS )
BaseWindowz7Provides utilities for performing windowing operations.	list[str]_attributeszfrozenset[Hashable]
exclusionsr$   _onNFr   single)	selectionobjrE   min_periods
int | Nonecenterbool | Nonewin_type
str | Noneaxisr>   onstr | Index | NoneclosedstepmethodstrreturnNonec                C  s   || _ || _|| _|	| _|| _|| _|| _|| _|d ur!||nd | _	|
| _
d | _| jd u r@| j	dkr:| j j| _n1| j j| _n+t| jtrK| j| _n t| j trb| j| j jv rbt| 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)rP   rX   rZ   r[   windowrQ   rS   rU   _get_axis_numberrW   r\   _win_freq_i8indexrM   columns
isinstancer$   r   
ValueError
_selection	_validate)selfrP   r`   rQ   rS   rU   rW   rX   rZ   r[   r\   rO    rj   N/var/www/html/myenv/lib/python3.10/site-packages/pandas/core/window/rolling.py__init__   s0   


zBaseWindow.__init__c                 C  sP  | j d urt| j std| jd ur<t| jstd| jdk r%tdt| jr<| j| jkr<td| j d| j | jd urJ| jdvrJtdt| jt	t
fs[td	t|  t| jtrt| jjj }tt jj }||krtt| jj d
| jdvrtd| jd urt| jstd| jdk rtdd S 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 )rightbothleftneitherz3closed must be 'right', 'left', 'both' or 'neither'zinvalid type: z? does not implement the correct signature for get_window_bounds)tablerN   z!method must be 'table' or 'singlezstep must be an integerzstep must be >= 0)rS   r   rf   rQ   r   r`   rZ   re   rP   r   r   	TypeErrortyper   inspect	signatureget_window_bounds
parameterskeys__name__r\   r[   )ri   get_window_bounds_signatureexpected_signaturerj   rj   rk   rh      sN   






zBaseWindow._validatestart
np.ndarrayendnum_valsintc                 C  sx   t |t |krtdt | dt | dt ||| jpd d | jp&d kr:tdt | d| d| j dd S )	Nzstart (z) and end (z ) bounds must be the same length   zstart and end bounds (z)) must be the same length as the object (z) divided by the step (z) if given and rounded up)lenrf   r[   )ri   r|   r~   r   rj   rj   rk   _check_window_bounds   s   $zBaseWindow._check_window_boundsrc   resultSized | Nonec                 C  s,   |du st |t |kr|S |dd| j S )zJ
        Slices the index for a given result and the preset step.
        N)r   r[   )ri   rc   r   rj   rj   rk   _slice_axis_for_step   s
   zBaseWindow._slice_axis_for_stepnamenumeric_onlyboolc                 C  sB   | j jdkr|rt| j jstt| j d| ddS dS dS )z
        Validate numeric_only argument, raising if invalid for the input.

        Parameters
        ----------
        name : str
            Name of the operator (kernel).
        numeric_only : bool
            Value passed by user.
        r   .z  does not implement numeric_onlyN)_selected_objndimr   dtypeNotImplementedErrorrs   ry   )ri   r   r   rj   rj   rk   _validate_numeric_only   s   
z!BaseWindow._validate_numeric_onlyr?   c                 C  s   |j dgdgd}|S )zSubset DataFrame to numeric columns.

        Parameters
        ----------
        obj : DataFrame

        Returns
        -------
        obj subset to numeric-only columns.
        numberr   )includeexclude)select_dtypes)ri   rP   r   rj   rj   rk   _make_numeric_only  s   zBaseWindow._make_numeric_onlyc                 C  s   | j durt| j ts|jdkr|j|j| j gdd}|jdkr.|s)| jdkr.| |}| jdkr@|j	ddd}|j
 |_
|S )A
        Split data into blocks & return conformed data.
        N   F)rd   copyr   float64)r   )rX   re   r$   r   reindexrd   
differencerW   r   astype_mgrconsolidate)ri   rP   r   rj   rj   rk   _create_data  s    

zBaseWindow._create_datac                   sJ   |du r j } fdd jD } ||}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
        Nc                   s   i | ]}|t  |qS rj   getattr).0attrri   rj   rk   
<dictcomp>5  s    z'BaseWindow._gotitem.<locals>.<dictcomp>rO   )rP   rK   _infer_selectionrs   )ri   keyr   subsetkwargsrO   new_winrj   r   rk   _gotitem#  s   zBaseWindow._gotitemr   c                 C  sD   || j v rt| |S || jv r| | S tdt| j d| d)N'z' object has no attribute ')_internal_names_setobject__getattribute__rP   AttributeErrorrs   ry   )ri   r   rj   rj   rk   __getattr__;  s   

zBaseWindow.__getattr__c                 C  s
   | j  S N)rP   _dir_additionsr   rj   rj   rk   r   E  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@    | ]}t  |d d ur|d dkr| dt  | V  qd S )Nr   _=r   )r   	attr_namer   rj   rk   	<genexpr>L  s    z&BaseWindow.__repr__.<locals>.<genexpr>,z [])rK   joinrs   ry   )ri   
attrs_listattrsrj   r   rk   __repr__H  s
   

zBaseWindow.__repr__r;   c                 c  s    | j | j}| |}|  }|jt|| j| j| j	| j
d\}}| ||t| t||D ]\}}|jt|| }|V  q1d S N
num_valuesrQ   rS   rZ   r[   )r   set_axisrM   r   _get_window_indexerrv   r   rQ   rS   rZ   r[   r   zipilocslice)ri   rP   indexerr|   r~   ser   rj   rj   rk   __iter__T  s    

zBaseWindow.__iter__valuesr=   c              
   C  s   t |jrtdt| j d|j dzt|tr$|jtj	tj
d}nt|}W n ttfy@ } z	td|j |d}~ww t|}| rRt|tj
|}|S )z1Convert input to numpy arrays for Cython routineszops for z for this dtype z are not implemented)na_valuezcannot handle this type -> N)r   r   r   rs   ry   re   r   to_numpynpr   nanr   rf   rr   isinfanywhere)ri   r   errinfrj   rj   rk   _prep_valuesf  s&   


zBaseWindow._prep_valuesrC   c                 C  s   ddl m} | jd urb| j|jsd| jj}|| j| jj|dd}||jv r,|||< d S ||jj	v r4d S || j
jv r\| j
j}|j}||}||d | }	t|	}
||
|| d S |||< d S d S d S )Nr   rD   Frc   r   r   )pandasrD   rX   rM   equalsrc   r   rP   rd   namesr   get_locintersectionr   insert)ri   r   rP   rD   r   	extra_colold_colsnew_colsold_locoverlapnew_locrj   rj   rk   _insert_on_column~  s"   

zBaseWindow._insert_on_columnnpt.NDArray[np.int64] | Nonec                 C  sJ   t | jtttfr| jjS t | jjtr#| jjjdv r#| jj	t
jdS d S )NmMr   )re   rM   r&   r#   r'   asi8r   r   kindr   r   int64r   rj   rj   rk   _index_array  s
   zBaseWindow._index_arrayoutc                 C  sL   |j d dkr|j d dkrtd|j d dkr|dS | || |S )zValidate and finalize result.r   r   No numeric types to aggregater   )shaper   r   r   )ri   r   rP   rj   rj   rk   _resolve_output  s   
zBaseWindow._resolve_outputr   c                 C  s<   t | jtr	| jS | jdurt| 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_sizerS   )r   )re   r`   r   rb   r"   r   rS   r    r   rj   rj   rk   r     s   
zBaseWindow._get_window_indexerhomogeneous_funcCallable[..., ArrayLike]rD   c              
   C  s   |  | j}|dkrt|t}z| |j}W n ttfy, } zt	d|d}~ww ||}| 
|j|}|j|||jdS )z5
        Series version of _apply_columnwise
        countr   Nrc   r   )r   r   r   r   r   r   _valuesrr   r   r   r   rc   _constructorr   )ri   r   r   rP   r   r   r   rc   rj   rj   rk   _apply_series  s   
zBaseWindow._apply_seriesDataFrame | Seriesc                 C  s8  |  || | jjdkr| ||S | | j|}|dkr*t|t}|j	 |_| j
dkr2|j}g }g }t| D ]1\}}z| |}W n ttfy^ }	 z	td|j |	d}	~	ww ||}
||
 || q<| |jt|dkr||d nd}t|j|||j|dd}| j
dkr|j}| ||S )zl
        Apply the given function to the DataFrame broken down into homogeneous
        sub-frames.
        r   r   z#Cannot aggregate non-numeric type: Nr   F)rc   rd   verify_integrity)r   r   r   r   r   r   r   r   r   r   rW   T	enumerate_iter_column_arraysr   rr   r   r   r   appendr   rc   r   rs   _from_arraysrd   taker   )ri   r   r   r   rP   taker
res_valuesiarrr   resrc   dfrj   rj   rk   _apply_columnwise  sJ   





zBaseWindow._apply_columnwisec           
      C  s   | j jdkr
td| | j |}| | }| jdkr |jn|}||}| jdkr.|jn|}| |j	|}|j
d t|jkrD|jn|jdd| j }|j|||d}	| |	|S )zT
        Apply the given function to the DataFrame across the entire object
        r   z1method='table' not applicable for Series objects.Nrc   rd   )r   r   rf   r   r   r   rW   r   r   rc   r   r   rd   r[   r   r   )
ri   r   r   r   rP   r   r   rc   rd   r   rj   rj   rk   _apply_tablewise  s   	zBaseWindow._apply_tablewisetargetotherDataFrame | Series | NonepairwisefuncFCallable[[DataFrame | Series, DataFrame | Series], DataFrame | Series]c                 C  sl   |  ||}|du r|}|du rdn|}nt|ttfs td|jdkr,|r,| |}t|||t|dS )]
        Apply the given pairwise function given 2 pandas objects (DataFrame/Series)
        NTz#other must be a DataFrame or Seriesr   )r  )	r   re   r   r   rf   r   r   r+   r   )ri   r  r	  r  r  r   rj   rj   rk   _apply_pairwise  s   
zBaseWindow._apply_pairwiserj   Callable[..., Any]
numba_argstuple[Any, ...]c                   sZ     jdurjnjd fdd}jdkr&|||S |||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_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
        Nr   r}   c                   s`   | j dkr	|  S  fdd}tjdd || }W d    |S 1 s)w   Y  |S )Nr   c                   sJ   j t| jjjd\}}||t|   | ||gR  S r   )rv   r   rS   rZ   r[   r   )xr|   r~   r  rQ   r  ri   window_indexerrj   rk   calcY  s   
z9BaseWindow._apply.<locals>.homogeneous_func.<locals>.calcignoreall)sizer   r   errstater   r  r   r  rj   rk   r   S  s   


z+BaseWindow._apply.<locals>.homogeneous_funcrN   r   r}   )r   rQ   r   r\   r  r  ri   r  r   r   r  r   r   rj   r  rk   _apply2  s   

zBaseWindow._applyengine_kwargsdict[str, bool] | Nonec                 K  sF  |   }| jd ur| jn|j}| | j}| jdkr|j}| | }|j	dkr/|
dd}|jt||| j| j| jd\}}	| ||	t| tj}
tj||
fddit|}||jf||	|d|j}| jdkrp|jn|}| |j|}|j	dkr| }|j|||jd}|S | |j|j}|j|||d}| ||S )	Nr   r   is_grouped_kernelF)r|   r~   rQ   r   r  )r   rQ   r   r   r   rW   r   r   r   r   reshaperv   r   rS   rZ   r[   r   r   float_dtype_mappinggenerate_shared_aggregatorr)   r   rc   squeezer   r   rd   r   )ri   r  r   func_kwargsr  rQ   rP   r   r|   r~   dtype_mapping
aggregatorr   rc   r   rd   rj   rj   rk   _numba_applyo  s\   




zBaseWindow._numba_applyc                 O  s2   t | |||d }|d u r| j|d||dS |S )Nargsr   F)rawr-  r   )r   aggapplyri   r  r-  r   r   rj   rj   rk   	aggregate  s   zBaseWindow.aggregate)	NNFNr   NNNrN   )rP   rE   rQ   rR   rS   rT   rU   rV   rW   r>   rX   rY   rZ   rV   r[   rR   r\   r]   r^   r_   r^   r_   )r|   r}   r~   r}   r   r   r^   r_   r   )rc   r$   r   r   r^   r$   )r   r]   r   r   r^   r_   )rP   r?   r^   r?   FrP   r?   r   r   r^   r?   )r   r]   )r^   r]   )r^   r;   )r   r=   r^   r}   )r   rC   rP   rC   r^   r_   )r^   r   )r   rC   rP   rC   r^   rC   )r^   r   )r   r   r   rV   r^   rD   )r   r   r   r]   r   r   r^   r   )NF)r   r   r   rV   r   r   r^   r   r  r   r	  r
  r  rT   r  r  r   r   r^   r   Frj   )r  r  r   r]   r   r   r  r  )r  r  r   r!  )"ry   
__module____qualname____doc__rK   __annotations__	frozensetrL   rl   rh   r   r   r   r   r   r   r   r   r   r   r   r   propertyr   r   r   r   r  r  r  r  r+  r2  r/  rj   rj   rj   rk   rI   x   sb   
 
-
+












8
@3rI   c                      s   e Zd ZU dZded< ded< dgZded< dd	d) fddZ		d*d+ fddZd, fd!d"Zd-d. fd$d%Z	d/ fd'd(	Z
  ZS )0BaseWindowGroupbyz3
    Provide the groupby windowing facilities.
    rG   _grouperr   	_as_indexrJ   rK   T)r@  rP   r   r^   r_   c                  sp   ddl m} t||std|| _|| _|j| jjdd}|dd ur)t	dt
 j|g|R i | d S )Nr   rF   zMust pass a BaseGrouper object.r  rd   errorsr[   z step not implemented for groupby)pandas.core.groupby.opsrG   re   rf   r?  r@  dropr   getr   superrl   )ri   rP   r?  r@  r-  r   rG   	__class__rj   rk   rl     s   
zBaseWindowGroupby.__init__Frj   r  r  r   r]   r   r  r  c                   sN  t  j||||fi |}jj}g |j}tjj}	|	| }
fddjjD }t|t|	kr;|j|dd}jj	}tjj
}jj }|rVtt| ntjg tjd  fdd|D }|d ur| }t|ts{t|g}|t|j	 |t|j
 t|||
dd}||_js|jttt|	d	}|S )
Nc                   s&   g | ]}| j jjvs|d u r|qS r   )rP   rc   r   )r   r   r   rj   rk   
<listcomp>  s
    z,BaseWindowGroupby._apply.<locals>.<listcomp>r  rA  r   c                   s   g | ]}|  qS rj   )r   r   c)r   rj   rk   rI    s    Fr   r   )level)rF  r  rP   rc   r   r   r?  r   rD  codeslevelsindicesr   r   concatenatelistarrayintpr   re   r%   from_arraysextendr@  reset_indexrange)ri   r  r   r   r  r   r   grouped_object_indexgrouped_index_namegroupby_keysresult_index_namesdrop_columnsrN  rO  group_indicesidxresult_indexrG  )r   ri   rk   r    sJ   




zBaseWindowGroupby._applyr  r	  r
  r  rT   r  c                   s  |j | jjdd}t ||||durltfdd| jj D slt}t	fdd| jj D dd | jj
 D }g }g }	ttt| D ]}
tt|
|}t|\}}|| |	| qOn7| jj}| jj}	| jj }|rtt| ntjg tjd	 |jd
krd
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  rA  Nc                 3  s     | ]}t |t  kV  qd S r   )r   )r   group)r	  rj   rk   r     s    
z4BaseWindowGroupby._apply_pairwise.<locals>.<genexpr>c                   s   g | ]}  | jqS rj   )r   r   rc   )r   
gb_indices)r   rj   rk   rI     s    z5BaseWindowGroupby._apply_pairwise.<locals>.<listcomp>c                 s  s    | ]}t |V  qd S r   )commaybe_make_list)r   pairrj   rj   rk   r   &  s    

r   r   c                   s   g | ]}t | qS rj   )r   repeatr   rJ  )r   	repeat_byrj   rk   rI  C  s    FrL  )rD  r?  r   rF  r  r  rP  r   r   r(   rx   maprR  r   r   rf  rS  r   r   rN  rO  rQ  rT  r   rd   re   rc   r%   r   )ri   r  r	  r  r  r   old_result_lengb_pairsgroupby_codesgroupby_levelsgb_level_pairlabelsrN  rO  r^  result_codesresult_levelsresult_names	idx_codes
idx_levelsr`  rG  )r   r	  rg  r   rk   r    sd   







z!BaseWindowGroupby._apply_pairwiser?   c                   s<   |j stt| jj tj}|	|}t
 ||S )r   )emptyr   rQ  rR  r?  rP  r   r   r   r   rF  r   )ri   rP   r   groupby_orderrG  rj   rk   r   \  s   
zBaseWindowGroupby._create_dataNc                   s*   | j d ur| j| j}t j|||dS )N)r   )rX   rP   	set_indexrM   rF  r   )ri   r   r   r   rG  rj   rk   r   j  s   
zBaseWindowGroupby._gotitem)rP   r   r?  rG   r@  r   r^   r_   r7  )
r  r  r   r]   r   r   r  r  r^   r   r6  r4  r5  r   )ry   r8  r9  r:  r;  rK   rl   r  r  r   r   __classcell__rj   rj   rG  rk   r>    s   
 =Tr>  c                      st  e Zd ZdZg dZ fddZd<d
dZ		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ed!eed"eed#e
d$d%d&d'd(d?d@d)d*Zeeed eeed!eed"eed#e
d+d%d,d-d(d?d@d.d/Zeeed eeed!eed"eed#e
d0d%d1d2d(dAdBd5d6Zeeed eeed!eed"eed#e
d7d%d8d9d(dAdBd:d;Z  ZS )CWindowa  
    Provide rolling window calculations.

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

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

        If a timedelta, str, or 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``, ``closed`` and
        ``step`` 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.

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

        .. deprecated:: 2.1.0

            The axis keyword is deprecated. For ``axis=1``,
            transpose the DataFrame first instead.

    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'``).

    step : int, default None

        .. versionadded:: 1.5.0

        Evaluate the window at every ``step`` result, equivalent to slicing as
        ``[::step]``. ``window`` must be an integer. Using a step argument other
        than None or 1 will produce a result with a different shape than the input.

    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
    -------
    pandas.api.typing.Window or pandas.api.typing.Rolling
        An instance of Window is returned if ``win_type`` is passed. Otherwise,
        an instance of Rolling is returned.

    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

    **step**

    Rolling sum with a window length of 2 observations, minimum of 1 observation to
    calculate a value, and a step of 2.

    >>> df.rolling(2, min_periods=1, step=2).sum()
         B
    0  0.0
    2  3.0
    4  4.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

    **on**

    Rolling sum with a window length of 2 days.

    >>> df = pd.DataFrame({
    ...     'A': [pd.to_datetime('2020-01-01'),
    ...           pd.to_datetime('2020-01-01'),
    ...           pd.to_datetime('2020-01-02'),],
    ...     'B': [1, 2, 3], },
    ...     index=pd.date_range('2020', periods=3))

    >>> df
                        A  B
    2020-01-01 2020-01-01  1
    2020-01-02 2020-01-01  2
    2020-01-03 2020-01-02  3

    >>> df.rolling('2D', on='A').sum()
                        A    B
    2020-01-01 2020-01-01  1.0
    2020-01-02 2020-01-01  3.0
    2020-01-03 2020-01-02  6.0
    	r`   rQ   rS   rU   rW   rX   rZ   r[   r\   c                   s   t    t| jtstd| j tddd}t|| jd | _| jd u r.td| j t| j	t
r8tdt| j	rB| j	dk rFtd| jdkrOtd	d S )
NzInvalid win_type zscipy.signal.windowsz,Scipy is required to generate window weight.)extraz6BaseIndexer subclasses not implemented with win_types.r   &window must be an integer 0 or greaterrN   z+'single' is the only supported method type.)rF  rh   re   rU   r]   rf   r   r   _scipy_weight_generatorr`   r   r   r   r\   )ri   signalrG  rj   rk   rh   |  s$   


zWindow._validater   r}   offsetr   r^   c                 C  s*   |dkrt |dg}t|t| }|S )zT
        Center the result in the window for weighted rolling aggregations.
        r   N)r   r   r   tuple)ri   r   r~  lead_indexerrj   rj   rk   _center_window  s   zWindow._center_windowFrj   r  ,Callable[[np.ndarray, int, int], np.ndarray]r   r]   r   r   r  r  c                   s\   j jfi |jrtd d ndd	 fdd}|||ddj 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,
        numeric_only : bool, default False
            Whether to only operate on bool, int, and float columns
        numba_args : tuple
            unused
        **kwargs
            additional arguments for scipy windows if necessary

        Returns
        -------
        y : type of input
        r   r   r   r   r}   c                   st   | j dkr	|  S  fdd}tjdd t|| }W d    n1 s*w   Y  jr8|}|S )Nr   c                   sB   t t jg }t | |f}  | jd urjS tS r   )r   rS  r   rQ  rQ   r   )r  additional_nansr  r~  ri   r`   rj   rk   r    s   z5Window._apply.<locals>.homogeneous_func.<locals>.calcr  r  )r  r   r   r  asarrayrS   r  r  r  rj   rk   r     s   
	z'Window._apply.<locals>.homogeneous_funcNr  )r|  r`   rS   r   r  r[   r  rj   r  rk   r    s   
zWindow._applyr2  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klassrW   c                 O  s(   t | |||d }|d u r|| }|S )Nr,  )r   r/  r1  rj   rj   rk   r2    s    zWindow.aggregate
ParametersReturnsSee AlsoExamplesa          >>> ser = pd.Series([0, 1, 5, 2, 8])

        To get an instance of :class:`~pandas.core.window.rolling.Window` we need
        to pass the parameter `win_type`.

        >>> type(ser.rolling(2, win_type='gaussian'))
        <class 'pandas.core.window.rolling.Window'>

        In order to use the `SciPy` Gaussian window we need to provide the parameters
        `M` and `std`. The parameter `M` corresponds to 2 in our example.
        We pass the second parameter `std` as a parameter of the following method
        (`sum` in this case):

        >>> ser.rolling(2, win_type='gaussian').sum(std=3)
        0         NaN
        1    0.986207
        2    5.917243
        3    6.903450
        4    9.862071
        dtype: float64
        rollingzweighted window sumsumwindow_methodaggregation_description
agg_methodc                 K     t j}| j|fd|d|S )Nr  r   r   )window_aggregationsroll_weighted_sumr  ri   r   r   window_funcrj   rj   rk   r    s   'z
Window.suma          >>> ser = pd.Series([0, 1, 5, 2, 8])

        To get an instance of :class:`~pandas.core.window.rolling.Window` we need
        to pass the parameter `win_type`.

        >>> type(ser.rolling(2, win_type='gaussian'))
        <class 'pandas.core.window.rolling.Window'>

        In order to use the `SciPy` Gaussian window we need to provide the parameters
        `M` and `std`. The parameter `M` corresponds to 2 in our example.
        We pass the second parameter `std` as a parameter of the following method:

        >>> ser.rolling(2, win_type='gaussian').mean(std=3)
        0    NaN
        1    0.5
        2    3.0
        3    3.5
        4    5.0
        dtype: float64
        zweighted window meanmeanc                 K  r  )Nr  r  )r  roll_weighted_meanr  r  rj   rj   rk   r  4  s   &zWindow.meana          >>> ser = pd.Series([0, 1, 5, 2, 8])

        To get an instance of :class:`~pandas.core.window.rolling.Window` we need
        to pass the parameter `win_type`.

        >>> type(ser.rolling(2, win_type='gaussian'))
        <class 'pandas.core.window.rolling.Window'>

        In order to use the `SciPy` Gaussian window we need to provide the parameters
        `M` and `std`. The parameter `M` corresponds to 2 in our example.
        We pass the second parameter `std` as a parameter of the following method:

        >>> ser.rolling(2, win_type='gaussian').var(std=3)
        0     NaN
        1     0.5
        2     8.0
        3     4.5
        4    18.0
        dtype: float64
        zweighted window variancevarr   ddofc                 K  s2   t tj|d}|dd  | j|fd|d|S )Nr  r   r  r  )r   r  roll_weighted_varpopr  )ri   r  r   r   r  rj   rj   rk   r  e  s   &z
Window.vara          >>> ser = pd.Series([0, 1, 5, 2, 8])

        To get an instance of :class:`~pandas.core.window.rolling.Window` we need
        to pass the parameter `win_type`.

        >>> type(ser.rolling(2, win_type='gaussian'))
        <class 'pandas.core.window.rolling.Window'>

        In order to use the `SciPy` Gaussian window we need to provide the parameters
        `M` and `std`. The parameter `M` corresponds to 2 in our example.
        We pass the second parameter `std` as a parameter of the following method:

        >>> ser.rolling(2, win_type='gaussian').std(std=3)
        0         NaN
        1    0.707107
        2    2.828427
        3    2.121320
        4    4.242641
        dtype: float64
        z"weighted window standard deviationstdc                 K  s   t | jd|d|d|S )Nr  )r  r   r   rj   )r,   r  )ri   r  r   r   rj   rj   rk   r    s   &z
Window.std)r   r}   r~  r   r^   r}   r7  )r  r  r   r]   r   r   r  r  r4  r   r   r   Fr  r   r   r   )ry   r8  r9  r:  rK   rh   r  r  r   r-   r   r2  r/  r2   r.   r/   r0   r3   r4   r  r  r  r  rw  rj   rj   rG  rk   rx  t  s     |
>
&%%%rx  c                   @  s*  e Zd ZdJdKddZ					dLdMddZdNddZ			dOdPddZ			dOdPddZ			dOdPd d!Z			dOdPd"d#Z				dOdPd$d%Z
	&			dQdRd)d*Z	&			dQdRd+d,ZdJdKd-d.ZdSdTd/d0ZdJdKd1d2Z	3	dUdVd8d9Z	:	;		dWdXd@dAZ			&	dYdZdFdGZ			&	dYdZdHdIZdS )[RollingAndExpandingMixinFr   r   c                 C     t j}| j|d|dS )Nr   r  )r  roll_sumr  ri   r   r  rj   rj   rk   r     s   zRollingAndExpandingMixin.countNr  r  r.  engine!Literal['cython', 'numba'] | Noner   r!  r-  tuple[Any, ...] | Noner   dict[str, Any] | Nonec           	      C  s   |d u rd}|d u ri }t |stdd}t|rA|du r"td|}| jdkr5t|fi t||}n%t|fi t||}n|dv rV|d urMtd| ||||}ntd| j|d	|d
S )Nrj   z'raw parameter must be `True` or `False`Fz.raw must be `True` when using the numba enginerN   )cythonNz+cython engine does not accept engine_kwargsz)engine must be either 'numba' or 'cython'r0  )r   r  )	r   rf   r*   r\   r8   r)   r9   _generate_cython_apply_funcr  )	ri   r  r.  r  r   r-  r   r  
apply_funcrj   rj   rk   r0    s@   	
zRollingAndExpandingMixin.applyr  dict[str, Any]bool | np.bool_functionr^   ?Callable[[np.ndarray, np.ndarray, np.ndarray, int], np.ndarray]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d} | |||S )NF)rc   r   )rM   )r   beginr~   rQ   r.  rD   ri   r  rj   rk   r    s   zHRollingAndExpandingMixin._generate_cython_apply_func.<locals>.apply_func)r   rD   r   r  
roll_apply)ri   r-  r   r.  r  r  rj   r  rk   r    s   z4RollingAndExpandingMixin._generate_cython_apply_funcc                 C  \   t |r#| jdkrttj}| j|d||dS ddlm} | ||S t	j
}| j|d|dS )Nrq   Tr.  r  r   r   )sliding_sumr  r  )r*   r\   r7   r   nansumr0  pandas.core._numba.kernelsr  r+  r  r  r  )ri   r   r  r   r  r  r  rj   rj   rk   r       

zRollingAndExpandingMixin.sumc                 C  s`   t |r%| jdkrttj}| j|d||dS ddlm} | j||ddS t	j
}| j|d|dS )	Nrq   Tr  r   sliding_min_maxis_maxmaxr  )r*   r\   r7   r   nanmaxr0  r  r  r+  r  roll_maxr  ri   r   r  r   r  r  r  rj   rj   rk   r       

zRollingAndExpandingMixin.maxc                 C  s`   t |r%| jdkrttj}| j|d||dS ddlm} | j||ddS t	j
}| j|d|d	S )
Nrq   Tr  r   r  Fr  minr  )r*   r\   r7   r   nanminr0  r  r  r+  r  roll_minr  r  rj   rj   rk   r  /  r  zRollingAndExpandingMixin.minc                 C  r  )Nrq   Tr  r   )sliding_meanr  r  )r*   r\   r7   r   nanmeanr0  r  r  r+  r  	roll_meanr  )ri   r   r  r   r  r  r  rj   rj   rk   r  E  r  zRollingAndExpandingMixin.meanc                 C  sL   t |r| jdkrttj}ntj}| j|d||dS tj}| j|d|dS )Nrq   Tr  medianr  )	r*   r\   r7   r   	nanmedianr0  r  roll_median_cr  )ri   r   r  r   r  r  rj   rj   rk   r  [  s   
zRollingAndExpandingMixin.medianr   r  r   c                   s^   t |r| jdkrtdddlm} t| j|| dS tj fdd}| j	|d|d	S )
Nrq   z%std not supported with method='table'r   sliding_varr  c                   s   t | ||| dS )Nr  )r,   )r   r  r~   rQ   r  r  rj   rk   
zsqrt_func  s   z0RollingAndExpandingMixin.std.<locals>.zsqrt_funcr  r  )
r*   r\   r   r  r  r,   r+  r  roll_varr  )ri   r  r   r  r   r  r  rj   r  rk   r  p  s   
zRollingAndExpandingMixin.stdc                 C  sT   t |r| jdkrtdddlm} | j|||dS ttj|d}| j	|d|dS )Nrq   z%var not supported with method='table'r   r  r  r  r  )
r*   r\   r   r  r  r+  r   r  r  r  )ri   r  r   r  r   r  r  rj   rj   rk   r    s   
zRollingAndExpandingMixin.varc                 C  r  )Nskewr  )r  	roll_skewr  r  rj   rj   rk   r       zRollingAndExpandingMixin.skewc                 C  s.   |  d| | j|d| j|d| d S Nsemr         ?r   r  r   powri   r  r   rj   rj   rk   r    s
   
zRollingAndExpandingMixin.semc                 C  r  )Nkurtr  )r  	roll_kurtr  r  rj   rj   rk   r    r  zRollingAndExpandingMixin.kurtlinearqfloatinterpolationr@   c                 C  s@   |dkrt j}n|dkrt j}ntt j||d}| j|d|dS )Ng      ?g        )quantiler  r  r  )r  r  r  r   roll_quantiler  )ri   r  r  r   r  rj   rj   rk   r    s   z!RollingAndExpandingMixin.quantileaverageTr\   rA   	ascendingpctc                 C  s"   t tj|||d}| j|d|dS )N)r\   r  
percentilerankr  )r   r  	roll_rankr  )ri   r\   r  r  r   r  rj   rj   rk   r    s   zRollingAndExpandingMixin.rankr	  r
  r  rT   c                   N   j d ur	tdd| ddlm   fdd}j||||S )Nzstep not implemented for covcovr   r   c                   s   | } |} }jd urjn|j}|jt||jjjd\}}	||t| t
jdd> t|| |||}t||||}	t||||}
tt|| t
j||d}||	|
  ||   }W d    n1 szw   Y   || j| jddS )Nr   r  r  r   Fr   )r   r   rQ   r   rv   r   rS   rZ   r[   r   r   r  r  r  r  r   r   r   rc   r   )r  yx_arrayy_arrayr  rQ   r|   r~   mean_x_ymean_xmean_y	count_x_yr   rD   r  ri   rj   rk   cov_func  s6   




z.RollingAndExpandingMixin.cov.<locals>.cov_funcr[   r   r   r   rD   r  r   )ri   r	  r  r  r   r  rj   r  rk   r    s   
zRollingAndExpandingMixin.covc                   r  )Nzstep not implemented for corrcorrr   r   c                   sJ   | } |} }jd urjn|j}|jt||jjjd\}}	||t| t
jddZ t|| |||}t||||}	t||||}
tt|| t
j||d}t||||}t||||}||	|
  ||   }|| d }|| }W d    n1 sw   Y   || j| jddS )Nr   r  r  r   r  Fr   )r   r   rQ   r   rv   r   rS   rZ   r[   r   r   r  r  r  r  r   r   r   r  rc   r   )r  r  r  r  r  rQ   r|   r~   r  r  r  r  x_vary_var	numeratordenominatorr   r  rj   rk   	corr_func  sJ   








z0RollingAndExpandingMixin.corr.<locals>.corr_funcr  )ri   r	  r  r  r   r  rj   r  rk   r    s   
(zRollingAndExpandingMixin.corrr4  r  FNNNNr  r  r.  r   r  r  r   r!  r-  r  r   r  )
r-  r  r   r  r.  r  r  r  r^   r  FNNr   r   r  r  r   r!  r   FNNr  r   r   r   r  r  r   r!  r  r  r  Fr  r  r  r@   r   r   r  TFFr\   rA   r  r   r  r   r   r   NNr   Fr	  r
  r  rT   r  r   r   r   )ry   r8  r9  r   r0  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  rj   rj   rj   rk   r    sx    
+1r  c                      s  e Zd ZU g dZded<  fddZddd	Zdd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ede
dddddddd dd fd$d%Zeeedeedeedeede
d&dd'd(d 	!	)	)	)	)dd fd5d6Zeeedee edeedeed7eede
d8ddddd9d9d 	!	)	)dd fd:d;Zeeedee edeedeed7eede
d<dd=d>d 	!dd)d)d?d fd@dAZeeedee edeedeed7eede
dBdddddCdDd 	!	)	)dd fdEdFZeeedee edeedeed7eede
dGdddddHdHd 	!	)	)dd fdIdJZeeedee edeedeed7eede
dKdddddLdLd 	!	)	)dd fdMdNZeeede
dOdddeedPedeeddQeed7e
dRdddede
dSdddddTdUd 		!	)	)dd fdXdYZeeede
dOdddeedPedeeddZeed7e
d[dddede
d\ddddd]d^d 		!	)	)dd fd_d`Zeeedeedeeddaeed7e
dbede
dcdddded dd fdfdgZeeede
dOdddeedeedeed7dhede
didddddjdkd dddldmZ eeedeedeeddneed7doede
dpdddddqdrd dd fdsdtZ!eeede
dudddeedeedeede
dvdddddwdwd e"dwdxdy	z	!dd fd~dZ#eedede
ddddeedeedeede
dddddddd 			!	!dd fddZ$eeede
ddddeedeedeede
ddddd 	)	)		!dd 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d7e
ddddede
dddddddd 	)	)		!dd fddZ&  Z'S )Rollingry  rJ   rK   c              
     sV  t    | jjs t| jtttfs t| jj	t
r| jj	jdv rt| jtttfr|   zt| j}W n ttfyL } z
td| j d|d }~ww t| jtrb|j| jjj| jjj  | _nzt| jj	}W n tyu   d}Y nw t|j|j| _| jd u rd| _| jd urtdd S t| jtrd S t | jr| jdk rtdd S )	Nr   zpassed window z, is not compatible with a datetimelike indexnsr   z,step is not supported with frequency windowsr   r{  )!rF  rh   rP   rt  re   rM   r#   r'   r&   r   r   r   r`   r]   r
   r    _validate_datetimelike_monotonicr   rr   rf   nanosfreqnrb   rH   r   as_unit_valuerQ   r[   r   r   r   )ri   r  r   unitrG  rj   rk   rh   L  sV   


zRolling._validater^   r_   c                 C  s8   | j jr	| d | j js| j js| d dS dS 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)rM   hasnans_raise_monotonic_erroris_monotonic_increasingis_monotonic_decreasingr   rj   rj   rk   r  |  s
   
z(Rolling._validate_datetimelike_monotonicmsgr]   c                 C  s4   | j }|d u r| jdkrd}nd}t| d| )Nr   rc   column )rX   rW   rf   )ri   r  rX   rj   rj   rk   r    s   
zRolling._raise_monotonic_errorr2  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  c                   s   t  j|g|R i |S r   )rF  r2  )ri   r  r-  r   rG  rj   rk   r2    s   &zRolling.aggregater  r  r  r  a  
        >>> s = pd.Series([2, 3, np.nan, 10])
        >>> s.rolling(2).count()
        0    NaN
        1    2.0
        2    1.0
        3    1.0
        dtype: float64
        >>> s.rolling(3).count()
        0    NaN
        1    NaN
        2    2.0
        3    2.0
        dtype: float64
        >>> s.rolling(4).count()
        0    NaN
        1    NaN
        2    NaN
        3    3.0
        dtype: float64
        
r   r  zcount of non NaN observationsr   r  Fr   r   c                   s   t  |S r   )rF  r   ri   r   rG  rj   rk   r     s   %zRolling.countz        >>> ser = pd.Series([1, 6, 5, 4])
        >>> ser.rolling(2).apply(lambda s: s.sum() - s.min())
        0    NaN
        1    6.0
        2    6.0
        3    5.0
        dtype: float64
        zcustom aggregation functionr0  Nr  r  r.  r  r  r   r!  r-  r  r   r  c                   s   t  j||||||dS )N)r.  r  r   r-  r   )rF  r0  )ri   r  r.  r  r   r-  r   rG  rj   rk   r0    s   !zRolling.apply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  c                      t  j|||dS N)r   r  r   )rF  r  ri   r   r  r   rG  rj   rk   r  
  s
   EzRolling.sumz        >>> ser = pd.Series([1, 2, 3, 4])
        >>> ser.rolling(2).max()
        0    NaN
        1    2.0
        2    3.0
        3    4.0
        dtype: float64
        maximumr  )r  r   c                  r  r   )rF  r  )ri   r   r  r   r-  r   rG  rj   rk   r  U  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                   r  r   )rF  r  r!  rG  rj   rk   r  ~  
   $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                   r  r   )rF  r  r!  rG  rj   rk   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
        r  c                   r  r   )rF  r  r!  rG  rj   rk   r    r$  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.
z
        The default ``ddof`` of 1 used in :meth:`Series.std` is different
        than the default ``ddof`` of 0 in :func:`numpy.std`.

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

        a
  
        >>> s = pd.Series([5, 5, 6, 7, 5, 5, 5])
        >>> s.rolling(3).std()
        0         NaN
        1         NaN
        2    0.577350
        3    1.000000
        4    1.000000
        5    1.154701
        6    0.000000
        dtype: float64
        zstandard deviationr  r  r   c                      t  j||||dS N)r  r   r  r   )rF  r  ri   r  r   r  r   rG  rj   rk   r  	     4zRolling.stdz/numpy.var : Equivalent method for NumPy array.
z
        The default ``ddof`` of 1 used in :meth:`Series.var` is different
        than the default ``ddof`` of 0 in :func:`numpy.var`.

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

        a
  
        >>> s = pd.Series([5, 5, 6, 7, 5, 5, 5])
        >>> s.rolling(3).var()
        0         NaN
        1         NaN
        2    0.333333
        3    1.000000
        4    1.000000
        5    1.333333
        6    0.000000
        dtype: float64
        variancer  c                   r%  r&  )rF  r  r'  rG  rj   rk   r  >	  r(  zRolling.varz:scipy.stats.skew : Third moment of a probability density.
zV
        A minimum of three periods is required for the rolling calculation.

        z        >>> ser = pd.Series([1, 5, 2, 7, 15, 6])
        >>> ser.rolling(3).skew().round(6)
        0         NaN
        1         NaN
        2    1.293343
        3   -0.585583
        4    0.670284
        5    1.652317
        dtype: float64
        zunbiased skewnessr  c                      t  j|dS Nr  )rF  r  r  rG  rj   rk   r  y	  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  c                 C  s,   |  d| | j|d| || d S r  r  r  rj   rj   rk   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                   r*  r+  )rF  r  r  rG  rj   rk   r  	  s   &zRolling.kurta  
        quantile : float
            Quantile to compute. 0 <= quantile <= 1.

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

                * linear: `i + (j - i) * fraction`, where `fraction` is the
                  fractional part of the index surrounded by `i` and `j`.
                * lower: `i`.
                * higher: `j`.
                * nearest: `i` or `j` whichever is nearest.
                * midpoint: (`i` + `j`) / 2.
        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  )old_arg_namenew_arg_namer  r  r  r@   c                   r  )N)r  r  r   )rF  r  )ri   r  r  r   rG  rj   rk   r  	  s
   9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\   rA   r  r  c                   r%  )N)r\   r  r  r   )rF  r  )ri   r\   r  r  r   rG  rj   rk   r  ,
  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        >>> ser1 = pd.Series([1, 2, 3, 4])
        >>> ser2 = pd.Series([1, 4, 5, 8])
        >>> ser1.rolling(2).cov(ser2)
        0    NaN
        1    1.5
        2    0.5
        3    1.5
        dtype: float64
        zsample covariancer  r	  r
  r  rT   c                   r%  N)r	  r  r  r   )rF  r  ri   r	  r  r  r   rG  rj   rk   r  w
  s   1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.

        ax  
        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]
        >>> np.corrcoef(v1[:-1], v2[:-1])
        array([[1.        , 0.33333333],
               [0.33333333, 1.        ]])
        >>> np.corrcoef(v1[1:], v2[1:])
        array([[1.       , 0.9169493],
               [0.9169493, 1.       ]])
        >>> 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.]])
        >>> np.corrcoef(matrix[:-1, 0], matrix[:-1, 1])
        array([[1.       , 0.6263001],
               [0.6263001, 1.       ]])
        >>> np.corrcoef(matrix[1:, 0], matrix[1:, 1])
        array([[1.        , 0.55536811],
               [0.55536811, 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
        correlationr  c                   r%  r.  )rF  r  r/  rG  rj   rk   r  
  s   ~zRolling.corrr3  )r  r]   r4  r  r  r   r  r  r  r  r  r  r  r  r  r  r	  r
  )(ry   r8  r9  rK   r;  rh   r  r  r   r-   r   r2  r/  r2   r.   r/   r3   r4   replacer   r6   r0  r5   r1   r  r  r  r  r  r  r  r  r  r  r   r  r  r  r  rw  rj   rj   rG  rk   r  ?  sN  
 
0

	%
$
.A
 
'
 


/


/!


!
%


2

?
,



:yr  c                   @  s.   e Zd ZdZejej Zd	ddZdd ZdS )
RollingGroupbyz3
    Provide a rolling groupby implementation.
    r^   r!   c                 C  s   d}| j }t| jtr't| j}| jj }t|tsJ |dd | j}n| j	dur2t
}| 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   groupby_indicesr  indexer_kwargs)r   re   r`   r   rs   __dict__r   dictr  rb   r"   r    r!   r?  rP  )ri   r4  r   rolling_indexerr`   r  rj   rj   rk   r   ?  s*   	

z"RollingGroupby._get_window_indexerc                 C  sj   | j jr	| d | jj D ]#}| j |}|js2|js2| j	du r$dn| j	}t
d| d| dqdS )zC
        Validate that each group in self._on is monotonic
        r  Nrc   zEach group within z' must be monotonic. Sort the values in z first.)rM   r  r  r?  rP  r   r   r  r  rX   rf   )ri   r^  group_onrX   rj   rj   rk   r  b  s    
z/RollingGroupby._validate_datetimelike_monotonicN)r^   r!   )	ry   r8  r9  r:  r  rK   r>  r   r  rj   rj   rj   rk   r2  8  s
    
#r2  )yr:  
__future__r   r   datetimer   	functoolsr   rt   textwrapr   typingr   r   r   r	   numpyr   pandas._libs.tslibsr
   r   r    pandas._libs.window.aggregations_libsr`   aggregationsr  pandas.compat._optionalr   pandas.errorsr   pandas.util._decoratorsr   r   pandas.core.dtypes.commonr   r   r   r   r   pandas.core.dtypes.dtypesr   pandas.core.dtypes.genericr   r   pandas.core.dtypes.missingr   pandas.core._numbar   pandas.core.algorithmsr   pandas.core.applyr   pandas.core.arraysr   pandas.core.baser   pandas.core.commoncorecommonrc  pandas.core.indexers.objectsr   r    r!   r"   pandas.core.indexes.apir#   r$   r%   r&   r'   pandas.core.reshape.concatr(   pandas.core.util.numba_r)   r*   pandas.core.window.commonr+   r,   pandas.core.window.docr-   r.   r/   r0   r1   r2   r3   r4   r5   r6   pandas.core.window.numba_r7   r8   r9   collections.abcr:   r;   r<   pandas._typingr=   r>   r?   r@   rA   rB   r   rC   rD   pandas.core.genericrE   rC  rG   pandas.core.arrays.datetimelikerH   rI   r>  rx  r  r  r2  rj   rj   rj   rk   <module>   s    0 	    7 J    J          }