
    Pi                   t   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
mZmZmZ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c mc 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( ddl)m*Z* ddl+m,Z,m-Z- ddl.m/Z/ ddl0m1Z1 ddl2m3Z3 ddl4m5Z5m6Z6 ddl7m8Z8 ddl9m:Z: ddl;m<c m=Z> ddl?m@Z@mAZAmBZBmCZC ddlDmEZEmFZFmGZGmHZHmIZI ddlJmKZK ddlLmMZMmNZNmOZO ddlPmQZQmRZR ddlSmTZTmUZUmVZV e
r8ddlWmXZX ddlWmYZYmZZZm[Z[ ddl\m]Z]m^Z^m_Z_m`Z`maZambZbmcZcmdZd ddlemfZfmgZg ddlhmiZi ddljmkZk dd llmmZm  G d! d"e:          Zn G d# d$en          Zo e"d%           G d& d'en                      Zp G d( d)en          Zq e"d%           G d* d+eq                      Zrepj         er_          e"d%           G d, d-eoer                      ZsdS ).zc
Provide a generic structure to support window functions,
similar to how we have a Groupby object.
    )annotationsN)	timedelta)partial)TYPE_CHECKINGAnyConcatenateLiteralSelfcastfinaloverload)
BaseOffset	Timedelta	to_offset)import_optional_dependency)	DataError)
set_module)ensure_float64is_bool
is_integeris_numeric_dtypeneeds_i8_conversion)
ArrowDtype)ABCDataFrame	ABCSeries)notna)executor)	factorize)ResamplerWindowApplyreconstruct_func)ExtensionArray)SelectionMixin)BaseIndexerFixedWindowIndexerGroupbyIndexerVariableWindowIndexer)DatetimeIndexIndex
MultiIndexPeriodIndexTimedeltaIndex)concat)get_jit_argumentsmaybe_use_numbaprepare_function_arguments)flex_binary_momentzsqrt)'generate_manual_numpy_nan_agg_with_axisgenerate_numba_apply_funcgenerate_numba_table_func)Callable)HashableIteratorSized)	ArrayLikeNDFrameTQuantileInterpolationPTimeUnitTWindowingRankTypenpt)	DataFrameSeries)NDFrameBaseGrouper)dtype_to_unitc                  P   e Zd ZU dZg Zded<    e            Zded<   ded<   	 	 	 	 	 	 	 	 dXdddYdZdZdZ	d[d#Z
d\d]d'Zd^d+Zd_d-Zd`dad.Zd\d/Zdbd1Zd2 Zdcd3Zddd5Zded8Zdfd:Zedgd<            Zdhd>Zdid@Z	 d\djdDZ	 d`dkdFZ	 	 dldmdGZdndNZ	 	 dodpdSZ	 d\dqdVZd\dWZ e Z!dS )r
BaseWindowz7Provides utilities for performing windowing operations.	list[str]_attributeszfrozenset[Hashable]
exclusionsr(   _onNFsingle)	selectionobjrC   min_periods
int | Nonecenterbool | Nonewin_type
str | Noneonstr | Index | NoneclosedstepmethodstrreturnNonec
                  || _         || _        || _        || _        || _        || _        || _        || _        |	| _        d | _	        | j        | j         j
        | _        nt          | j        t                    r| j        | _        njt          | j         t                    r8| j        | j         j        v r%t          | j         | j                           | _        nt!          d| j         d          |
| _        |                                  d S )Nzinvalid on specified as z3, must be a column (of DataFrame), an Index or None)rO   rV   rX   rY   windowrP   rR   rT   rZ   _win_freq_i8indexrL   
isinstancer(   r   columns
ValueError
_selection	_validate)selfrO   r_   rP   rR   rT   rV   rX   rY   rZ   rN   s              n/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/pandas/core/window/rolling.py__init__zBaseWindow.__init__{   s    	& (,7?x~DHH'' 	wDHH,// 	DGtx?O4O4OTXdg.//DHHD47 D D D  
 $    c                V   | j         #t          | j                   st          d          | j        t	          | j                  st          d          | j        dk     rt          d          t	          | j                  r/| j        | j        k    rt          d| j         d| j                   | j        | j        dvrt          d          t          | j        t          t          f          st          d	t          |                      t          | j        t                    rt          j        | j        j                  j                                        }t          j        t                      j                  j                                        }||k    r)t          t          | j                  j         d
          | j        dvrt          d          | j        =t	          | j                  st          d          | j        dk     rt          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)tablerM   z!method must be 'table' or 'singlezstep must be an integerzstep must be >= 0)rR   r   rd   rP   r   r_   rX   rb   rO   r   r   	TypeErrortyper#   inspect	signatureget_window_bounds
parameterskeys__name__rZ   rY   )rg   get_window_bounds_signatureexpected_signatures      rh   rf   zBaseWindow._validate   s=   ;"74;+?+?"7888'd.// C !ABBB!## !;<<<$+&& 4+;dk+I+I U4#3UUUU   ;"t{ ;
 (
 (
 RSSS$(Y$=>> 	;9T$ZZ99:::dk;// 	 +2*;-+ + ( ")!2/" "  +.@@@ DK((1 C C C   ;111@AAA9 di(( < !:;;;y1}} !4555	 !  }rj   start
np.ndarrayendnum_valsintc           	     P   t          |          t          |          k    r0t          dt          |           dt          |           d          t          |          || j        pdz   dz
  | j        pdz  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)lenrd   rY   )rg   r{   r}   r~   s       rh   _check_window_boundszBaseWindow._check_window_bounds   s     u::S!!#e**  S      u::(din159ty~ANNN+U + +"*+ +CG9+ + +   ONrj   ra   resultSized | Nonec                j    | t          |          t          |          k    r|n|dd| j                 S )zJ
        Slices the index for a given result and the preset step.
        N)r   rY   )rg   ra   r   s      rh   _slice_axis_for_stepzBaseWindow._slice_axis_for_step   s;     ~VE

!:!: E||$)|$	
rj   namenumeric_onlyboolc                    | j         j        dk    rB|rBt          | 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NotImplementedErrorrr   rx   )rg   r   r   s      rh   _validate_numeric_onlyz!BaseWindow._validate_numeric_only   sx     #q(( )$T%7%=>> ) &::&OOOOO  	 )(((((rj   r:   c                8    |                     dgdg          }|S )zSubset DataFrame to numeric columns.

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

        Returns
        -------
        obj subset to numeric-only columns.
        numberr   )includeexclude)select_dtypes)rg   rO   r   s      rh   _make_numeric_onlyzBaseWindow._make_numeric_only   s%     ""H:}"MMrj   c                   | j         [t          | j         t                    sA|j        dk    r6|                    |j                            | j         gd                    }|j        dk    r|r|                     |          }|S )A
        Split data into blocks & return conformed data.
        N   F)sort)rc   r   )rV   rb   r(   r   reindexrc   
differencer   )rg   rO   r   s      rh   _create_datazBaseWindow._create_data  s{    
 7z$'5'A'AchRSmm++ck&<&<dgYU&<&S&S+TTC8a<<L<))#..C
rj   c                     | j         } f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                2    i | ]}|t          |          S  getattr).0attrrg   s     rh   
<dictcomp>z'BaseWindow._gotitem.<locals>.<dictcomp>%  s%    III$d++IIIrj   rN   )rO   rJ   _infer_selectionrr   )rg   keyr   subsetkwargsrN   new_wins   `      rh   _gotitemzBaseWindow._gotitem  sl     >XF JIII8HIII))#v66	$t**VCCyCFCCrj   r   c                    || 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__rO   AttributeErrorrr   rx   )rg   r   s     rh   __getattr__zBaseWindow.__getattr__+  sn    4+++**466648:GT

#GGGGG
 
 	
rj   c                4    | j                                         S N)rO   _dir_additionsrg   s    rh   r   zBaseWindow._dir_additions5  s    x&&(((rj   c                      fd j         D             }d                    |          }t                     j         d| dS )z@
        Provide a nice str repr of our rolling object.
        c              3  |   K   | ]6}t          |d           |d         dk    | dt          |           V  7d S )Nr   _=r   )r   	attr_namerg   s     rh   	<genexpr>z&BaseWindow.__repr__.<locals>.<genexpr><  sg       
 
tY--9ilc>Q>Q 55743355>Q>Q>Q>Q
 
rj   ,z [])rJ   joinrr   rx   )rg   
attrs_listattrss   `  rh   __repr__zBaseWindow.__repr__8  sa    
 
 
 
!-
 
 


 $$t**%111111rj   r7   c              #    K   | j                             | j                  }|                     |          }|                                 }|                    t          |          | j        | j        | j	        | j
                  \  }}|                     ||t          |                     t          ||d          D ]$\  }}|j        t          ||                   }|V  %d S )N
num_valuesrP   rR   rX   rY   T)strict)r   set_axisrL   r   _get_window_indexerru   r   rP   rR   rX   rY   r   zipilocslice)rg   rO   indexerr{   r}   ser   s           rh   __iter__zBaseWindow.__iter__D  s       ))$(33$$**,,..3xx(;; / 
 

s 	!!%c#hh777s4000 	 	DAqXeAqkk*FLLLL	 	rj   valuesr9   c                   t          |j                  r-t          dt          |           j         d|j         d          	 t          |t                    r,|                    t          j	        t          j
                  }nt          |          }n1# t          t          f$ r}t          d|j                   |d}~ww xY wt          j        |          }|                                r t          j        |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   rr   rx   rb   r!   to_numpynpfloat64nanr   rd   rq   isinfanywhere)rg   r   errinfs       rh   _prep_valueszBaseWindow._prep_valuesV  s   v|,, 	%<4::. < << < <  	S&.11 0bfEE'//I& 	S 	S 	SH&,HHIIsR	S hv7799 	3Xc26622Fs   AB C%B==CrA   c                   ddl m} | j        | j                            |j                  s| j        j        } || j        | j        j        |d          }||j        v r|||<   d S ||j        j	        v rd S || j
        j        v rm| j
        j        }|j        }|                    |          }|                    |d |                   }	t          |	          }
|                    |
||           d S |||<   d S d S d S )Nr   rB   Fra   r   copy)pandasrB   rV   rL   equalsra   r   rO   rc   namesr   get_locintersectionr   insert)rg   r   rO   rB   r   	extra_colold_colsnew_colsold_locoverlapnew_locs              rh   _insert_on_columnzBaseWindow._insert_on_columnn  s    	"!!!!!7txsy'A'A8=Dtxtx~DuUUUIv~%%(t++++333-5!>"**400"//'0BCCg,,gtY77777  )t% rj   npt.NDArray[np.int64] | Nonec                   t          | j        t          t          t          f          r| j        j        S t          | j        j        t                    r8| j        j        j        dv r%| j        	                    t          j                  S d S )NmMr   )rb   rL   r*   r'   r+   asi8r   r   kindr   r   int64r   s    rh   _index_arrayzBaseWindow._index_array  sp     dhm^ LMM 	58= 
33 	58Kt8S8S8$$28$444trj   outc                    |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   astyper   )rg   r   rO   s      rh   _resolve_outputzBaseWindow._resolve_output  sp    9Q<11!1!1;<<<9Q<1::i(((sC(((
rj   r#   c                    t          | j        t                    r| j        S | j        !t	          | j        | j        | j                  S t          | j                  S )z[
        Return an indexer class that will compute the window start and end bounds
        N)index_arraywindow_sizerR   )r   )rb   r_   r#   r`   r&   r   rR   r$   r   s    rh   r   zBaseWindow._get_window_indexer  sf     dk;// 	;(( - -{   
 "dk::::rj   homogeneous_funcCallable[..., ArrayLike]rB   c                   |                      | j                  }|dk    r't          |                              t                    }	 |                     |j                  }n)# t          t          f$ r}t          d          |d}~ww xY w ||          }| 
                    |j        |          }|                    |||j                  S )z5
        Series version of _apply_columnwise
        countr   Nra   r   )r   r   r   r   r   r   _valuesrq   r   r   r   ra   _constructorr   )rg   r   r   rO   r   r   r   ra   s           rh   _apply_serieszBaseWindow._apply_series  s      2337??**##C((C	F&&s{33FF./ 	F 	F 	F;<<#E	F "!&))))#)V<<e#(CCCs   	A$ $B
