HOME


sh-3ll 1.0
DIR:/usr/local/lib64/python3.6/site-packages/pandas/core/window/__pycache__/
Upload File :
Current File : //usr/local/lib64/python3.6/site-packages/pandas/core/window/__pycache__/ewm.cpython-36.pyc
3

���hQA�@sddlZddlmZddlmZddlmZmZddlZ	ddl
mZddlj
jjZddlmZmZddlmZddlmZmZmZdd	lmZdd
lmZddlm Z ddl!j"j#Z#ddl$m%Z%m&Z&m'Z'dd
l(m)Z)m*Z*dZ+ee,ee,ee,ee,e,d�dd�Z-Gdd�de*�Z.dS)�N)�partial)�dedent)�Optional�Union)�	Timedelta)�
FrameOrSeries�TimedeltaConvertibleTypes)�function)�Appender�Substitution�doc)�is_datetime64_ns_dtype)�ABCDataFrame)�	DataError)�
_doc_template�_shared_docs�zsqrt)�_flex_binary_moment�_Rollingz�
        Parameters
        ----------
        bias : bool, default False
            Use a standard estimation bias correction.
        *args, **kwargs
            Arguments and keyword arguments to be passed into func.
)�comass�span�halflife�alpha�returncCs�tj||||�}|dkr td��|dk	r:|dkr�td��n�|dk	r`|dkrRtd��|dd}nt|dk	r�|dkrxtd��dtjtjd�|�}d|d}n6|dk	r�|dks�|dkr�td	��d
||}ntd��t|�S)N�z8comass, span, halflife, and alpha are mutually exclusiverz comass must satisfy: comass >= 0zspan must satisfy: span >= 1g@z#halflife must satisfy: halflife > 0g�?z"alpha must satisfy: 0 < alpha <= 1g�?z1Must pass one of comass, span, halflife, or alpha)�common�count_not_none�
ValueError�np�exp�log�float)rrrrZvalid_countZdecay�r"�8/tmp/pip-build-5_djhm0z/pandas/pandas/core/window/ewm.py�get_center_of_mass s*
r$cs�eZdZdZdddddgZd.eeeeeeeefeee	e
e
e	eeeej
efd�	dd
�Zedd��Zed�Zed�Zeedeedddd��fdd��ZeZdd�Zeddd�ee�dd���Zeddd�ee�ee�d/e
d �d!d"����ZeZ edd#d�ee�ee�d0e
d �d$d%����Z!edd&d�ee�d1eeej
efee
e
d'�d(d)���Z"edd*d�ee�d2eeej
efee
d+�d,d-���Z#�Z$S)3�ExponentialMovingWindowa�
    Provide exponential weighted (EW) functions.

    Available EW functions: ``mean()``, ``var()``, ``std()``, ``corr()``, ``cov()``.

    Exactly one parameter: ``com``, ``span``, ``halflife``, or ``alpha`` must 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, the time unit (str or timedelta) 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 NA).
    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; specify ``True`` to reproduce
        pre-0.15.0 behavior.

        - 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`` (reproducing pre-0.15.0 behavior), 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
        The axis to use. The value 0 identifies the rows, and 1
        identifies the columns.
    times : str, np.ndarray, Series, default None

        .. versionadded:: 1.1.0

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

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

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

        Only applicable to ``mean()``.

    Returns
    -------
    DataFrame
        A Window sub-classed for the particular operation.

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

    Notes
    -----

    More details can be found at:
    :ref:`Exponentially weighted windows <stats.moments.exponentially_weighted>`.

    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

    Specifying ``times`` with a timedelta ``halflife`` when computing mean.

    >>> 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
    �com�min_periods�adjust�	ignore_na�axisNrTF)	r&rrrr'r(r)r*�timescCs|||_tt|�d�|_||_||_|	|_d|_|
dk	r�t|
t	�rN|j
|
}
t|
�s^td��t
|
�t
|�krvtd��t|t	tjf�s�td��tj|
jtj��|_t|�j|_tj|||�dkr�t||d|�|_nd|_n<|dk	r�t|t	tjf�r�td��d|_d|_t||||�|_dS)Nrz#times must be datetime64[ns] dtype.z,times must be the same length as the object.z6halflife must be a string or datetime.timedelta objectrzKhalflife can only be a timedelta convertible argument if times is not None.)�obj�max�intr'r(r)r*�on�
isinstance�str�
_selected_objr
r�len�datetime�	timedeltarZasarrayZastypeZint64r+r�valuerrrr$r&)�selfr,r&rrrr'r(r)r*r+r"r"r#�__init__�s8


z ExponentialMovingWindow.__init__cCstS)N)r%)r7r"r"r#�_constructor�sz$ExponentialMovingWindow._constructorzF
    See Also
    --------
    pandas.DataFrame.rolling.aggregate
    ad
    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
    �	aggregate�zSeries/Dataframe)Zsee_alsoZexamplesZversionadded�klassr*cst�j|f|�|�S)N)�superr:)r7�func�args�kwargs)�	__class__r"r#r:s	z!ExponentialMovingWindow.aggregatecCs�|j|j�\}}t|�}g}g}x�t|�D]�\}}y|j|j�}	WnPttfk
r�}
z0t|t	�rx|j
|j�||=w*n
td�|
�WYdd}
~
XnX|	j
dkr�|j|	j��q*|jtj||j|	��q*W|j||||�S)a$
        Rolling statistical measure using supplied function. Designed to be
        used with passed-in Cython array-based functions.

        Parameters
        ----------
        func : str/callable to apply

        Returns
        -------
        y : same type as input argument
        zNo numeric types to aggregateNr)Z_create_blocksr2�list�	enumerate�_prep_values�values�	TypeError�NotImplementedErrorr0r�extend�columnsr�size�append�copyrZapply_along_axisr*Z
_wrap_results)r7r>�blocksr,Z
block_list�results�exclude�i�brE�errr"r"r#�_apply$s$


zExponentialMovingWindow._applyZewm�mean)�name�	func_namecOshtjd||�|jdk	r:|jd�}t||j|j|jd�}n$|jd�}t||j|j|j	|jd�}|j
|�S)z�
        Exponential weighted moving average.

        Parameters
        ----------
        *args, **kwargs
            Arguments and keyword arguments to be passed into func.
        rTNZ	ewma_time)�minpr+rZewma)r&r(r)rW)�nv�validate_window_funcr+Z_get_roll_funcrr'rr&r(r)rS)r7r?r@Zwindow_funcr"r"r#rTJs 



zExponentialMovingWindow.mean�std)�biascOs&tjd||�t|jfd|i|���S)z5
        Exponential weighted moving stddev.
        rZr[)rXrYr�var)r7r[r?r@r"r"r#rZiszExponentialMovingWindow.stdr\cs&tjd||���fdd�}�j|�S)z7
        Exponential weighted moving variance.
        r\cstj||�j�j�j�j��S)N)�window_aggregations�ewmcovr&r(r)r')�arg)r[r7r"r#�f~sz&ExponentialMovingWindow.var.<locals>.f)rXrYrS)r7r[r?r@r`r")r[r7r#r\uszExponentialMovingWindow.var�cov)�other�pairwiser[csN|dkr�j}|dkrdn|}�j|�}��fdd�}t�j|j|t|�d�S)aM
        Exponential weighted sample covariance.

        Parameters
        ----------
        other : Series, DataFrame, or ndarray, 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.
        **kwargs
           Keyword arguments to be passed into func.
        NTcsD�j|�}�j|�}tj|j�|j��j�j�j�j��}|j|�S)N)	�
