
    `Vg͊                       d dl mZ d dlZd dlmZ d dlmZ d dlmZm	Z	 d dl
Z
d dlZd dlmZ d dlmc mc mZ d dlmZmZ erd dlmZmZ d d	lmZ d d
lmZ d dlm Z  d dl!m"Z" d dl#m$Z$m%Z% d dl&m'Z' d dl(m)c m*Z* d dl+m,Z,m-Z-m.Z. d dl/m0Z0m1Z1 d dl2m3Z3m4Z4 d dl5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z? d dl@mAZAmBZB d dlCmDZDmEZE d dlFmGZGmHZH 	 	 	 	 	 	 	 	 	 	 ddZI	 	 	 	 	 	 ddZJ G d deG      ZK G d deHeK      ZL G d deK      ZMy)     )annotationsN)partial)dedent)TYPE_CHECKINGcast)	Timedelta)AxisTimedeltaConvertibleTypes)	DataFrameSeries)NDFrame)function)doc)find_stack_level)is_datetime64_ns_dtypeis_numeric_dtype)isna)BaseIndexerExponentialMovingWindowIndexerGroupbyIndexer)get_jit_argumentsmaybe_use_numba)maybe_warn_args_and_kwargszsqrt)
_shared_docsargs_compatcreate_section_headerkwargs_compatkwargs_numeric_onlynumba_notestemplate_headertemplate_returnstemplate_see_alsowindow_agg_numba_parameters)generate_numba_ewm_funcgenerate_numba_ewm_table_func)EWMMeanStategenerate_online_numba_ewma_func)
BaseWindowBaseWindowGroupbyc                   t        j                  | |||      }|dkD  rt        d      | | dk  rt        d      |#|dk  rt        d      |dz
  dz  } t        |       S |Q|dk  rt        d      dt        j                  t        j
                  d      |z        z
  }d|z  dz
  } t        |       S |(|dk  s|dkD  rt        d	      d|z
  |z  } t        |       S t        d
      t        |       S )N   z8comass, span, halflife, and alpha are mutually exclusiver   z comass must satisfy: comass >= 0zspan must satisfy: span >= 1   z#halflife must satisfy: halflife > 0g      ?z"alpha must satisfy: 0 < alpha <= 1z1Must pass one of comass, span, halflife, or alpha)commoncount_not_none
ValueErrornpexplogfloat)comassspanhalflifealphavalid_countdecays         W/var/www/html/hubwallet-dev/venv/lib/python3.12/site-packages/pandas/core/window/ewm.pyget_center_of_massr<   K   s!    ''hFKQSTT A:?@@		!8;<<(a = 
	q=BCCBFF266#;122UQ = 
	A:ABBe)u$ = LMM=    c                    t        j                  | j                  t         j                        t         j                        }t        t        |      j                        }t        j                  |      |z  S )a  
    Return the diff of the times divided by the half-life. These values are used in
    the calculation of the ewm mean.

    Parameters
    ----------
    times : str, np.ndarray, Series, default None
        Times corresponding to the observations. Must be monotonically increasing
        and ``datetime64[ns]`` dtype.
    halflife : float, str, timedelta, optional
        Half-life specifying the decay

    Returns
    -------
    np.ndarray
        Diff of the times divided by the half-life
    dtype)	r1   asarrayviewint64float64r4   r   valuediff)timesr7   _times	_halflifes       r;   _calculate_deltasrJ   l   sR    2 ZZ

288BJJF i)//0I776?Y&&r=   c                      e Zd ZdZg dZ	 	 	 	 	 	 	 	 	 	 d0dd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d1 fdZ	 	 	 	 	 	 	 	 d2dZd3dZ	 d4	 d5dZ e	e
d	    ed
       ed      dd       fd       ZeZ e	e ed      ee e       e ed      e ed      e ed       ej.                  ddd      ddd      	 d6ddd	 d7d       Z e	e ed      ee e       e ed      e ed      e ed       ej.                  ddd      ddd      	 d6ddd	 d7d       Z e	e ed       ed      j/                  ddd      eee ed      e ed      edd  dd!d"      d8d9d#       Zd6d:d$Z e	e ed       ed      j/                  ddd      eee ed      e ed      edd  dd%d&      d8d9d'       Z e	e ed       ed(      j/                  ddd      ee ed      e ed      edd  dd)d*      	 	 	 	 d;	 	 	 	 	 	 	 d<d+       Z e	e ed       ed,      j/                  ddd      ee ed      e ed      edd  dd-d.      	 	 	 d=	 	 	 	 	 d>d/       Z xZS )?ExponentialMovingWindowa  
    Provide exponentially weighted (EW) calculations.

    Exactly one of ``com``, ``span``, ``halflife``, or ``alpha`` must be
    provided if ``times`` is not provided. If ``times`` is provided,
    ``halflife`` and one of ``com``, ``span`` or ``alpha`` may be provided.

    Parameters
    ----------
    com : float, optional
        Specify decay in terms of center of mass

        :math:`\alpha = 1 / (1 + com)`, for :math:`com \geq 0`.

    span : float, optional
        Specify decay in terms of span

        :math:`\alpha = 2 / (span + 1)`, for :math:`span \geq 1`.

    halflife : float, str, timedelta, optional
        Specify decay in terms of half-life

        :math:`\alpha = 1 - \exp\left(-\ln(2) / halflife\right)`, for
        :math:`halflife > 0`.

        If ``times`` is specified, a timedelta convertible unit over which an
        observation decays to half its value. Only applicable to ``mean()``,
        and halflife value will not apply to the other functions.

        .. versionadded:: 1.1.0

    alpha : float, optional
        Specify smoothing factor :math:`\alpha` directly

        :math:`0 < \alpha \leq 1`.

    min_periods : int, default 0
        Minimum number of observations in window required to have a value;
        otherwise, result is ``np.nan``.

    adjust : bool, default True
        Divide by decaying adjustment factor in beginning periods to account
        for imbalance in relative weightings (viewing EWMA as a moving average).

        - When ``adjust=True`` (default), the EW function is calculated using weights
          :math:`w_i = (1 - \alpha)^i`. For example, the EW moving average of the series
          [:math:`x_0, x_1, ..., x_t`] would be:

        .. math::
            y_t = \frac{x_t + (1 - \alpha)x_{t-1} + (1 - \alpha)^2 x_{t-2} + ... + (1 -
            \alpha)^t x_0}{1 + (1 - \alpha) + (1 - \alpha)^2 + ... + (1 - \alpha)^t}

        - When ``adjust=False``, the exponentially weighted function is calculated
          recursively:

        .. math::
            \begin{split}
                y_0 &= x_0\\
                y_t &= (1 - \alpha) y_{t-1} + \alpha x_t,
            \end{split}
    ignore_na : bool, default False
        Ignore missing values when calculating weights.

        - When ``ignore_na=False`` (default), weights are based on absolute positions.
          For example, the weights of :math:`x_0` and :math:`x_2` used in calculating
          the final weighted average of [:math:`x_0`, None, :math:`x_2`] are
          :math:`(1-\alpha)^2` and :math:`1` if ``adjust=True``, and
          :math:`(1-\alpha)^2` and :math:`\alpha` if ``adjust=False``.

        - When ``ignore_na=True``, weights are based
          on relative positions. For example, the weights of :math:`x_0` and :math:`x_2`
          used in calculating the final weighted average of
          [:math:`x_0`, None, :math:`x_2`] are :math:`1-\alpha` and :math:`1` if
          ``adjust=True``, and :math:`1-\alpha` and :math:`\alpha` if ``adjust=False``.

    axis : {0, 1}, default 0
        If ``0`` or ``'index'``, calculate across the rows.

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

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

    times : str, np.ndarray, Series, default None

        .. versionadded:: 1.1.0

        Only applicable to ``mean()``.

        Times corresponding to the observations. Must be monotonically increasing and
        ``datetime64[ns]`` dtype.

        If 1-D array like, a sequence with the same shape as the observations.

        .. deprecated:: 1.4.0
            If str, the name of the column in the DataFrame representing the times.

    method : str {'single', 'table'}, default 'single'
        .. versionadded:: 1.4.0

        Execute the rolling operation per single column or row (``'single'``)
        or over the entire object (``'table'``).

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

        Only applicable to ``mean()``

    Returns
    -------
    ``ExponentialMovingWindow`` subclass

    See Also
    --------
    rolling : Provides rolling window calculations.
    expanding : Provides expanding transformations.

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

    >>> df.ewm(com=0.5).mean()
              B
    0  0.000000
    1  0.750000
    2  1.615385
    3  1.615385
    4  3.670213
    >>> df.ewm(alpha=2 / 3).mean()
              B
    0  0.000000
    1  0.750000
    2  1.615385
    3  1.615385
    4  3.670213

    **adjust**

    >>> df.ewm(com=0.5, adjust=True).mean()
              B
    0  0.000000
    1  0.750000
    2  1.615385
    3  1.615385
    4  3.670213
    >>> df.ewm(com=0.5, adjust=False).mean()
              B
    0  0.000000
    1  0.666667
    2  1.555556
    3  1.555556
    4  3.650794

    **ignore_na**

    >>> df.ewm(com=0.5, ignore_na=True).mean()
              B
    0  0.000000
    1  0.750000
    2  1.615385
    3  1.615385
    4  3.225000
    >>> df.ewm(com=0.5, ignore_na=False).mean()
              B
    0  0.000000
    1  0.750000
    2  1.615385
    3  1.615385
    4  3.670213

    **times**

    Exponentially weighted mean with weights calculated with a timedelta ``halflife``
    relative to ``times``.

    >>> times = ['2020-01-01', '2020-01-03', '2020-01-10', '2020-01-15', '2020-01-17']
    >>> df.ewm(halflife='4 days', times=pd.DatetimeIndex(times)).mean()
              B
    0  0.000000
    1  0.585786
    2  1.523889
    3  1.523889
    4  3.233686
    )
comr6   r7   r8   min_periodsadjust	ignore_naaxisrG   methodN	selectionc          
     H   t         |   ||dnt        t        |      d      d dd ||	|       || _        || _        || _        || _        || _        || _	        |
| _
        | j                  | j                  st        d      t        | j                  t              rLt        j                  dt         t#                      t%        d| j&                  | j                           | _
        t)        | j                        st+        d      t-        | j                        t-        |      k7  rt+        d	      t        | j                  t        t.        j0                  t2        j4                  f      st+        d
      t7        | j                        j9                         rt+        d      t;        | j                  | j                        | _        t?        j@                  | j                  | j
                  | j                        dkD  r2tC        | j                  | j
                  d | j                        | _"        y d| _"        y | j                  Dt        | j                  t        t.        j0                  t2        j4                  f      rt+        d      t3        jF                  t        | jH                  jJ                  | jL                     dz
  d      t2        jN                        | _        tC        | j                  | j
                  | j                  | j                        | _"        y )Nr,   F)objrN   oncenterclosedrR   rQ   rT   z)times is not supported with adjust=False.zSpecifying times as a string column label is deprecated and will be removed in a future version. Pass the column into times instead.
stacklevelr   z#times must be datetime64[ns] dtype.z,times must be the same length as the object.z/halflife must be a timedelta convertible objectz$Cannot convert NaT values to integerr   g      ?zKhalflife can only be a timedelta convertible argument if times is not None.r?   )(super__init__maxintrM   r6   r7   r8   rO   rP   rG   NotImplementedError
isinstancestrwarningswarnFutureWarningr   r   _selected_objr   r0   lendatetime	timedeltar1   timedelta64r   anyrJ   _deltasr.   r/   r<   _comonesrV   shaperQ   rD   )selfrV   rM   r6   r7   r8   rN   rO   rP   rQ   rG   rR   rT   	__class__s                r;   r]   z ExponentialMovingWindow.__init__^  sb     	(0c#k:JA6N 	 		
 	 
"
::!;;)*UVV$**c*. "/1 "(D,>,>tzz,JK
)$**5 !FGG4::#c(* !OPPdmmc83E3Er~~-VW !RSSDJJ##% !GHH,TZZGDL $$TXXtyy$**EI.txxD$**U		}}(ZX%7%7H. !) 
 77DHHNN499-115RZZDL + 		

DIr=   c                     y N )rp   startendnum_valss       r;   _check_window_boundsz,ExponentialMovingWindow._check_window_bounds  s    
 	r=   c                    t               S )z[
        Return an indexer class that will compute the window start and end bounds
        )r   rp   s    r;   _get_window_indexerz+ExponentialMovingWindow._get_window_indexer  s     .//r=   c                   t        | j                  | j                  | j                  | j                  | j
                  | j                  | j                  | j                  | j                  | j                  ||| j                        S )a  
        Return an ``OnlineExponentialMovingWindow`` object to calculate
        exponentially moving window aggregations in an online method.

        .. versionadded:: 1.3.0

        Parameters
        ----------
        engine: str, default ``'numba'``
            Execution engine to calculate online aggregations.
            Applies to all supported aggregation methods.

        engine_kwargs : dict, default None
            Applies to all supported aggregation methods.

            * 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 the function

        Returns
        -------
        OnlineExponentialMovingWindow
        )rV   rM   r6   r7   r8   rN   rO   rP   rQ   rG   engineengine_kwargsrT   )OnlineExponentialMovingWindowrV   rM   r6   r7   r8   rN   rO   rP   rQ   rG   
_selection)rp   r}   r~   s      r;   onlinezExponentialMovingWindow.online  sf    8 -]]**((;;nn**'oo
 	
r=   	aggregatezV
        See Also
        --------
        pandas.DataFrame.rolling.aggregate
        a  
        Examples
        --------
        >>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]})
        >>> df
           A  B  C
        0  1  4  7
        1  2  5  8
        2  3  6  9

        >>> df.ewm(alpha=0.5).mean()
                  A         B         C
        0  1.000000  4.000000  7.000000
        1  1.666667  4.666667  7.666667
        2  2.428571  5.428571  8.428571
        zSeries/Dataframe )see_alsoexamplesklassrQ   c                *    t        |   |g|i |S rs   )r\   r   )rp   funcargskwargsrq   s       r;   r   z!ExponentialMovingWindow.aggregate  s    > w 7777r=   
ParametersReturnszSee AlsoNotes
r,   ewmz"(exponential weighted moment) meanmean)window_methodaggregation_description
agg_method)r}   r~   c          
     t   t        t        |       d||       t        |      ry| j                  dk(  rt        }nt
        } |d
i t        |      | j                  | j                  | j                  t        | j                        dd}| j                  |d      S |dv r|t        d      t        j                  d||       | j                   d n| j                  }t#        t$        j&                  | j                  | j                  | j                  |d      }	| j                  |	d|      S t        d	      )Nr   singleTrM   rO   rP   deltas	normalizenamecythonN+cython engine does not accept engine_kwargsr   numeric_only)engine must be either 'numba' or 'cython'rt   )r   typer   rR   r%   r&   r   rm   rO   rP   tuplerl   _applyr0   nvvalidate_window_funcrG   r   window_aggregationsr   
rp   r   r}   r~   r   r   r   ewm_funcr   window_funcs
             r;   r   zExponentialMovingWindow.mean  s   2 	#4:vtVD6"{{h&.4 #M2II{{..T\\*H ;;xf;55''( !NOO##FD&9!ZZ/TT\\F!#''II{{..K ;;{l;SSHIIr=   z!(exponential weighted moment) sumsumc          
        t        t        |       d||       | j                  st        d      t	        |      ry| j
                  dk(  rt        }nt        } |di t        |      | j                  | j                  | j                  t        | j                        dd}| j                  |d      S |dv r|t        d      t        j                   d||       | j"                  d n| j                  }t%        t&        j(                  | j                  | j                  | j                  |d      }	| j                  |	d|	      S t        d
      )Nr   z(sum is not implemented with adjust=Falser   Fr   r   r   r   r   r   rt   )r   r   rO   r`   r   rR   r%   r&   r   rm   rP   r   rl   r   r0   r   r   rG   r   r   r   r   s
             r;   r   zExponentialMovingWindow.sumI  s.   2 	#4:udFC{{%&PQQ6"{{h&.4 #M2II{{..T\\*H ;;xe;44''( !NOO##E48!ZZ/TT\\F!#''II{{..K ;;{\;RRHIIr=   zc
        bias : bool, default False
            Use a standard estimation bias correction.
        z0(exponential weighted moment) standard deviationstdc                P   t        t        |       d||       t        j                  d||       |rY| j                  j
                  dk(  r@t        | j                  j                        s!t        t        |       j                   d      t         | j                  d||d|      S )Nr   r,   z$.std does not implement numeric_only)biasr   rt   )r   r   r   r   rf   ndimr   r@   r`   __name__r   var)rp   r   r   r   r   s        r;   r   zExponentialMovingWindow.std  s    * 	#4:udFC
tV4""''1,$T%7%7%=%=> &:&&''KL  XTXXM4lMfMNNr=   c                v    t        j                  dt        t                       | j                  |g|i |S )NzGvol is deprecated will be removed in a future version. Use std instead.rZ   )rc   rd   re   r   r   rp   r   r   r   s       r;   volzExponentialMovingWindow.vol  s;    # ')	
 txx.t.v..r=   z&(exponential weighted moment) variancer   c                   t        t        |       d||       t        j                  d||       t        j
                  }t        || j                  | j                  | j                  |      fd}| j                  |d|      S )Nr   )rM   rO   rP   r   c                     | ||||       S rs   rt   )valuesbeginrv   rN   wfuncs       r;   var_funcz-ExponentialMovingWindow.var.<locals>.var_func  s    [&AAr=   r   )r   r   r   r   r   ewmcovr   rm   rO   rP   r   )rp   r   r   r   r   r   r   r   s          @r;   r   zExponentialMovingWindow.var  sv    * 	#4:udFC
tV4)00		;;nn
	B {{8%l{KKr=   a  
        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 MultiIndex DataFrame in the case of DataFrame
            inputs. In the case of missing elements, only complete pairwise
            observations will be used.
        bias : bool, default False
            Use a standard estimation bias correction.
        z/(exponential weighted moment) sample covariancecovc                     ddl m t        t               dd |        j	                  d|        fd} j                   j                  ||||      S )Nr   r   r   c                   j                  |       }j                  |      }j                         }j                  j                  n|j                  }|j	                  t        |      |j                  j                  j                        \  }}t        j                  |||j                  |j                  j                  j                  
	      } 	|| j                  | j                        S )N
num_valuesrN   rX   rY   stepindexr   )_prep_valuesr{   rN   window_sizeget_window_boundsrg   rX   rY   r   r   r   rm   rO   rP   r   r   )xyx_arrayy_arraywindow_indexerrN   ru   rv   resultr   r   rp   s            r;   cov_funcz-ExponentialMovingWindow.cov.<locals>.cov_func  s    ''*G''*G!557N ##/   #// 
 (99w<'{{{{YY : JE3 )//   		F &aff==r=   pandasr   r   r   _validate_numeric_only_apply_pairwiserf   )rp   otherpairwiser   r   r   r   r   s   `  `   @r;   r   zExponentialMovingWindow.cov  sV    J 	""4:udFC##E<8	>> ##x<
 	
r=   aL  
        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 MultiIndex DataFrame in the case of DataFrame
            inputs. In the case of missing elements, only complete pairwise
            observations will be used.
        z0(exponential weighted moment) sample correlationcorrc                     ddl m t        t               dd |        j	                  d|        fd} j                   j                  ||||      S )Nr   r   r   c                2  
 j                  |       }j                  |      }j                         }j                  j                  n|j                  |j	                  t        |      j                  j                  j                        \  

fd}t        j                  d      5   |||      } |||      } |||      }|t        ||z        z  }	d d d         	| j                  | j                        S # 1 sw Y   (xY w)Nr   c                z    t        j                  | |j                  j                  j                  d	      S )NT)r   r   rm   rO   rP   )XYrv   rN   rp   ru   s     r;   _covz<ExponentialMovingWindow.corr.<locals>.cov_func.<locals>._cov\  s=    *11IIKKNN
 
r=   ignore)allr   )r   r{   rN   r   r   rg   rX   rY   r   r1   errstater   r   r   )r   r   r   r   r   r   r   x_vary_varr   rv   rN   ru   r   rp   s             @@@r;   r   z.ExponentialMovingWindow.corr.<locals>.cov_funcK  s
   ''*G''*G!557N ##/   #// 
 (99w<'{{{{YY : JE3 * 47G,Wg.Wg.uUU]33	4
 &aff==4 4s   9-DDr   )rp   r   r   r   r   r   r   s   `     @r;   r   zExponentialMovingWindow.corr$  sW    D 	""4:vtVD##FL9#	>J ##x<
 	