5BB
DataFrame | Seriesc                   |                      ||           | j        j        dk    r|                     ||          S |                     | j        |          }|dk    rEt          |                              t                    }|j        	                                |_        g }g }t          |                                          D ]\  }}	 |                     |          }n1# t          t          f$ r}	t          d|j                   |	d}	~	ww xY w ||          }
|                    |
           |                    |           |                     |j        t)          |          dk    r|d         nd          }t+          |                              |||j                            |          d          }|                     ||          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)ra   rc   verify_integrity)r   r   r   r  r   r   r   r   _mgrconsolidate	enumerate_iter_column_arraysr   rq   r   r   r   appendr   ra   r   rr   _from_arraysrc   taker   )rg   r   r   r   rO   taker
res_valuesiarrr   resra   dfs                rh   _apply_columnwisezBaseWindow._apply_columnwise  s    	##D,777"a''%%&6=== 2LAA7??**##C((Cx++--CH
 7 7 9 9:: 	 	FAs'',,23   E#)EE  #"3''Cc"""LLOOOO))IJ!(;(;z!}}
 
 #YY##K$$U++"	 $ 
 
 ##B,,,s   C$$D5DDc                   | j         j        dk    rt          d          |                     | j         |          }|                     |                                          } ||          }|                     |j        |          }|j        d         t          |j
                  k    r|j
        n|j
        dd| j                 }|                    |||          }	|                     |	|          S )zT
        Apply the given function to the DataFrame across the entire object
        r   z1method='table' not applicable for Series objects.Nra   rc   )r   r   rd   r   r   r   r   ra   r   r   rc   rY   r  r   )
rg   r   r   r   rO   r   r   ra   rc   r   s
             rh   _apply_tablewisezBaseWindow._apply_tablewise  s     "a''PQQQ 2LAA""3<<>>22!!&))))#)V<< |A#ck"2"222 KK\\	\* 	
 vUGDD##C---rj   targetotherDataFrame | Series | NonepairwisefuncFCallable[[DataFrame | Series, DataFrame | Series], DataFrame | Series]c                   |                      ||          }|	|}|dn|}nMt          |t          t          f          st	          d          |j        dk    r|r|                     |          }t          |||t          |                    S )]
        Apply the given pairwise function given 2 pandas objects (DataFrame/Series)
        NTz#other must be a DataFrame or Seriesr   )r  )	r   rb   r   r   rd   r   r   r0   r   )rg   r  r  r  r   r   s         rh   _apply_pairwisezBaseWindow._apply_pairwise  s     ""6<88=E'/ttXHHEL)#<== 	3BCCCZ1___++E22E!&%XOOOOrj   r   Callable[..., Any]
numba_argstuple[Any, ...]c                                                        j         j        nj        d f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                    | j         dk    r|                                 S fd}t          j        d          5   ||           }d d d            n# 1 swxY w Y   |S )Nr   c                                         t          |           j        j        j                  \  }}                    ||t          |                       | ||gR  S )Nr   )ru   r   rR   rX   rY   r   )xr{   r}   r   rP   r&  rg   window_indexers      rh   calcz9BaseWindow._apply.<locals>.homogeneous_func.<locals>.calcA  sz    +=="1vv +;; >  
s ))%c!ff===tAuc;DDDDDrj   ignoreall)sizer   r   errstate)r   r-  r   r   rP   r&  rg   r,  s      rh   r   z+BaseWindow._apply.<locals>.homogeneous_func;  s     {a{{}}$
E 
E 
E 
E 
E 
E 
E 
E 
E *** & &f& & & & & & & & & & & & & & & Ms   AAArM   r   r|   )r   rP   r   rZ   r  r  )	rg   r   r   r   r&  r   r   rP   r,  s	   ``  `  @@rh   _applyzBaseWindow._apply  s    4 1133 + + 		 	 	 	 	 	 	 	 	 	. ;(""))*:D,OOO(()94NNNrj   engine_kwargsdict[str, bool] | Nonec                   |                                  }| j        | j        n|j        }|                     | j                  }|                     |                                          }|j        dk    r|                    dd          }|	                    t          |          || j        | j        | j                  \  }}	|                     ||	t          |                     t          j        }
t          j        ||
fddit%          |          } ||j        f||	|d|j        }|                     |j        |          }|j        dk    r3|                                }|                    |||j                  }|S |                     |j        |j                  }|                    |||          }|                     ||          S )	Nr   r   is_grouped_kernelF)r{   r}   rP   r  r  )r   rP   r   r   r   r   r   r   reshaperu   r   rR   rX   rY   r   r   float_dtype_mappinggenerate_shared_aggregatorr-   r>   r   ra   squeezer  r   rc   r   )rg   r   r5  func_kwargsr,  rP   rO   r   r{   r}   dtype_mapping
aggregatorr   ra   r   rc   s                   rh   _numba_applyzBaseWindow._numba_applyW  s    1133 + + 	
  233""3<<>>22;!^^B**F#556{{#;; 6 
 

s 	!!%c&kk:::
 !48
 
 $
  ..	
 

 H
!s
 
GR
 

 	 ))#)V<<8q==^^%%F""6SX"FFCJ//VXFFG""6"HHC''S111rj   c                   t          |fi |\  }}}}t          | |||                                          }t          |t                    r|r|j        d d |f         }||_        ||                     |d||          S |S )Nargsr   F)rawrD  r   )r    r   aggrb   r   r   rc   apply)rg   r   rD  r   
relabelingrc   orderr   s           rh   	aggregatezBaseWindow.aggregate  s    +;D+K+KF+K+K(
D'5%dDtFKKKOOQQfl++ 	%
 	%[E*F$FN>::dD:HHHrj   )NNFNNNNrM   )rO   rC   rP   rQ   rR   rS   rT   rU   rV   rW   rX   rU   rY   rQ   rZ   r[   r\   r]   r\   r]   )r{   r|   r}   r|   r~   r   r\   r]   r   )ra   r(   r   r   r\   r(   )r   r[   r   r   r\   r]   )rO   r:   r\   r:   FrO   r:   r   r   r\   r:   )r   r[   )r\   r[   )r\   r7   )r   r9   r\   r|   )r   rA   rO   rA   r\   r]   )r\   r   )r   rA   rO   rA   r\   rA   )r\   r#   )r   r  r   rU   r\   rB   )r   r  r   r[   r   r   r\   r  )NF)r   r  r   rU   r   r   r\   r  r  r  r  r  r  rS   r   r!  r   r   r\   r  Fr   )r   r%  r   r[   r   r   r&  r'  )r   r%  r5  r6  )"rx   
__module____qualname____doc__rJ   __annotations__	frozensetrK   ri   rf   r   r   r   r   r   r   r   r   r   r   r   r   propertyr   r   r   r  r  r  r$  r4  rA  rJ  rF  r   rj   rh   rH   rH   t   s        AAK&/ikkJ1111JJJ
 "&##!%!% % % % % % %N)6 )6 )6 )6V   
 
 
 
 
   (   	 	 	 	 	   0
 
 
 
) ) )
2 
2 
2 
2   $   0) ) ) )2    X   ; ; ; ; NRD D D D D0 #	-- -- -- -- --d  "	. . . . .0P P P P6 #&(;O ;O ;O ;O ;O@ 15.2 .2 .2 .2 .2`    CCCrj   rH   c                       e Zd ZU dZded<   ded<   dgZded<   dd	d$ fdZ	 	 d%d& fdZd' fdZd(d) fd!Z	d* fd#	Z
 xZS )+BaseWindowGroupbyz3
    Provide the groupby windowing facilities.
    rE   _grouperr   	_as_indexrI   rJ   T)rY  rO   r  r\   r]   c               2   ddl m} t          ||          st          d          || _        || _        |                    | j        j        d          }|                    d          t          d           t                      j        |g|R i | d S )Nr   rD   zMust pass a BaseGrouper object.r.  rc   errorsrY   z step not implemented for groupby)pandas.core.groupby.opsrE   rb   rd   rX  rY  dropr   getr   superri   )rg   rO   rX  rY  rD  r   rE   	__class__s          rh   ri   zBaseWindowGroupby.__init__  s     	877777(K00 	@>??? " hht}28hDD::f)%&HIII.t...v.....rj   Fr   r   r%  r   r[   r   r&  r'  c           	     b     t                      j        ||||fi |} j        j        }g |j        }t          j         j        j                  }	|	|z   }
 fd j        j        D             }t          |          t          |	          k    r|                    |d          } j        j	        }t          j         j        j
                  } j        j                                        }|r"t          j        t          |                    n t          j        g t          j                  fd|D             }||                              }t'          |t(                    st)          j        |g          }|                    t          |j	                             |                    t          |j
                             t)          |||