_shallow_copyr]r^rDr&r(r)r'�_wrap_result)�X�Yra)r[r7r"r#�_get_cov�s

z-ExponentialMovingWindow.cov.<locals>._get_cov)rc)r2rdr�bool)r7rbrcr[r@rhr")r[r7r#ra�s
zExponentialMovingWindow.cov�corr)rbrccsL|dkr�j}|dkrdn|}�j|�}�fdd�}t�j|j|t|�d�S)a�
        Exponential weighted sample correlation.

        Parameters
        ----------
        other : Series, DataFrame, or ndarray, 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.
        **kwargs
           Keyword arguments to be passed into func.
        NTc	s��j|�}�j|�}�fdd�}|j�}|j�}tjdd��4|||�}|||�}|||�}|t||�}WdQRX|j|�S)Ncstj||�j�j�j�jd�S)Nr)r]r^r&r(r)r')�x�y)r7r"r#�_cov�sz=ExponentialMovingWindow.corr.<locals>._get_corr.<locals>._cov�ignore)�all)rdrDrZerrstaterre)	rfrgrmZx_valuesZy_valuesraZx_varZy_varrj)r7r"r#�	_get_corr�s




z/ExponentialMovingWindow.corr.<locals>._get_corr)rc)r2rdrri)r7rbrcr@rpr")r7r#rj�s
zExponentialMovingWindow.corr)	NNNNrTFrN)F)F)NNF)NN)%�__name__�
__module__�__qualname__�__doc__�_attributesrr!rrr.rir1rZndarrayrr8�propertyr9rZ_agg_see_also_docZ_agg_examples_docrrr:ZaggrSrr
rrT�_bias_templaterZZvolr\rarj�
__classcell__r"r")rAr#r%As\H&&



*/
r%)/r4�	functoolsr�textwraprZtypingrrZnumpyrZpandas._libs.tslibsrZ pandas._libs.window.aggregationsZ_libsZwindowZaggregationsr]Zpandas._typingrrZpandas.compat.numpyr	rXZpandas.util._decoratorsr
rrZpandas.core.dtypes.commonr
Zpandas.core.dtypes.genericrZpandas.core.baserZpandas.core.common�corerZpandas.core.window.commonrrrZpandas.core.window.rollingrrrwr!r$r%r"r"r"r#�<module>s,