r=   )
NNNNr   TFr   Nr   )rV   r   rM   float | Noner6   r   r7   (float | TimedeltaConvertibleTypes | Noner8   r   rN   
int | NonerO   boolrP   r   rQ   r	   rG   !str | np.ndarray | NDFrame | NonerR   rb   returnNone)ru   
np.ndarrayrv   r   rw   r_   r   r   )r   r   )numbaN)r   r   F)r   r   )FF)r   r   r   r   r   r   NNFFr   DataFrame | Series | Noner   bool | Noner   r   r   r   NNFr   r   r   r   r   r   ) r   
__module____qualname____doc___attributesr]   rx   r{   r   r   r   r   r   aggr!   r   r   r   r$   r   r"   r#   r    replacer   r   r   r   r   r   r   __classcell__rq   s   @r;   rL   rL      s   BHK  !!=A""#37S SS S 	S
 ;S S  S S S S 1S S 
Sj&0<?	0 -1*
	&*
X 	[!
 
$ !9<8=<8 Cl+#%i(j)g&D"a( D& #'J 'J'J#"'JR 	l+#%i(j)g&D"a( C& #)J )J)J#")JV 	l+	

 '$A
i(j)#2 R%(O)(O	/ 	l+	

 '$A
i(j)#2 H%(L)(L" 	l+	
 '$A
i(j)#2 Q7> ,0 $".
(.
 .
 	.

 .
;:.
` 	l+	
 '$A
i(j)#2 R3: ,0 $"	3
(3
 3
 	3
763
r=   rL   c                  d     e Zd ZdZej
                  ej
                  z   Zddd fdZddZ xZ	S )ExponentialMovingWindowGroupbyzF
    Provide an exponential moving window groupby implementation.
    N)_grouperc               L   t        |   |g|d|i| |j                  s| j                  ut	        j
                  t        | j                  j                  j                                     }t        | j                  j                  |      | j                        | _        y y y )Nr   )r\   r]   emptyrG   r1   concatenatelistr   indicesr   rJ   taker7   rl   )rp   rV   r   r   r   groupby_orderrq   s         r;   r]   z'ExponentialMovingWindowGroupby.__init__|  s    AtAhA&AyyTZZ3NN40E0E0L0L0N+OPM,

.DL 4yr=   c                P    t        | j                  j                  t              }|S )z
        Return an indexer class that will compute the window start and end bounds

        Returns
        -------
        GroupbyIndexer
        )groupby_indicesr   )r   r   r  r   )rp   r   s     r;   r{   z2ExponentialMovingWindowGroupby._get_window_indexer  s&     ( MM119
 r=   r   r   )r   r   )
r   r   r   r   rL   r   r*   r]   r{   r   r   s   @r;   r   r   u  s.     *558I8U8UUK,0 	r=   r   c                       e Zd Z	 	 	 	 	 	 	 	 	 	 	 ddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZddZd ZdddZ	 	 	 d	 	 	 	 	 ddZ	 	 	 	 d	 	 	 	 	 	 	 ddZddd	Z	ddd
dZ
 xZS )r   NrS   c               (   |
t        d      t        | 	  |||||||||	|
|       t        | j                  | j
                  | j                  | j                  |j                        | _	        t        |      r|| _        || _        y t        d      )Nz0times is not implemented with online operations.)rV   rM   r6   r7   r8   rN   rO   rP   rQ   rG   rT   z$'numba' is the only supported engine)r`   r\   r]   r'   rm   rO   rP   rQ   ro   _meanr   r}   r~   r0   )rp   rV   rM   r6   r7   r8   rN   rO   rP   rQ   rG   r}   r~   rT   rq   s                 r;   r]   z&OnlineExponentialMovingWindow.__init__  s    " %B  	# 	 	
 "IIt{{DNNDIIsyy

 6" DK!.DCDDr=   c                8    | j                   j                          y)z=
        Reset the state captured by `update` calls.
        N)r
  resetrz   s    r;   r  z#OnlineExponentialMovingWindow.reset  s     	

r=   c                    t         S rs   r`   )rp   r   r   r   s       r;   r   z'OnlineExponentialMovingWindow.aggregate      ""r=   c                    t         S rs   r  r   s       r;   r   z!OnlineExponentialMovingWindow.std  r  r=   c                    t         S rs   r  )rp   r   r   r   r   s        r;   r   z"OnlineExponentialMovingWindow.corr  s
     #"r=   c                    t         S rs   r  )rp   r   r   r   r   r   s         r;   r   z!OnlineExponentialMovingWindow.cov  s
     #"r=   c                    t         S rs   r  r   s       r;   r   z!OnlineExponentialMovingWindow.var  r  r=   )updateupdate_timesc                  i }| j                   j                  dk(  rdnd}|t        d      t        j                  t        | j                   j                  | j                  dz
     dz
  d      t        j                        }|| j                  j                  t        d	      d}|j                  |d
<   |r;| j                  j                  t        j                  ddf   }	|j                  |d<   n%| j                  j                  }	|j                  |d<   t        j                   |	|j#                         f      }
nd}| j                   j                  |d
<   |r| j                   j                  |d<   n| j                   j                  |d<   | j                   j%                  t        j                        j#                         }
t'        di t)        | j*                        }| j                  j-                  |r|
n|
ddt        j                  f   || j.                  |      }|s|j1                         }||d } | j                   j2                  |fi |}|S )a[  
        Calculate an online exponentially weighted mean.

        Parameters
        ----------
        update: DataFrame or Series, default None
            New values to continue calculating the
            exponentially weighted mean from the last values and weights.
            Values should be float64 dtype.

            ``update`` needs to be ``None`` the first time the
            exponentially weighted mean is calculated.

        update_times: Series or 1-D np.ndarray, default None
            New times to continue calculating the
            exponentially weighted mean from the last values and weights.
            If ``None``, values are assumed to be evenly spaced
            in time.
            This feature is currently unsupported.

        Returns
        -------
        DataFrame or Series

        Examples
        --------
        >>> df = pd.DataFrame({"a": range(5), "b": range(5, 10)})
        >>> online_ewm = df.head(2).ewm(0.5).online()
        >>> online_ewm.mean()
              a     b
        0  0.00  5.00
        1  0.75  5.75
        >>> online_ewm.mean(update=df.tail(3))
                  a         b
        2  1.615385  6.615385
        3  2.550000  7.550000
        4  3.520661  8.520661
        >>> online_ewm.reset()
        >>> online_ewm.mean()
              a     b
        0  0.00  5.00
        1  0.75  5.75
        r-   TFNz update_times is not implemented.r,   r   r?   z;Must call mean with update=None first before passing updater   columnsr   rt   )rf   r   r`   r1   rn   r^   ro   rQ   rD   r
  last_ewmr0   r   newaxisr  r   r   to_numpyastyper(   r   r~   run_ewmrN   squeeze_constructor)rp   r  r  r   r   result_kwargsis_frameupdate_deltasresult_from
last_valuenp_array	ewma_funcr   s                r;   r   z"OnlineExponentialMovingWindow.mean  s   X --22a74U#%&HIIGGD&&,,TYY];a?C2::M zz""* Q  K%+\\M'"!ZZ00Q?
+1>>i(!ZZ00
(.f%~~z6??3D&EFHK%)%7%7%=%=M'"+/+=+=+E+Ei((,(:(:(?(?f%))00<EEGH3 
 2 23
	 ## Hhq"**}&=	
 ^^%F%0##00I=Ir=   )NNNNr   TFr   Nr   N)rV   r   rM   r   r6   r   r7   r   r8   r   rN   r   rO   r   rP   r   rQ   r	   rG   r   r}   rb   r~   zdict[str, bool] | Noner   r   r  r   r   r   r   r   r   )r   r   r   r]   r  r   r   r   r   r   r   r   r   s   @r;   r   r     sQ    !!=A""#3704)E )E)E )E 	)E
 ;)E )E  )E )E )E )E 1)E )E .)E  
!)EV##
 ,0 $"	#(# # 	# ,0 $"#(# # 	#
 ## "&D W Wr=   r   )
r5   r   r6   r   r7   r   r8   r   r   r4   )rG   r   r7   r   r   r   )N
__future__r   rh   	functoolsr   textwrapr   typingr   r   rc   numpyr1   pandas._libs.tslibsr    pandas._libs.window.aggregations_libswindowaggregationsr   pandas._typingr	   r
   r   r   r   pandas.core.genericr   pandas.compat.numpyr   r   pandas.util._decoratorsr   pandas.util._exceptionsr   pandas.core.dtypes.commonr   r   pandas.core.dtypes.missingr   pandas.core.commoncorer.   pandas.core.indexers.objectsr   r   r   pandas.core.util.numba_r   r   pandas.core.window.commonr   r   pandas.core.window.docr   r   r   r   r   r    r!   r"   r#   r$   pandas.core.window.numba_r%   r&   pandas.core.window.onliner'   r(   pandas.core.window.rollingr)   r*   r<   rJ   rL   r   r   rt   r=   r;   <module>r@     s   "      ) > >
 (+ . ' 4 , # # 
  
  	
 B','6' '@f
j f
R%68O Be$; er=   