d          }||_         j        s=|                    t          t3          t          |	                                        }|S )	Nc                >    g | ]}|j         j        j        vs||S r   )rO   ra   r   )r   r   rg   s     rh   
<listcomp>z,BaseWindowGroupby._apply.<locals>.<listcomp>  s7     
 
 
$(....#+ 2=++rj   r.  r[  r   c                :    g | ]}|                               S r   )r  )r   cr   s     rh   rd  z,BaseWindowGroupby._apply.<locals>.<listcomp>  s#    000Q000rj   Fr   r
  )level)r`  r4  rO   ra   r   r   rX  r   r^  codeslevelsindicesr   r   concatenatelistarrayintpr  rb   r)   from_arraysextendrY  reset_indexrange)rg   r   r   r   r&  r   r   grouped_object_indexgrouped_index_namegroupby_keysresult_index_namesdrop_columnsri  rj  group_indicesidxresult_indexr   ra  s   `                @rh   r4  zBaseWindowGroupby._apply  s1     	
 

 
 
  $x~:39:y!455),>>
 
 
 
}*
 
 
 |L 1 111[[h[GGF#4=/00-4466 	2nT-%8%899GGhr111G0000%000  +&++G44Cc:.. 4 ,cU33LLci)))MM$sz**+++!E!3e
 
 
 $~ 	N''d5\9J9J3K3K.L.L'MMFrj   r  r  r  r  rS   r!  c                   |                     | j        j        d          }t                                          ||||          /t          fd| j        j                                        D                       st                    }t          fd| j        j                                        D                       d | j        j        
                                D             }g }g }	t          t          t          |ddi          D ]e}
t          j        t          j        |
          |          }t#          |          \  }}|                    |           |	                    |           fn| j        j        }| j        j        }	| j        j                                        }|r"t          j        t          |                    n t          j        g t          j        	          |j        d
k    rd
nt          |j                  fd|D             }t3          j        t6                    rLt          j        j                  }t          j        j                  }t          j        j                  }n*t#          j                  \  }}|g}|g}j        j        g}||z   }|	|z   }| j        j        |z   }t7          |||d          }|_        S )r#  r.  r[  Nc              3  X   K   | ]$}t          |          t                    k    V  %d S r   )r   )r   groupr  s     rh   r   z4BaseWindowGroupby._apply_pairwise.<locals>.<genexpr>   sE       )
 )
).CJJ#e**$)
 )
 )
 )
 )
 )
rj   c                j    g | ]/}                     |                              j                  0S r   )r  r   ra   )r   
gb_indicesr   s     rh   rd  z5BaseWindowGroupby._apply_pairwise.<locals>.<listcomp>	  sE       " KK
++33FLAA  rj   c              3  >   K   | ]}t          j        |          V  d S r   )commaybe_make_list)r   pairs     rh   r   z4BaseWindowGroupby._apply_pairwise.<locals>.<genexpr>  s>        .2#D))     rj   r   Tr   r   c                `    g | ]*}t          j        |                                        +S r   )r   repeatr  )r   rf  r   	repeat_bys     rh   rd  z5BaseWindowGroupby._apply_pairwise.<locals>.<listcomp>,  s<       :;	!&&//955  rj   Frg  )r^  rX  r   r`  r$  r0  rk  r   r   r,   rw   maprm  r   r   r  rn  r   r  ri  rj  rl  ro  r   rc   rb   ra   r)   r   )rg   r  r  r  r   r   old_result_lengb_pairsgroupby_codesgroupby_levelsgb_level_pairlabelsri  rj  ry  result_codesresult_levelsresult_names	idx_codes
idx_levelsr{  r   r  r   ra  s     `                  @@@rh   r$  z!BaseWindowGroupby._apply_pairwise  s     T]%8JJ(($UUS )
 )
 )
 )
26-2G2N2N2P2P)
 )
 )
 &
 &
 ![[N   &*m&;&B&B&D&D   F 6:m6K6P6P6R6R  H MN!$T3+F+F+F!G!G . .28M#:#:NKK )& 1 1v$$U+++%%f----	. !M/M "]1N M188::M 6.m)<)<==(2RW555{a		//	    ?L  M flJ// 	/ 233L !455M 233LL$-fl$;$;!Iz%;L'LM"L-.L %|3&6}*\9!<|e
 
 
 $rj   r:   c                4   |j         sot          j        t          | j        j                                                                                t          j                  }|	                    |          }t                                          ||          S )r   )emptyr   rl  rm  rX  rk  r   r   r   r  r`  r   )rg   rO   r   groupby_orderra  s       rh   r   zBaseWindowGroupby._create_dataE  sy     y 	*N40E0L0L0N0N+O+OPPWW M ((=))Cww##C666rj   Nc                    | j         | j                            | j                  }t	                                          |||          S )N)r   )rV   rO   	set_indexrL   r`  r   )rg   r   r   r   ra  s       rh   r   zBaseWindowGroupby._gotitemS  sC     7X''11FwwT&999rj   )rO   r  rX  rE   rY  r   r\   r]   rO  )
r   r%  r   r[   r   r   r&  r'  r\   r  rN  rL  rM  r   )rx   rP  rQ  rR  rS  rJ   ri   r4  r$  r   r   __classcell__ra  s   @rh   rW  rW    s          OOO(\K)))) / / / / / / / /6 #&(; ; ; ; ; ; ;zR R R R R Rh7 7 7 7 7 7 7: : : : : : : : : :rj   rW  zpandas.api.typingc                  v     e Zd ZdZg dZd fdZdd
Z	 	 d d!dZd"dZeZ	d#d$dZ
d#d$dZd%d&dZd%d&dZ xZS )'Windowa  
    Provide rolling window calculations.

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

        If an integer, the delta between the start and end of each window.
        The number of points in the window depends on the ``closed`` argument.

        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
        :ref:`this link<timeseries.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.

    closed : str, default None
        Determines the inclusivity of points in the window

        If ``'right'``, uses the window (first, last] meaning the last point
        is included in the calculations.

        If ``'left'``, uses the window [first, last) meaning the first point
        is included in the calculations.

        If ``'both'``, uses the window [first, last] meaning all points in
        the window are included in the calculations.

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

        () and [] are referencing open and closed set
        notation respetively.

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

    step : int, default None
        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'

        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_   rP   rR   rT   rV   rX   rY   rZ   r\   r]   c                    t                                                       t          | j        t                    st          d| j                   t          dd          }t          || j        d           | _        | j        t          d| j                   t          | j	        t                    rt          d          t          | j	                  r| j	        dk     rt          d          | j        dk    rt          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 greaterrM   z+'single' is the only supported method type.)r`  rf   rb   rT   r[   rd   r   r   _scipy_weight_generatorr_   r#   r   r   rZ   )rg   signalra  s     rh   rf   zWindow._validatee  s   $--- 	B@@@AAA+"*X
 
 
 (/vt}d'K'K$'/@@@AAAdk;// 	%H   $+&& 	G$+//EFFF;(""%&STTT #"rj   r   r|   offsetr   c                    |dk    r8t          |d          g}t          j        |t          |                             }|S )zT
        Center the result in the window for weighted rolling aggregations.
        r   N)r   r   r   tuple)rg   r   r  lead_indexers       rh   _center_windowzWindow._center_window{  s@     A::!&$//0LWVE,$7$7899Frj   Fr   r   ,Callable[[np.ndarray, int, int], np.ndarray]r   r[   r   r   r&  r'  c                       j          j        fi | j        rt                    dz
  dz  ndd f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                $   | j         dk    r|                                 S fd}t          j        d          5  t          j         ||                     }d d d            n# 1 swxY w Y   j        r                    |          }|S )Nr   c                    t          j        t           j                  }t          j        | |f          }  | j        j        nt                              S r   )r   fullr   rl  rP   r   )r+  additional_nansr   r  rg   r_   s     rh   r-  z5Window._apply.<locals>.homogeneous_func.<locals>.calc  s]    "$'&"&"9"9NA#788t(,(8(DD$$#f++  rj   r.  r/  )r1  r   r   r2  asarrayrR   r  )r   r-  r   r   r  rg   r_   s      rh   r   z'Window._apply.<locals>.homogeneous_func  s     {a{{}}$        *** 2 2DDLL112 2 2 2 2 2 2 2 2 2 2 2 2 2 2 { =,,VV<<Ms   A((A,/A,Nr3  )r  r_   rR   r   r  rY   )	rg   r   r   r   r&  r   r   r  r_   s	   ``     @@rh   r4  zWindow._apply  s    : .-K
 
!
 
 ,0;=#f++/a''A	 	 	 	 	 	 	 	 	0 %%&6lKKLtyL
 	
rj   Nc                j    t          | |||                                          }| ||           }|S )ao	  
        Aggregate using one or more operations over the specified axis.

        Parameters
        ----------
        func : function, str, list or dict
            Function to use for aggregating the data. If a function, must either
            work when passed a Series/DataFrame or
            when passed to Series/DataFrame.apply.

            Accepted combinations are:

            - function
            - string function name
            - list of functions and/or function names, e.g. ``[np.sum, 'mean']``
            - dict of axis labels -> functions, function names or list of such.

        *args
            Positional arguments to pass to `func`.
        **kwargs
            Keyword arguments to pass to `func`.

        Returns
        -------
        scalar, Series or DataFrame

            The return can be:

            * scalar : when Series.agg is called with single function
            * Series : when DataFrame.agg is called with a single function
            * DataFrame : when DataFrame.agg is called with several functions

        See Also
        --------
        DataFrame.aggregate : Similar DataFrame method.
        Series.aggregate : Similar Series method.

        Notes
        -----
        The aggregation operations are always performed over an axis, either the
        index (default) or the column axis. This behavior is different from
        `numpy` aggregation functions (`mean`, `median`, `prod`, `sum`, `std`,
        `var`), where the default is to compute the aggregation of the flattened
        array, e.g., ``numpy.mean(arr_2d)`` as opposed to
        ``numpy.mean(arr_2d, axis=0)``.

        `agg` is an alias for `aggregate`. Use the alias.

        Functions that mutate the passed object can produce unexpected
        behavior or errors and are not supported. See :ref:`gotchas.udf-mutation`
        for more details.

        A passed user-defined-function will be passed a Series for evaluation.

        If ``func`` defines an index relabeling, ``axis`` must be ``0`` or ``index``.

        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
        rC  )r   rF  )rg   r   rD  r   r   s        rh   rJ  zWindow.aggregate  s>    P &dDtFKKKOOQQ>T$ZZFrj   c                <    t           j        } | j        |fd|d|S )a  
        Calculate the rolling weighted window sum.

        Parameters
        ----------
        numeric_only : bool, default False
            Include only float, int, boolean columns.

        **kwargs
            Keyword arguments to configure the ``SciPy`` weighted window type.

        Returns
        -------
        Series or DataFrame
            Return type is the same as the original object with ``np.float64`` dtype.

        See Also
        --------
        Series.rolling : Calling rolling with Series data.
        DataFrame.rolling : Calling rolling with DataFrames.
        Series.sum : Aggregating sum for Series.
        DataFrame.sum : Aggregating sum for DataFrame.

        Examples
        --------
        >>> 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.api.typing.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
        sumr   r   )window_aggregationsroll_weighted_sumr4  rg   r   r   window_funcs       rh   r  z
Window.sum  sB    ^ *; t{
%
 
 	
 
 	
rj   c                <    t           j        } | j        |fd|d|S )a  
        Calculate the rolling weighted window mean.

        Parameters
        ----------
        numeric_only : bool, default False
            Include only float, int, boolean columns.

        **kwargs
            Keyword arguments to configure the ``SciPy`` weighted window type.

        Returns
        -------
        Series or DataFrame
            Return type is the same as the original object with ``np.float64`` dtype.

        See Also
        --------
        Series.rolling : Calling rolling with Series data.
        DataFrame.rolling : Calling rolling with DataFrames.
        Series.mean : Aggregating mean for Series.
        DataFrame.mean : Aggregating mean for DataFrame.

        Examples
        --------
        >>> 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.api.typing.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
        meanr  )r  roll_weighted_meanr4  r  s       rh   r  zWindow.meanM  sB    \ *< t{
%
 
 	
 
 	
rj   r   ddofc                    t          t          j        |          }|                    dd            | j        |fd|d|S )aB  
        Calculate the rolling weighted window variance.

        Parameters
        ----------
        ddof : int, default 1
            Delta Degrees of Freedom.  The divisor used in calculations
            is ``N - ddof``, where ``N`` represents the number of elements.
        numeric_only : bool, default False
            Include only float, int, boolean columns.

        **kwargs
            Keyword arguments to configure the ``SciPy`` weighted window type.

        Returns
        -------
        Series or DataFrame
            Return type is the same as the original object with ``np.float64`` dtype.

        See Also
        --------
        Series.rolling : Calling rolling with Series data.
        DataFrame.rolling : Calling rolling with DataFrames.
        Series.var : Aggregating var for Series.
        DataFrame.var : Aggregating var for DataFrame.

        Examples
        --------
        >>> 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.api.typing.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
        r  r   Nvarr  )r   r  roll_weighted_varpopr4  )rg   r  r   r   r  s        rh   r  z
Window.var  sQ    b 1C$OOO

64   t{;XUXXQWXXXrj   c           	     >    t           | j        d|d|d|          S )a`  
        Calculate the rolling weighted window standard deviation.

        Parameters
        ----------
        ddof : int, default 1
            Delta Degrees of Freedom.  The divisor used in calculations
            is ``N - ddof``, where ``N`` represents the number of elements.
        numeric_only : bool, default False
            Include only float, int, boolean columns.

        **kwargs
            Keyword arguments to configure the ``SciPy`` weighted window type.

        Returns
        -------
        Series or DataFrame
            Return type is the same as the original object with ``np.float64`` dtype.

        See Also
        --------
        Series.rolling : Calling rolling with Series data.
        DataFrame.rolling : Calling rolling with DataFrames.
        Series.std : Aggregating std for Series.
        DataFrame.std : Aggregating std for DataFrame.

        Examples
        --------
        >>> 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.api.typing.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
        std)r  r   r   r   )r1   r  )rg   r  r   r   s       rh   r  z
Window.std  s5    b DHP$UPPPP
 
 	
rj   rK  )r   r|   r  r   r\   r|   rO  )r   r  r   r[   r   r   r&  r'  r   rL  r   r   r   Fr  r   r   r   )rx   rP  rQ  rR  rJ   rf   r  r4  rJ  rF  r  r  r  r  r  r  s   @rh   r  r  ]  s#       y yv	 	 	KU U U U U U,    #&(<
 <
 <
 <
 <
|M M M M^ C8
 8
 8
 8
 8
t7
 7
 7
 7
 7
r3Y 3Y 3Y 3Y 3Yj3
 3
 3
 3
 3
 3
 3
 3
 3
rj   r  c                  b   e Zd ZdFdGdZ	 	 	 	 	 dHdIdZdJdZedKd            ZedLd             ZdMd"Z	 	 	 dNdOd#Z	 	 	 dNdOd$Z		 	 	 dNdOd%Z
	 	 	 dNdOd&Z	 	 	 dNdOd'Z	 	 	 	 dPdQd+Z	 	 	 	 dPdQd,ZdFdGd-ZdRdSd.ZdFdGd/ZdFdGd0ZdFdGd1Z	 	 dTdUd7Z	 	 	 	 dVdWd>Z	 dFdGd?Z	 	 	 	 dXdYdDZ	 	 	 	 dXdYdEZdS )ZRollingAndExpandingMixinFr   r   c                J    t           j        }|                     |d|          S )Nr  r  )r  roll_sumr4  rg   r   r  s      rh   r  zRollingAndExpandingMixin.count  s"    )2{{;W<{PPPrj   Nr   r%  rE  engine!Literal['cython', 'numba'] | Noner5  r6  rD  tuple[Any, ...] | Noner   dict[str, Any] | Nonec                   |d}|i }t          |          st          d          d}t          |          rj|du rt          d          t          |||d          \  }}| j        dk    rt          |fi t          |          }nXt          |fi t          |          }n=|dv r*|t          d	          |                     ||||          }nt          d
          | 	                    |d|          S )Nr   z'raw parameter must be `True` or `False`Fz.raw must be `True` when using the numba enginer   )num_required_argsrM   )cythonNz+cython engine does not accept engine_kwargsz)engine must be either 'numba' or 'cython'rG  )r   r&  )
r   rd   r.   r/   rZ   r3   r-   r4   _generate_cython_apply_funcr4  )	rg   r   rE  r  r5  rD  r   r&  
apply_funcs	            rh   rG  zRollingAndExpandingMixin.apply  sZ    <D>Fs|| 	HFGGG&(
6"" 	Je|| !QRRR!;dFa" " "J {h&&6 -m<< 

 7 -m<< 

 '''( !NOOO99$TRRJJHIII{{!  
 
 	
rj   r'  dict[str, Any]bool | np.bool_functionr\   ?Callable[[np.ndarray, np.ndarray, np.ndarray, int], np.ndarray]c                     ddl m t          t          j        ||t          |          |          |f fd	}|S )Nr   r   )rD  r   rE  r  c                J    |s | j         d          }  | |||          S )NF)ra   r   )rL   )r   beginr}   rP   rE  rB   rg   r  s        rh   r  zHRollingAndExpandingMixin._generate_cython_apply_func.<locals>.apply_func4  s:     DdhUCCC;vuc;???rj   )r   rB   r   r  
roll_applyr   )rg   rD  r   rE  r  r  rB   r  s   `     @@rh   r  z4RollingAndExpandingMixin._generate_cython_apply_func#  s     	"!!!!!*S		
 
 
 =@ 	@ 	@ 	@ 	@ 	@ 	@ 	@ 	@ rj   !Callable[Concatenate[Self, P], T]P.argsP.kwargsr>   c                    d S r   r   rg   r   rD  r   s       rh   pipezRollingAndExpandingMixin.pipe<  	     Crj   tuple[Callable[..., T], str]r   c                    d S r   r   r  s       rh   r  zRollingAndExpandingMixin.pipeD  r  rj   @Callable[Concatenate[Self, P], T] | tuple[Callable[..., T], str]c                .    t          j        | |g|R i |S r   )r  r  r  s       rh   r  zRollingAndExpandingMixin.pipeL  s&     xd4T444V444rj   c                   t          |          rY| j        dk    r2t          t          j                  }|                     |d||          S ddlm} |                     ||          S t          j
        }|                     |d|          S )Nrp   TrE  r  r5  r   )sliding_sumr  r  )r.   rZ   r2   r   nansumrG  pandas.core._numba.kernelsr  rA  r  r  r4  )rg   r   r  r5  r   r  r  s          rh   r  zRollingAndExpandingMixin.sumT  s     6"" 	E{g%%>ryIIzz!"/	 "    CBBBBB((mDDD)2{{;U{NNNrj   c                   t          |          r[| j        dk    r2t          t          j                  }|                     |d||          S ddlm} |                     ||d          S t          j
        }|                     |d|          S )	Nrp   Tr  r   sliding_min_maxis_maxmaxr  )r.   rZ   r2   r   nanmaxrG  r  r  rA  r  roll_maxr4  rg   r   r  r5  r   r  r  s          rh   r  zRollingAndExpandingMixin.maxj  s     6"" 	V{g%%>ryIIzz!"/	 "    GFFFFF((-PT(UUU)2{{;U{NNNrj   c                   t          |          r[| j        dk    r2t          t          j                  }|                     |d||          S ddlm} |                     ||d          S t          j
        }|                     |d|	          S )
Nrp   Tr  r   r  Fr  minr  )r.   rZ   r2   r   nanminrG  r  r  rA  r  roll_minr4  r  s          rh   r  zRollingAndExpandingMixin.min  s     6"" 	W{g%%>ryIIzz!"/	 "    GFFFFF((-PU(VVV)2{{;U{NNNrj   c                   t          |          rY| j        dk    r2t          t          j                  }|                     |d||          S ddlm} |                     ||          S t          j
        }|                     |d|          S )Nrp   Tr  r   )sliding_meanr  r  )r.   rZ   r2   r   nanmeanrG  r  r  rA  r  	roll_meanr4  )rg   r   r  r5  r   r  r  s          rh   r  zRollingAndExpandingMixin.mean  s     6"" 	F{g%%>rzJJzz!"/	 "    DCCCCC((}EEE)3{{;V,{OOOrj   c                    t          |          rJ| j        dk    rt          t          j                  }nt          j        }|                     |d||          S t          j        }|                     |d|          S )Nrp   Tr  medianr  )	r.   rZ   r2   r   	nanmedianrG  r  roll_median_cr4  )rg   r   r  r5  r   r  s         rh   r  zRollingAndExpandingMixin.median  s     6"" 	{g%%>r|LL|::+	     *7{{;XL{QQQrj   r   r  r   c                   t          |          rE| j        dk    rt          d          ddlm} t          |                     ||                    S t          j        fd}| 	                    |d|          S )	Nrp   z%std not supported with method='table'r   sliding_varr  c           	     >    t           | |||                    S )Nr  )r1   )r   r  r}   rP   r  r  s       rh   
zsqrt_funcz0RollingAndExpandingMixin.std.<locals>.zsqrt_func  s&    VUC4PPPQQQrj   r  r  )
r.   rZ   r   r  r  r1   rA  r  roll_varr4  )rg   r  r   r  r5  r  r  r  s    `     @rh   r  zRollingAndExpandingMixin.std  s     6"" 	S{g%%)*QRRR>>>>>>**;D*QQRRR)2	R 	R 	R 	R 	R 	R {{%  
 
 	
rj   c                    t          |          r8| j        dk    rt          d          ddlm} |                     |||          S t          t          j        |          }| 	                    |d|          S )Nrp   z%var not supported with method='table'r   r  r  r  r  )
r.   rZ   r   r  r  rA  r   r  r  r4  )rg   r  r   r  r5  r  r  s          rh   r  zRollingAndExpandingMixin.var  s     6"" 	L{g%%)*QRRR>>>>>>$$[-d$KKK1:FFF{{%  
 
 	
rj   c                J    t           j        }|                     |d|          S )Nskewr  )r  	roll_skewr4  r  s      rh   r  zRollingAndExpandingMixin.skew  .    )3{{%  
 
 	
rj   c                    |                      d|           |                     ||          |                     |                              d          z  S )Nsemr   r  r         ?r   r  r  powrg   r  r   s      rh   r  zRollingAndExpandingMixin.sem  sQ    ##E<888xx\x==JJLJ11
#c(( 	rj   c                J    t           j        }|                     |d|          S )Nkurtr  )r  	roll_kurtr4  r  s      rh   r  zRollingAndExpandingMixin.kurt  r
  rj   c                J    t           j        }|                     |d|          S )Nfirstr  )r  
roll_firstr4  r  s      rh   r  zRollingAndExpandingMixin.first  s.    )4{{%  
 
 	
rj   c                J    t           j        }|                     |d|          S )Nlastr  )r  	roll_lastr4  r  s      rh   r  zRollingAndExpandingMixin.last  r
  rj   linearqfloatinterpolationr;   c                    |dk    rt           j        }n/|dk    rt           j        }nt          t           j        ||          }|                     |d|          S )Ng      ?g        )quantiler  r!  r  )r  r  r  r   roll_quantiler4  )rg   r  r  r   r  s        rh   r!  z!RollingAndExpandingMixin.quantile  sd     88-6KK#XX-6KK!#1+  K {{;Zl{SSSrj   averageTrZ   r?   	ascendingpctc                l    t          t          j        |||          }|                     |d|          S )N)rZ   r$  
percentilerankr  )r   r  	roll_rankr4  )rg   rZ   r$  r%  r   r  s         rh   r(  zRollingAndExpandingMixin.rank'  sA     )	
 
 
 {{;V,{OOOrj   c                d    t          t          j                  }|                     |d|          S )Nnuniquer  )r   r  roll_nuniquer4  r  s      rh   r+  z RollingAndExpandingMixin.nunique7  s3     ,
 
 {{;Y\{RRRrj   r  r  r  rS   c                      j         t          d                               d|           ddlm  fd}                      j        ||||          S )Nzstep not implemented for covcovr   r   c                *                        |           }                     |          }                                }j        j        n|j        }|                    t          |          |j        j        j                  \  }}	                    ||t          |                     t          j        d          5  t          j        ||z  |||          }t          j        ||||          }	t          j        ||||          }
t          j        t          ||z                                 t          j                  ||d          }||	|
z  z
  ||z
  z  z  }d d d            n# 1 swxY w Y    || j        | j        d          S )Nr   r.  r/  r   Fr   )r   r   rP   r   ru   r   rR   rX   rY   r   r   r2  r  r  r  r   r   r   ra   r   )r+  yx_arrayy_arrayr,  rP   r{   r}   mean_x_ymean_xmean_y	count_x_yr   rB   r  rg   s                rh   cov_funcz.RollingAndExpandingMixin.cov.<locals>.cov_funcN  s   ''**G''**G!5577N #/   #/ 
 (99w<<'{{Y :  JE3 %%eS#g,,???*** 	Y 	Y.8g%uc;  -6wsKXX,6wsKXX/8'G+,,33BJ??Q 	 #Vf_4iRVFV9WX	Y 	Y 	Y 	Y 	Y 	Y 	Y 	Y 	Y 	Y 	Y 	Y 	Y 	Y 	Y 6&af5IIIIs   BE11E58E5rY   r   r   r   rB   r$  r   )rg   r  r  r  r   r7  rB   s   `  `  @rh   r.  zRollingAndExpandingMixin.covA  s     9 %&DEEE##E<888!!!!!!	J 	J 	J 	J 	J 	J 	J< ##x<
 
 	
rj   c                      j         t          d                               d|           ddlm  fd}                      j        ||||          S )Nzstep not implemented for corrcorrr   r   c                                        |           }                     |          }                                }j        j        n|j        }|                    t          |          |j        j        j                  \  }}	                    ||t          |                     t          j        d          5  t          j        ||z  |||          }t          j        ||||          }	t          j        ||||          }
t          j        t          ||z                                 t          j                  ||d          }t          j        ||||          }t          j        ||||          }||	|
z  z
  ||z
  z  z  }||z  dz  }||z  }d d d            n# 1 swxY w Y    || j        | j        d          S )Nr   r.  r/  r   r  Fr   )r   r   rP   r   ru   r   rR   rX   rY   r   r   r2  r  r  r  r   r   r   r  ra   r   )r+  r0  r1  r2  r,  rP   r{   r}   r3  r4  r5  r6  x_vary_var	numeratordenominatorr   rB   r  rg   s                    rh   	corr_funcz0RollingAndExpandingMixin.corr.<locals>.corr_func}  s=   ''**G''**G!5577N #/   #/ 
 (99w<<'{{Y :  JE3 %%eS#g,,???*** 1 1.8g%uc;  -6wsKXX,6wsKXX/8'G+,,33BJ??Q 	 ,4UCd  ,4UCd  &7T!12	  %u}4"[0'1 1 1 1 1 1 1 1 1 1 1 1 1 1 1( 6&af5IIIIs   CF..F25F2r8  )rg   r  r  r  r   r@  rB   s   `  `  @rh   r:  zRollingAndExpandingMixin.corrp  s     9 %&EFFF##FL999!!!!!!&	J &	J &	J &	J &	J &	J &	JP ##xL
 
 	
rj   rL  r  FNNNNr   r%  rE  r   r  r  r5  r6  rD  r  r   r  )
rD  r'  r   r  rE  r  r  r%  r\   r  r   r  rD  r  r   r  r\   r>   r   r  rD  r   r   r   r\   r>   r   r  rD  r   r   r   r\   r>   FNNr   r   r  r  r5  r6  r   FNNr  r   r   r   r  r  r5  r6  r  r  r  Fr  r  r  r;   r   r   r#  TFFrZ   r?   r$  r   r%  r   r   r   NNr   Fr  r  r  rS   r  r   r   r   )rx   rP  rQ  r  rG  r  r   r  r  r  r  r  r  r  r  r  r  r  r  r  r!  r(  r+  r.  r:  r   rj   rh   r  r    s!       Q Q Q Q Q 4804'+(,+
 +
 +
 +
 +
Z   2    X    X5 5 5 5 #4804	O O O O O0 #4804	O O O O O0 #4804	O O O O O0 #4804	P P P P P0 #4804	R R R R R. "4804
 
 
 
 
4 "4804
 
 
 
 
(
 
 
 
 
    
 
 
 
 

 
 
 
 

 
 
 
 
 08"	T T T T T* %."P P P P P$ #S S S S S ,0 $"-
 -
 -
 -
 -
b ,0 $"7
 7
 7
 7
 7
 7
 7
rj   r  c                       e Zd ZU g dZded<   dK fdZdKdZdLd
ZdM fd	ZeZ	dNdO fdZ
	 	 	 	 	 dPdQ fdZedRd!            ZedSd$            ZedT fd&            Z	 	 	 dUdV fd'Z	 dNddd(dV fd)Z	 	 	 dUdV fd*Z	 	 	 dUdV fd+Z	 	 	 dUdV fd,Z	 	 	 	 dWdX fd0Z	 	 	 	 dWdX fd1ZdNdO fd2ZdYdZd3ZdNdO fd4ZdNdO fd5ZdNdO fd6Z	 	 d[d\ fd<Z	 	 	 	 d]d^ fdCZ	 dNdO fdDZ	 	 	 	 d_d` fdIZ	 	 	 	 d_d` fdJZ xZ S )aRollingr  rI   rJ   r\   r]   c                p   t                                                       | j        j        s[t	          | j        t          t          t          f          s4t	          | j        j	        t                    rw| j        j	        j        dv rct	          | j        t          t          t          f          r;|                                  	 t#          | j                  }n2# t$          t&          f$ r}t'          d| j         d          |d }~ww xY wt	          | j        t                    r1|j        | j        j        j        | j        j        j        z  z  | _        nn	 t1          | j        j	                  }n# t$          $ r d}Y nw xY wt3          d|          }t5          |j                                      |          j        | _        | j        d| _        | j        t?          d          d S t	          | j        t@                    rd S tC          | j                  r| j        dk     rt'          d	          d S )
Nr   zpassed window z, is not compatible with a datetimelike indexnsr=   r   z,step is not supported with frequency windowsr   r  )"r`  rf   rO   r  rb   rL   r'   r+   r*   r   r   r   r_   r[   r   r    _validate_datetimelike_monotonicr   rq   rd   nanosfreqnr`   rF   r   r   as_unit_valuerP   rY   r   r#   r   )rg   rV  r   unitra  s       rh   rf   zRolling._validate  sA    HN+	G$(]NK$PQQ+	G 48>:66+	G <@8>;NRV;V;VsJ	&BCC <W11333 --z*    ;T[ ; ; ;  
 $(K00 O %)JHM'$(-/9%!! (88DD       DDD  J--$-dj$9$9$A$A$$G$G$N! '#$ y$)B   %$
 [11 	GDDK(( 	GDK!OOEFFF -<Os*   C D
,DD
E3 3FFc                    | 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)rL   hasnans_raise_monotonic_erroris_monotonic_increasingis_monotonic_decreasingr   s    rh   rT  z(Rolling._validate_datetimelike_monotonic  su    
 8 	D''(BCCC0 	DDH4T 	D''(BCCCCC	D 	D 	D 	Drj   msgr[   c                @    | j         }|d}t          | d|           )Nra    )rV   rd   )rg   ra  rV   s      rh   r^  zRolling._raise_monotonic_error  s+    W:BB'''rj   Nc                >     t                      j        |g|R i |S )a	  
        Aggregate using one or more operations over the specified axis.

        Parameters
        ----------
        func : function, str, list or dict
            Function to use for aggregating the data. If a function, must either
            work when passed a Series/Dataframe or
            when passed to Series/Dataframe.apply.

            Accepted combinations are:

            - function
            - string function name
            - list of functions and/or function names, e.g. ``[np.sum, 'mean']``
            - dict of axis labels -> functions, function names or list of such.

        *args
            Positional arguments to pass to `func`.
        **kwargs
            Keyword arguments to pass to `func`.

        Returns
        -------
        scalar, Series or DataFrame

            The return can be:

            * scalar : when Series.agg is called with single function
            * Series : when DataFrame.agg is called with a single function
            * DataFrame : when DataFrame.agg is called with several functions

        See Also
        --------
        Series.rolling : Calling object with Series data.
        DataFrame.rolling : Calling object with DataFrame data.

        Notes
        -----
        The aggregation operations are always performed over an axis, either the
        index (default) or the column axis. This behavior is different from
        `numpy` aggregation functions (`mean`, `median`, `prod`, `sum`, `std`,
        `var`), where the default is to compute the aggregation of the flattened
        array, e.g., ``numpy.mean(arr_2d)`` as opposed to
        ``numpy.mean(arr_2d, axis=0)``.

        `agg` is an alias for `aggregate`. Use the alias.

        Functions that mutate the passed object can produce unexpected
        behavior or errors and are not supported. See :ref:`gotchas.udf-mutation`
        for more details.

        A passed user-defined-function will be passed a Series for evaluation.

        If ``func`` defines an index relabeling, ``axis`` must be ``0`` or ``index``.

        Examples
        --------
        >>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]})
        >>> df
        A  B  C
        0  1  4  7
        1  2  5  8
        2  3  6  9

        >>> df.rolling(2).sum()
            A     B     C
        0  NaN   NaN   NaN
        1  3.0   9.0  15.0
        2  5.0  11.0  17.0

        >>> df.rolling(2).agg({"A": "sum", "B": "min"})
            A    B
        0  NaN  NaN
        1  3.0  4.0
        2  5.0  5.0
        )r`  rJ  rg   r   rD  r   ra  s       rh   rJ  zRolling.aggregate  s-    \ !uww 7777777rj   Fr   r   c                F    t                                          |          S )a1  
        Calculate the rolling count of non NaN observations.

        Parameters
        ----------
        numeric_only : bool, default False
            Include only float, int, boolean columns.

        Returns
        -------
        Series or DataFrame
            Return type is the same as the original object with ``np.float64`` dtype.

        See Also
        --------
        Series.rolling : Calling rolling with Series data.
        DataFrame.rolling : Calling rolling with DataFrames.
        Series.count : Aggregating count for Series.
        DataFrame.count : Aggregating count for DataFrame.

        Examples
        --------
        >>> 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  rg   r   ra  s     rh   r  zRolling.countJ  s    V ww}}\***rj   r   r%  rE  r  r  r5  r6  rD  r  r   r  c                R    t                                          ||||||          S )a	  
        Calculate the rolling custom aggregation function.

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

        raw : bool, default False
            * ``False`` : passes each row or column as a Series to the
              function.
            * ``True`` : the passed function will receive ndarray
              objects instead.

            If you are just applying a NumPy reduction function this will
            achieve much better performance.

        engine : str, default None
            * ``'cython'`` : Runs rolling apply through C-extensions from cython.
            * ``'numba'`` : Runs rolling apply through JIT compiled code from numba.
              Only available when ``raw`` is set to ``True``.
            * ``None`` : Defaults to ``'cython'`` or
              globally setting ``compute.use_numba``.

        engine_kwargs : dict, default None
            * For ``'cython'`` engine, there are no accepted ``engine_kwargs``
            * For ``'numba'`` engine, the engine can accept ``nopython``, ``nogil``
              and ``parallel`` dictionary keys. The values must either be ``True`` or
              ``False``.

            The default ``engine_kwargs`` for the ``'numba'`` engine is
            ``{'nopython': True, 'nogil': False, 'parallel': False}`` and will be
            applied to both the ``func`` and the ``apply`` rolling aggregation.

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

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

        Returns
        -------
        Series or DataFrame
            Return type is the same as the original object with ``np.float64`` dtype.

        See Also
        --------
        Series.rolling : Calling rolling with Series data.
        DataFrame.rolling : Calling rolling with DataFrames.
        Series.apply : Aggregating apply for Series.
        DataFrame.apply : Aggregating apply for DataFrame.

        Examples
        --------
        >>> 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
        )rE  r  r5  rD  r   )r`  rG  )rg   r   rE  r  r5  rD  r   ra  s          rh   rG  zRolling.applyw  s7    R ww}}'  
 
 	
rj   r  r  r  r>   c                    d S r   r   r  s       rh   r  zRolling.pipe  r  rj   r  r   c                    d S r   r   r  s       rh   r  zRolling.pipe  r  rj   r  c                >     t                      j        |g|R i |S )a	  
        Apply a ``func`` with arguments to this Rolling object and return its result.

        Use `.pipe` when you want to improve readability by chaining together
        functions that expect
        Series, DataFrames, GroupBy, Rolling, Expanding or Resampler
        objects.
        Instead of writing

        >>> h = lambda x, arg2, arg3: x + 1 - arg2 * arg3
        >>> g = lambda x, arg1: x * 5 / arg1
        >>> f = lambda x: x**4
        >>> df = pd.DataFrame(
        ...     {"A": [1, 2, 3, 4]}, index=pd.date_range("2012-08-02", periods=4)
        ... )
        >>> h(g(f(df.rolling("2D")), arg1=1), arg2=2, arg3=3)  # doctest: +SKIP

        You can write

        >>> (
        ...     df.rolling("2D").pipe(f).pipe(g, arg1=1).pipe(h, arg2=2, arg3=3)
        ... )  # doctest: +SKIP

        which is much more readable.

        Parameters
        ----------
        func : callable or tuple of (callable, str)
            Function to apply to this Rolling object or, alternatively,
            a `(callable, data_keyword)` tuple where `data_keyword` is a
            string indicating the keyword of `callable` that expects the
            Rolling object.
        *args : iterable, optional
            Positional arguments passed into `func`.
        **kwargs : dict, optional
                A dictionary of keyword arguments passed into `func`.

        Returns
        -------
        Rolling
            The original object with the function `func` applied.

        See Also
        --------
        Series.pipe : Apply a function with arguments to a series.
        DataFrame.pipe: Apply a function with arguments to a dataframe.
        apply : Apply function to each group instead of to the
            full Rolling object.

        Notes
        -----
        See more `here
        <https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html#piping-function-calls>`__.

        Examples
        --------

        >>> df = pd.DataFrame(
        ...     {"A": [1, 2, 3, 4]}, index=pd.date_range("2012-08-02", periods=4)
        ... )
        >>> df
                    A
        2012-08-02  1
        2012-08-03  2
        2012-08-04  3
        2012-08-05  4

        To get the difference between each rolling
        2-day window's maximum and minimum
        value in one pass, you can do

        >>> df.rolling("2D").pipe(lambda x: x.max() - x.min())
                    A
        2012-08-02  0.0
        2012-08-03  1.0
        2012-08-04  1.0
        2012-08-05  1.0
        )r`  r  re  s       rh   r  zRolling.pipe  s,    j uww|D242226222rj   c                L    t                                          |||          S )at	  
        Calculate the rolling sum.

        Parameters
        ----------
        numeric_only : bool, default False
            Include only float, int, boolean columns.

        engine : str, default None
            * ``'cython'`` : Runs the operation through C-extensions from cython.
            * ``'numba'`` : Runs the operation through JIT compiled code from numba.
            * ``None`` : Defaults to ``'cython'`` or
              globally setting ``compute.use_numba``

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

        Returns
        -------
        Series or DataFrame
            Return type is the same as the original object with ``np.float64`` dtype.

        See Also
        --------
        Series.rolling : Calling rolling with Series data.
        DataFrame.rolling : Calling rolling with DataFrames.
        Series.sum : Aggregating sum for Series.
        DataFrame.sum : Aggregating sum for DataFrame.

        Notes
        -----
        See :ref:`window.numba_engine` and :ref:`enhancingperf.numba`
        for extended documentation and performance considerations
        for the Numba engine.

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

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

        >>> s.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  r5  )r`  r  rg   r   r  r5  ra  s       rh   r  zRolling.sum0	  s.    v ww{{%'  
 
 	
rj   )r  r5  c               L    t                                          |||          S )a  
        Calculate the rolling maximum.

        Parameters
        ----------
        numeric_only : bool, default False
            Include only float, int, boolean columns.

        *args : iterable, optional
            Positional arguments passed into ``func``.

        engine : str, default None
            * ``'cython'`` : Runs the operation through C-extensions from cython.
            * ``'numba'`` : Runs the operation through JIT compiled code from numba.
            * ``None`` : Defaults to ``'cython'`` or
              globally setting ``compute.use_numba``

        engine_kwargs : dict, default None
            * For ``'cython'`` engine, there are no accepted ``engine_kwargs``
            * For ``'numba'`` engine, the engine can accept ``nopython``, ``nogil``
              and ``parallel`` dictionary keys. The values must either be ``True`` or
              ``False``.

            The default ``engine_kwargs`` for the ``'numba'`` engine is
            ``{'nopython': True, 'nogil': False, 'parallel': False}``.

        **kwargs : mapping, optional
            A dictionary of keyword arguments passed into ``func``.

        Returns
        -------
        Series or DataFrame
            Return type is the same as the original object with ``np.float64`` dtype.

        See Also
        --------
        Series.rolling : Calling rolling with Series data.
        DataFrame.rolling : Calling rolling with DataFrames.
        Series.max : Aggregating max for Series.
        DataFrame.max : Aggregating max for DataFrame.

        Notes
        -----
        See :ref:`window.numba_engine` and :ref:`enhancingperf.numba`
        for extended documentation and performance considerations
        for the Numba engine.

        Examples
        --------
        >>> ser = pd.Series([1, 2, 3, 4])
        >>> ser.rolling(2).max()
        0    NaN
        1    2.0
        2    3.0
        3    4.0
        dtype: float64
        rm  )r`  r  )rg   r   r  r5  rD  r   ra  s         rh   r  zRolling.max	  s.    B ww{{%'  
 
 	
rj   c                L    t                                          |||          S )a,  
        Calculate the rolling minimum.

        Parameters
        ----------
        numeric_only : bool, default False
            Include only float, int, boolean columns.

        engine : str, default None
            * ``'cython'`` : Runs the operation through C-extensions from cython.
            * ``'numba'`` : Runs the operation through JIT compiled code from numba.
            * ``None`` : Defaults to ``'cython'`` or
              globally setting ``compute.use_numba``

        engine_kwargs : dict, default None
            * For ``'cython'`` engine, there are no accepted ``engine_kwargs``
            * For ``'numba'`` engine, the engine can accept ``nopython``, ``nogil``
              and ``parallel`` dictionary keys. The values must either be ``True`` or
              ``False``.

            The default ``engine_kwargs`` for the ``'numba'`` engine is
            ``{'nopython': True, 'nogil': False, 'parallel': False}``.

        Returns
        -------
        Series or DataFrame
            Return type is the same as the original object with ``np.float64`` dtype.

        See Also
        --------
        Series.rolling : Calling rolling with Series data.
        DataFrame.rolling : Calling rolling with DataFrames.
        Series.min : Aggregating min for Series.
        DataFrame.min : Aggregating min for DataFrame.

        Notes
        -----
        See :ref:`window.numba_engine` and :ref:`enhancingperf.numba`
        for extended documentation and performance considerations
        for the Numba engine.

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

        >>> s = pd.Series([4, 3, 5, 2, 6])
        >>> s.rolling(3).min()
        0    NaN
        1    NaN
        2    3.0
        3    2.0
        4    2.0
        dtype: float64
        rm  )r`  r  rn  s       rh   r  zRolling.min	  s.    x ww{{%'  
 
 	
rj   c                L    t                                          |||          S )a  
        Calculate the rolling mean.

        Parameters
        ----------
        numeric_only : bool, default False
            Include only float, int, boolean columns.

        engine : str, default None
            * ``'cython'`` : Runs the operation through C-extensions from cython.
            * ``'numba'`` : Runs the operation through JIT compiled code from numba.
            * ``None`` : Defaults to ``'cython'`` or
              globally setting ``compute.use_numba``

        engine_kwargs : dict, default None
            * For ``'cython'`` engine, there are no accepted ``engine_kwargs``
            * For ``'numba'`` engine, the engine can accept ``nopython``, ``nogil``
              and ``parallel`` dictionary keys. The values must either be ``True`` or
              ``False``.

            The default ``engine_kwargs`` for the ``'numba'`` engine is
            ``{'nopython': True, 'nogil': False, 'parallel': False}``.

        Returns
        -------
        Series or DataFrame
            Return type is the same as the original object with ``np.float64`` dtype.

        See Also
        --------
        Series.rolling : Calling rolling with Series data.
        DataFrame.rolling : Calling rolling with DataFrames.
        Series.mean : Aggregating mean for Series.
        DataFrame.mean : Aggregating mean for DataFrame.

        Notes
        -----
        See :ref:`window.numba_engine` and :ref:`enhancingperf.numba`
        for extended documentation and performance considerations
        for the Numba engine.

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

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

        >>> s.rolling(3).mean()
        0    NaN
        1    NaN
        2    2.0
        3    3.0
        dtype: float64
        rm  )r`  r  rn  s       rh   r  zRolling.mean
  s.    F ww||%'  
 
 	
rj   c                L    t                                          |||          S )aD  
        Calculate the rolling median.

        Parameters
        ----------
        numeric_only : bool, default False
            Include only float, int, boolean columns.

        engine : str, default None
            * ``'cython'`` : Runs the operation through C-extensions from cython.
            * ``'numba'`` : Runs the operation through JIT compiled code from numba.
            * ``None`` : Defaults to ``'cython'`` or
              globally setting ``compute.use_numba``

        engine_kwargs : dict, default None
            * For ``'cython'`` engine, there are no accepted ``engine_kwargs``
            * For ``'numba'`` engine, the engine can accept ``nopython``, ``nogil``
              and ``parallel`` dictionary keys. The values must either be ``True`` or
              ``False``.

            The default ``engine_kwargs`` for the ``'numba'`` engine is
            ``{'nopython': True, 'nogil': False, 'parallel': False}``.

        Returns
        -------
        Series or DataFrame
            Return type is the same as the original object with ``np.float64`` dtype.

        See Also
        --------
        Series.rolling : Calling rolling with Series data.
        DataFrame.rolling : Calling rolling with DataFrames.
        Series.median : Aggregating median for Series.
        DataFrame.median : Aggregating median for DataFrame.

        Notes
        -----
        See :ref:`window.numba_engine` and :ref:`enhancingperf.numba`
        for extended documentation and performance considerations
        for the Numba engine.

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

        >>> s = pd.Series([0, 1, 2, 3, 4])
        >>> s.rolling(3).median()
        0    NaN
        1    NaN
        2    1.0
        3    2.0
        4    3.0
        dtype: float64
        rm  )r`  r  rn  s       rh   r  zRolling.medianc
  s.    x ww~~%'  
 
 	
rj   r   r  r   c                N    t                                          ||||          S )aX  
        Calculate the rolling standard deviation.

        Parameters
        ----------
        ddof : int, default 1
            Delta Degrees of Freedom.  The divisor used in calculations
            is ``N - ddof``, where ``N`` represents the number of elements.

        numeric_only : bool, default False
            Include only float, int, boolean columns.

        engine : str, default None
            * ``'cython'`` : Runs the operation through C-extensions from cython.
            * ``'numba'`` : Runs the operation through JIT compiled code from numba.
            * ``None`` : Defaults to ``'cython'`` or
              globally setting ``compute.use_numba``

        engine_kwargs : dict, default None
            * For ``'cython'`` engine, there are no accepted ``engine_kwargs``
            * For ``'numba'`` engine, the engine can accept ``nopython``, ``nogil``
              and ``parallel`` dictionary keys. The values must either be ``True`` or
              ``False``.

            The default ``engine_kwargs`` for the ``'numba'`` engine is
            ``{'nopython': True, 'nogil': False, 'parallel': False}``.

        Returns
        -------
        Series or DataFrame
            Return type is the same as the original object with ``np.float64`` dtype.

        See Also
        --------
        numpy.std : Equivalent method for NumPy array.
        Series.rolling : Calling rolling with Series data.
        DataFrame.rolling : Calling rolling with DataFrames.
        Series.std : Aggregating std for Series.
        DataFrame.std : Aggregating std for DataFrame.

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

        Examples
        --------
        >>> s = pd.Series([5, 5, 6, 7, 5, 5, 5])
        >>> s.rolling(3).std()
        0         NaN
        1         NaN
        2    0.577350
        3    1.000000
        4    1.000000
        5    1.154701
        6    0.000000
        dtype: float64
        r  r   r  r5  )r`  r  rg   r  r   r  r5  ra  s        rh   r  zRolling.std
  1    F ww{{%'	  
 
 	
rj   c                N    t                                          ||||          S )aN  
        Calculate the rolling variance.

        Parameters
        ----------
        ddof : int, default 1
            Delta Degrees of Freedom.  The divisor used in calculations
            is ``N - ddof``, where ``N`` represents the number of elements.

        numeric_only : bool, default False
            Include only float, int, boolean columns.

        engine : str, default None
            * ``'cython'`` : Runs the operation through C-extensions from cython.
            * ``'numba'`` : Runs the operation through JIT compiled code from numba.
            * ``None`` : Defaults to ``'cython'`` or
              globally setting ``compute.use_numba``

        engine_kwargs : dict, default None
            * For ``'cython'`` engine, there are no accepted ``engine_kwargs``
            * For ``'numba'`` engine, the engine can accept ``nopython``, ``nogil``
              and ``parallel`` dictionary keys. The values must either be ``True`` or
              ``False``.

            The default ``engine_kwargs`` for the ``'numba'`` engine is
            ``{'nopython': True, 'nogil': False, 'parallel': False}``.

        Returns
        -------
        Series or DataFrame
            Return type is the same as the original object with ``np.float64`` dtype.

        See Also
        --------
        numpy.var : Equivalent method for NumPy array.
        Series.rolling : Calling rolling with Series data.
        DataFrame.rolling : Calling rolling with DataFrames.
        Series.var : Aggregating var for Series.
        DataFrame.var : Aggregating var for DataFrame.

        Notes
        -----
        The default ``ddof`` of 1 used in :meth:`Series.var` is different
        than the default ``ddof`` of 0 in :func:`numpy.var`.

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

        Examples
        --------
        >>> s = pd.Series([5, 5, 6, 7, 5, 5, 5])
        >>> s.rolling(3).var()
        0         NaN
        1         NaN
        2    0.333333
        3    1.000000
        4    1.000000
        5    1.333333
        6    0.000000
        dtype: float64
        rt  )r`  r  ru  s        rh   r  zRolling.var
  rv  rj   c                H    t                                          |          S )a"  
        Calculate the rolling unbiased skewness.

        Parameters
        ----------
        numeric_only : bool, default False
            Include only float, int, boolean columns.

        Returns
        -------
        Series or DataFrame
            Return type is the same as the original object with ``np.float64`` dtype.

        See Also
        --------
        scipy.stats.skew : Third moment of a probability density.
        Series.rolling : Calling rolling with Series data.
        DataFrame.rolling : Calling rolling with DataFrames.
        Series.skew : Aggregating skew for Series.
        DataFrame.skew : Aggregating skew for DataFrame.

        Notes
        -----

        A minimum of three periods is required for the rolling calculation.

        Examples
        --------
        >>> 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
        r  )r`  r  rg  s     rh   r  zRolling.skew9  s    N ww|||666rj   c                    |                      d|           |                     ||          |                     |                              d          z  S )aB  
        Calculate the rolling standard error of mean.

        Parameters
        ----------
        ddof : int, default 1
            Delta Degrees of Freedom.  The divisor used in calculations
            is ``N - ddof``, where ``N`` represents the number of elements.

        numeric_only : bool, default False
            Include only float, int, boolean columns.

        Returns
        -------
        Series or DataFrame
            Return type is the same as the original object with ``np.float64`` dtype.

        See Also
        --------
        Series.rolling : Calling rolling with Series data.
        DataFrame.rolling : Calling rolling with DataFrames.
        Series.sem : Aggregating sem for Series.
        DataFrame.sem : Aggregating sem for DataFrame.

        Notes
        -----
        A minimum of one period is required for the calculation.

        Examples
        --------
        >>> s = pd.Series([0, 1, 2, 3])
        >>> s.rolling(2, min_periods=1).sem()
        0    NaN
        1    0.5
        2    0.5
        3    0.5
        dtype: float64
        r  r  r  r  r  s      rh   r  zRolling.semb  sR    P 	##E<888xx\x==JJ|$$
#c(( 	rj   c                H    t                                          |          S )a  
        Calculate the rolling Fisher's definition of kurtosis without bias.

        Parameters
        ----------
        numeric_only : bool, default False
            Include only float, int, boolean columns.

        Returns
        -------
        Series or DataFrame
            Return type is the same as the original object with ``np.float64`` dtype.

        See Also
        --------
        scipy.stats.kurtosis : Reference SciPy method.
        Series.rolling : Calling rolling with Series data.
        DataFrame.rolling : Calling rolling with DataFrames.
        Series.kurt : Aggregating kurt for Series.
        DataFrame.kurt : Aggregating kurt for DataFrame.

        Notes
        -----
        A minimum of four periods is required for the calculation.

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

        >>> arr = [1, 2, 3, 4, 999]
        >>> import scipy.stats
        >>> print(f"{scipy.stats.kurtosis(arr[:-1], bias=False):.6f}")
        -1.200000
        >>> print(f"{scipy.stats.kurtosis(arr[1:], bias=False):.6f}")
        3.999946
        >>> s = pd.Series(arr)
        >>> s.rolling(4).kurt()
        0         NaN
        1         NaN
        2         NaN
        3   -1.200000
        4    3.999946
        dtype: float64
        r  )r`  r  rg  s     rh   r  zRolling.kurt  s    \ ww|||666rj   c                H    t                                          |          S )a]  
        Calculate the rolling First (left-most) element of the window.

        Parameters
        ----------
        numeric_only : bool, default False
            Include only float, int, boolean columns.

        Returns
        -------
        Series or DataFrame
            Return type is the same as the original object with ``np.float64`` dtype.

        See Also
        --------
        GroupBy.first : Similar method for GroupBy objects.
        Rolling.last : Method to get the last element in each window.

        Examples
        --------
        The example below will show a rolling calculation with a window size of
        three.

        >>> s = pd.Series(range(5))
        >>> s.rolling(3).first()
        0         NaN
        1         NaN
        2         0.0
        3         1.0
        4         2.0
        dtype: float64
        r  )r`  r  rg  s     rh   r  zRolling.first  s    B ww}},}777rj   c                H    t                                          |          S )a]  
        Calculate the rolling Last (right-most) element of the window.

        Parameters
        ----------
        numeric_only : bool, default False
            Include only float, int, boolean columns.

        Returns
        -------
        Series or DataFrame
            Return type is the same as the original object with ``np.float64`` dtype.

        See Also
        --------
        GroupBy.last : Similar method for GroupBy objects.
        Rolling.first : Method to get the first element in each window.

        Examples
        --------
        The example below will show a rolling calculation with a window size of
        three.

        >>> s = pd.Series(range(5))
        >>> s.rolling(3).last()
        0         NaN
        1         NaN
        2         2.0
        3         3.0
        4         4.0
        dtype: float64
        r  )r`  r  rg  s     rh   r  zRolling.last  s    B ww|||666rj   r  r  r  r  r;   c                L    t                                          |||          S )aV  
        Calculate the rolling quantile.

        Parameters
        ----------
        q : 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.

        numeric_only : bool, default False
            Include only float, int, boolean columns.

        Returns
        -------
        Series or DataFrame
            Return type is the same as the original object with ``np.float64`` dtype.

        See Also
        --------
        Series.rolling : Calling rolling with Series data.
        DataFrame.rolling : Calling rolling with DataFrames.
        Series.quantile : Aggregating quantile for Series.
        DataFrame.quantile : Aggregating quantile for DataFrame.

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

        >>> s.rolling(2).quantile(0.4, interpolation="midpoint")
        0    NaN
        1    1.5
        2    2.5
        3    3.5
        dtype: float64
        )r  r  r   )r`  r!  )rg   r  r  r   ra  s       rh   r!  zRolling.quantile  s0    r ww'%   
 
 	
rj   r#  TrZ   r?   r$  r%  c                N    t                                          ||||          S )a  
        Calculate the rolling rank.

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

        numeric_only : bool, default False
            Include only float, int, boolean columns.

        Returns
        -------
        Series or DataFrame
            Return type is the same as the original object with ``np.float64`` dtype.

        See Also
        --------
        Series.rolling : Calling rolling with Series data.
        DataFrame.rolling : Calling rolling with DataFrames.
        Series.rank : Aggregating rank for Series.
        DataFrame.rank : Aggregating rank for DataFrame.

        Examples
        --------
        >>> 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
        )rZ   r$  r%  r   )r`  r(  )rg   rZ   r$  r%  r   ra  s        rh   r(  zRolling.rankD  s1    N ww||%	  
 
 	
rj   c                H    t                                          |          S )a  
        Calculate the rolling nunique.

        .. versionadded:: 3.0.0

        Parameters
        ----------
        numeric_only : bool, default False
            Include only float, int, boolean columns.

        Returns
        -------
        Series or DataFrame
            Return type is the same as the original object with ``np.float64`` dtype.

        See Also
        --------
        Series.rolling : Calling rolling with Series data.
        DataFrame.rolling : Calling rolling with DataFrames.
        Series.nunique : Aggregating nunique for Series.
        DataFrame.nunique : Aggregating nunique for DataFrame.

        Examples
        --------
        >>> s = pd.Series([1, 4, 2, np.nan, 3, 3, 4, 5])
        >>> s.rolling(3).nunique()
        0    NaN
        1    NaN
        2    3.0
        3    NaN
        4    NaN
        5    NaN
        6    2.0
        7    3.0
        dtype: float64
        r  )r`  r+  rg  s     rh   r+  zRolling.nunique  s(    P ww%  
 
 	
rj   r  r  r  rS   c                N    t                                          ||||          S )aL  
        Calculate the rolling sample covariance.

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

        numeric_only : bool, default False
            Include only float, int, boolean columns.

        Returns
        -------
        Series or DataFrame
            Return type is the same as the original object with ``np.float64`` dtype.

        See Also
        --------
        Series.rolling : Calling rolling with Series data.
        DataFrame.rolling : Calling rolling with DataFrames.
        Series.cov : Aggregating cov for Series.
        DataFrame.cov : Aggregating cov for DataFrame.

        Examples
        --------
        >>> 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
        r  r  r  r   )r`  r.  rg   r  r  r  r   ra  s        rh   r.  zRolling.cov  s1    l ww{{%	  
 
 	
rj   c                N    t                                          ||||          S )a  
        Calculate the rolling correlation.

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

        numeric_only : bool, default False
            Include only float, int, boolean columns.

        Returns
        -------
        Series or DataFrame
            Return type is the same as the original object with ``np.float64`` dtype.

        See Also
        --------
        cov : Similar method to calculate covariance.
        numpy.corrcoef : NumPy Pearson's correlation calculation.
        Series.rolling : Calling rolling with Series data.
        DataFrame.rolling : Calling rolling with DataFrames.
        Series.corr : Aggregating corr for Series.
        DataFrame.corr : Aggregating corr for DataFrame.

        Notes
        -----
        This function uses Pearson's definition of correlation
        (https://en.wikipedia.org/wiki/Pearson_correlation_coefficient).

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

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

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

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

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

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

        >>> v1 = [3, 3, 3, 5, 8]
        >>> v2 = [3, 4, 4, 4, 8]
        >>> 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.0, 35.0], [49.0, 30.0], [47.0, 32.0], [46.0, 31.0], [50.0, 36.0]]
        ... )
        >>> 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
        r  )r`  r:  r  s        rh   r:  zRolling.corr  s1    v ww||%	  
 
 	
rj   rK  )ra  r[   r   rL  r  rA  rB  rC  rD  rE  rF  rG  rH  rI  r  r  rJ  rK  rL  rM  rN  rO  )!rx   rP  rQ  rJ   rS  rf   rT  r^  rJ  rF  r  rG  r   r  r   r  r  r  r  r  r  r  r  r  r  r  r  r!  r(  r+  r.  r:  r  r  s   @rh   rQ  rQ    s        	 	 	K 	 	 	 	/G /G /G /G /G /GbD D D D( ( ( (N8 N8 N8 N8 N8 N8` C++ ++ ++ ++ ++ ++ ++` 4804'+(,P
 P
 P
 P
 P
 P
 P
d    X    X T3 T3 T3 T3 T3 UT3p #4804	_
 _
 _
 _
 _
 _
 _
F #E
 5904E
 E
 E
 E
 E
 E
 E
 E
R #4804	@
 @
 @
 @
 @
 @
 @
H #4804	G
 G
 G
 G
 G
 G
 G
V #4804	@
 @
 @
 @
 @
 @
 @
H "4804H
 H
 H
 H
 H
 H
 H
X "4804H
 H
 H
 H
 H
 H
 H
T'7 '7 '7 '7 '7 '7 '7R+ + + + +Z.7 .7 .7 .7 .7 .7 .7`!8 !8 !8 !8 !8 !8 !8F!7 !7 !7 !7 !7 !7 !7L 08"	=
 =
 =
 =
 =
 =
 =
B %."L
 L
 L
 L
 L
 L
 L
` #*
 *
 *
 *
 *
 *
 *
\ ,0 $";
 ;
 ;
 ;
 ;
 ;
 ;
~ ,0 $"@
 @
 @
 @
 @
 @
 @
 @
 @
 @
 @
rj   rQ  c                  @    e Zd ZdZej        ej        z   ZddZd	dZdS )
RollingGroupbyz3
    Provide a rolling groupby implementation.
    r\   r%   c                   d}| j         }t          | j        t                    rgt	          | j                  }| j        j                                        }t          |t                    sJ |                    dd           | j        }n$| j	        t          }| j	        }nt          }| j        }t          ||| j        j        ||          }|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   rb   r_   r#   rr   __dict__r   dictr  r`   r&   r$   r%   rX  rk  )rg   r  r   rolling_indexerr_   r,  s         rh   r   z"RollingGroupby._get_window_indexer  s     15'dk;// 	!"4;//O![16688Nnd33333}d333[FF*3O &FF0O[F'# M1*)
 
 
 rj   r]   c                &   | j         j        r|                     d           | j        j                                        D ]P}| j                             |          }|j        s-|j        s&| j	        dn| j	        }t          d| d| d          QdS )zC
        Validate that each group in self._on is monotonic
        r\  Nra   zEach group within z' must be monotonic. Sort the values in z first.)rL   r]  r^  rX  rk  r   r  r_  r`  rV   rd   )rg   ry  group_onrV   s       rh   rT  z/RollingGroupby._validate_datetimelike_monotonic  s    
 8 	D''(BCCC!]299;; 		 		Mx}}]33H04<4T !%WWTW 6 6 6*,6 6 6  		 		rj   N)r\   r%   rK  )	rx   rP  rQ  rR  rQ  rJ   rW  r   rT  r   rj   rh   r  r    sZ          %(9(EEK! ! ! !F     rj   r  )trR  
__future__r   r   datetimer   	functoolsr   rs   typingr   r   r   r	   r
   r   r   r   numpyr   pandas._libs.tslibsr   r   r    pandas._libs.window.aggregations_libsr_   aggregationsr  pandas.compat._optionalr   pandas.errorsr   pandas.util._decoratorsr   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   r    pandas.core.arraysr!   pandas.core.baser"   pandas.core.commoncorecommonr  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.   r/   pandas.core.window.commonr0   r1   pandas.core.window.numba_r2   r3   r4   collections.abcr5   r6   r7   r8   pandas._typingr9   r:   r;   r<   r=   r>   r?   r@   r   rA   rB   pandas.core.genericrC   r]  rE   pandas.core.arrays.datetimelikerF   rH   rW  r  r  rQ  r  r   rj   rh   <module>r     s:   
 # " " " " "              	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	             
 ? > > > > > > > > > > > > > > > > > # # # # # # . . . . . .              1 0 0 0 0 0        - , , , , , ' ' ' ' ' ' , , , , , ,        . - - - - - + + + + + +                                           . - - - - -         
                  4((((((         	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	        ,+++++333333 9 9 9 9 9 9] ] ] ] ] ] ] ]@F: F: F: F: F:
 F: F: F:R   P

 P

 P

 P

 P

Z P

 P

 ! P

fv
 v
 v
 v
 v
z v
 v
 v
r   P
 P
 P
 P
 P
& P
 P
 ! P
f. .   : : : : :& : : ! : : :rj   