1from __future__ import annotations
2
3import datetime
4from functools import partial
5from typing import (
6 TYPE_CHECKING,
7 cast,
8)
9
10import numpy as np
11
12from pandas._libs.tslibs import Timedelta
13import pandas._libs.window.aggregations as window_aggregations
14from pandas.util._decorators import set_module
15
16from pandas.core.dtypes.common import (
17 is_datetime64_dtype,
18 is_numeric_dtype,
19)
20from pandas.core.dtypes.dtypes import DatetimeTZDtype
21from pandas.core.dtypes.generic import ABCSeries
22from pandas.core.dtypes.missing import isna
23
24from pandas.core import common
25from pandas.core.arrays.datetimelike import dtype_to_unit
26from pandas.core.indexers.objects import (
27 BaseIndexer,
28 ExponentialMovingWindowIndexer,
29 GroupbyIndexer,
30)
31from pandas.core.util.numba_ import (
32 get_jit_arguments,
33 maybe_use_numba,
34)
35from pandas.core.window.common import zsqrt
36from pandas.core.window.numba_ import (
37 generate_numba_ewm_func,
38 generate_numba_ewm_table_func,
39)
40from pandas.core.window.online import (
41 EWMMeanState,
42 generate_online_numba_ewma_func,
43)
44from pandas.core.window.rolling import (
45 BaseWindow,
46 BaseWindowGroupby,
47)
48
49if TYPE_CHECKING:
50 from pandas._typing import (
51 TimedeltaConvertibleTypes,
52 TimeUnit,
53 npt,
54 )
55
56 from pandas import (
57 DataFrame,
58 Series,
59 )
60 from pandas.core.generic import NDFrame
61
62
63def get_center_of_mass(
64 comass: float | None,
65 span: float | None,
66 halflife: float | None,
67 alpha: float | None,
68) -> float:
69 valid_count = common.count_not_none(comass, span, halflife, alpha)
70 if valid_count > 1:
71 raise ValueError("comass, span, halflife, and alpha are mutually exclusive")
72
73 # Convert to center of mass; domain checks ensure 0 < alpha <= 1
74 if comass is not None:
75 if comass < 0:
76 raise ValueError("comass must satisfy: comass >= 0")
77 elif span is not None:
78 if span < 1:
79 raise ValueError("span must satisfy: span >= 1")
80 comass = (span - 1) / 2
81 elif halflife is not None:
82 if halflife <= 0:
83 raise ValueError("halflife must satisfy: halflife > 0")
84 decay = 1 - np.exp(np.log(0.5) / halflife)
85 comass = 1 / decay - 1
86 elif alpha is not None:
87 if alpha <= 0 or alpha > 1:
88 raise ValueError("alpha must satisfy: 0 < alpha <= 1")
89 comass = (1 - alpha) / alpha
90 else:
91 raise ValueError("Must pass one of comass, span, halflife, or alpha")
92
93 return float(comass)
94
95
96def _calculate_deltas(
97 times: np.ndarray | NDFrame,
98 halflife: float | TimedeltaConvertibleTypes | None,
99) -> npt.NDArray[np.float64]:
100 """
101 Return the diff of the times divided by the half-life. These values are used in
102 the calculation of the ewm mean.
103
104 Parameters
105 ----------
106 times : np.ndarray, Series
107 Times corresponding to the observations. Must be monotonically increasing
108 and ``datetime64[ns]`` dtype.
109 halflife : float, str, timedelta, optional
110 Half-life specifying the decay
111
112 Returns
113 -------
114 np.ndarray
115 Diff of the times divided by the half-life
116 """
117 unit = dtype_to_unit(times.dtype)
118 unit = cast("TimeUnit", unit)
119 if isinstance(times, ABCSeries):
120 times = times._values
121 _times = np.asarray(times.view(np.int64), dtype=np.float64)
122 _halflife = float(Timedelta(halflife).as_unit(unit)._value)
123 return np.diff(_times) / _halflife
124
125
126@set_module("pandas.api.typing")
127class ExponentialMovingWindow(BaseWindow):
128 r"""
129 Provide exponentially weighted (EW) calculations.
130
131 Exactly one of ``com``, ``span``, ``halflife``, or ``alpha`` must be
132 provided if ``times`` is not provided. If ``times`` is provided and ``adjust=True``,
133 ``halflife`` and one of ``com``, ``span`` or ``alpha`` may be provided.
134 If ``times`` is provided and ``adjust=False``, ``halflife`` must be the only
135 provided decay-specification parameter.
136
137 Parameters
138 ----------
139 com : float, optional
140 Specify decay in terms of center of mass
141
142 :math:`\alpha = 1 / (1 + com)`, for :math:`com \geq 0`.
143
144 span : float, optional
145 Specify decay in terms of span
146
147 :math:`\alpha = 2 / (span + 1)`, for :math:`span \geq 1`.
148
149 halflife : float, str, timedelta, optional
150 Specify decay in terms of half-life
151
152 :math:`\alpha = 1 - \exp\left(-\ln(2) / halflife\right)`, for
153 :math:`halflife > 0`.
154
155 If ``times`` is specified, a timedelta convertible unit over which an
156 observation decays to half its value. Only applicable to ``mean()``,
157 and halflife value will not apply to the other functions.
158
159 alpha : float, optional
160 Specify smoothing factor :math:`\alpha` directly
161
162 :math:`0 < \alpha \leq 1`.
163
164 min_periods : int, default 0
165 Minimum number of observations in window required to have a value;
166 otherwise, result is ``np.nan``.
167
168 adjust : bool, default True
169 Divide by decaying adjustment factor in beginning periods to account
170 for imbalance in relative weightings (viewing EWMA as a moving average).
171
172 - When ``adjust=True`` (default), the EW function is calculated using weights
173 :math:`w_i = (1 - \alpha)^i`. For example, the EW moving average of the series
174 [:math:`x_0, x_1, ..., x_t`] would be:
175
176 .. math::
177 y_t = \frac{x_t + (1 - \alpha)x_{t-1} + (1 - \alpha)^2 x_{t-2} + ... + (1 -
178 \alpha)^t x_0}{1 + (1 - \alpha) + (1 - \alpha)^2 + ... + (1 - \alpha)^t}
179
180 - When ``adjust=False``, the exponentially weighted function is calculated
181 recursively:
182
183 .. math::
184 \begin{split}
185 y_0 &= x_0\\
186 y_t &= (1 - \alpha) y_{t-1} + \alpha x_t,
187 \end{split}
188 ignore_na : bool, default False
189 Ignore missing values when calculating weights.
190
191 - When ``ignore_na=False`` (default), weights are based on absolute positions.
192 For example, the weights of :math:`x_0` and :math:`x_2` used in calculating
193 the final weighted average of [:math:`x_0`, None, :math:`x_2`] are
194 :math:`(1-\alpha)^2` and :math:`1` if ``adjust=True``, and
195 :math:`(1-\alpha)^2` and :math:`\alpha` if ``adjust=False``.
196
197 - When ``ignore_na=True``, weights are based
198 on relative positions. For example, the weights of :math:`x_0` and :math:`x_2`
199 used in calculating the final weighted average of
200 [:math:`x_0`, None, :math:`x_2`] are :math:`1-\alpha` and :math:`1` if
201 ``adjust=True``, and :math:`1-\alpha` and :math:`\alpha` if ``adjust=False``.
202
203 times : np.ndarray, Series, default None
204
205 Only applicable to ``mean()``.
206
207 Times corresponding to the observations. Must be monotonically increasing and
208 ``datetime64[ns]`` dtype.
209
210 If 1-D array like, a sequence with the same shape as the observations.
211
212 method : str {'single', 'table'}, default 'single'
213 Execute the rolling operation per single column or row (``'single'``)
214 or over the entire object (``'table'``).
215
216 This argument is only implemented when specifying ``engine='numba'``
217 in the method call.
218
219 Only applicable to ``mean()``
220
221 Returns
222 -------
223 pandas.api.typing.ExponentialMovingWindow
224 An instance of ExponentialMovingWindow for further exponentially weighted (EW)
225 calculations, e.g. using the ``mean`` method.
226
227 See Also
228 --------
229 rolling : Provides rolling window calculations.
230 expanding : Provides expanding transformations.
231
232 Notes
233 -----
234 See :ref:`Windowing Operations <window.exponentially_weighted>`
235 for further usage details and examples.
236
237 Examples
238 --------
239 >>> df = pd.DataFrame({'B': [0, 1, 2, np.nan, 4]})
240 >>> df
241 B
242 0 0.0
243 1 1.0
244 2 2.0
245 3 NaN
246 4 4.0
247
248 >>> df.ewm(com=0.5).mean()
249 B
250 0 0.000000
251 1 0.750000
252 2 1.615385
253 3 1.615385
254 4 3.670213
255 >>> df.ewm(alpha=2 / 3).mean()
256 B
257 0 0.000000
258 1 0.750000
259 2 1.615385
260 3 1.615385
261 4 3.670213
262
263 **adjust**
264
265 >>> df.ewm(com=0.5, adjust=True).mean()
266 B
267 0 0.000000
268 1 0.750000
269 2 1.615385
270 3 1.615385
271 4 3.670213
272 >>> df.ewm(com=0.5, adjust=False).mean()
273 B
274 0 0.000000
275 1 0.666667
276 2 1.555556
277 3 1.555556
278 4 3.650794
279
280 **ignore_na**
281
282 >>> df.ewm(com=0.5, ignore_na=True).mean()
283 B
284 0 0.000000
285 1 0.750000
286 2 1.615385
287 3 1.615385
288 4 3.225000
289 >>> df.ewm(com=0.5, ignore_na=False).mean()
290 B
291 0 0.000000
292 1 0.750000
293 2 1.615385
294 3 1.615385
295 4 3.670213
296
297 **times**
298
299 Exponentially weighted mean with weights calculated with a timedelta ``halflife``
300 relative to ``times``.
301
302 >>> times = ['2020-01-01', '2020-01-03', '2020-01-10', '2020-01-15', '2020-01-17']
303 >>> df.ewm(halflife='4 days', times=pd.DatetimeIndex(times)).mean()
304 B
305 0 0.000000
306 1 0.585786
307 2 1.523889
308 3 1.523889
309 4 3.233686
310 """
311
312 _attributes = [
313 "com",
314 "span",
315 "halflife",
316 "alpha",
317 "min_periods",
318 "adjust",
319 "ignore_na",
320 "times",
321 "method",
322 ]
323
324 def __init__(
325 self,
326 obj: NDFrame,
327 com: float | None = None,
328 span: float | None = None,
329 halflife: float | TimedeltaConvertibleTypes | None = None,
330 alpha: float | None = None,
331 min_periods: int | None = 0,
332 adjust: bool = True,
333 ignore_na: bool = False,
334 times: np.ndarray | NDFrame | None = None,
335 method: str = "single",
336 *,
337 selection=None,
338 ) -> None:
339 super().__init__(
340 obj=obj,
341 min_periods=1 if min_periods is None else max(int(min_periods), 1),
342 on=None,
343 center=False,
344 closed=None,
345 method=method,
346 selection=selection,
347 )
348 self.com = com
349 self.span = span
350 self.halflife = halflife
351 self.alpha = alpha
352 self.adjust = adjust
353 self.ignore_na = ignore_na
354 self.times = times
355 if self.times is not None:
356 times_dtype = getattr(self.times, "dtype", None)
357 if not (
358 is_datetime64_dtype(times_dtype)
359 or isinstance(times_dtype, DatetimeTZDtype)
360 ):
361 raise ValueError("times must be datetime64 dtype.")
362 if len(self.times) != len(obj):
363 raise ValueError("times must be the same length as the object.")
364 if not isinstance(self.halflife, (str, datetime.timedelta, np.timedelta64)):
365 raise ValueError("halflife must be a timedelta convertible object")
366 if isna(self.times).any():
367 raise ValueError("Cannot convert NaT values to integer")
368 self._deltas = _calculate_deltas(self.times, self.halflife)
369 # Halflife is no longer applicable when calculating COM
370 # But allow COM to still be calculated if the user passes other decay args
371 if common.count_not_none(self.com, self.span, self.alpha) > 0:
372 if not self.adjust:
373 raise NotImplementedError(
374 "None of com, span, or alpha can be specified if "
375 "times is provided and adjust=False"
376 )
377 self._com = get_center_of_mass(self.com, self.span, None, self.alpha)
378 else:
379 self._com = 1.0
380 else:
381 if self.halflife is not None and isinstance(
382 self.halflife, (str, datetime.timedelta, np.timedelta64)
383 ):
384 raise ValueError(
385 "halflife can only be a timedelta convertible argument if "
386 "times is not None."
387 )
388 # Without times, points are equally spaced
389 self._deltas = np.ones(max(self.obj.shape[0] - 1, 0), dtype=np.float64)
390 self._com = get_center_of_mass(
391 # error: Argument 3 to "get_center_of_mass" has incompatible type
392 # "Union[float, Any, None, timedelta64, signedinteger[_64Bit]]";
393 # expected "Optional[float]"
394 self.com,
395 self.span,
396 self.halflife, # type: ignore[arg-type]
397 self.alpha,
398 )
399
400 def _check_window_bounds(
401 self, start: np.ndarray, end: np.ndarray, num_vals: int
402 ) -> None:
403 # emw algorithms are iterative with each point
404 # ExponentialMovingWindowIndexer "bounds" are the entire window
405 pass
406
407 def _get_window_indexer(self) -> BaseIndexer:
408 """
409 Return an indexer class that will compute the window start and end bounds
410 """
411 return ExponentialMovingWindowIndexer()
412
413 def online(
414 self, engine: str = "numba", engine_kwargs=None
415 ) -> OnlineExponentialMovingWindow:
416 """
417 Return an ``OnlineExponentialMovingWindow`` object to calculate
418 exponentially moving window aggregations in an online method.
419
420 Parameters
421 ----------
422 engine: str, default ``'numba'``
423 Execution engine to calculate online aggregations.
424 Applies to all supported aggregation methods.
425
426 engine_kwargs : dict, default None
427 Applies to all supported aggregation methods.
428
429 * For ``'numba'`` engine, the engine can accept ``nopython``, ``nogil``
430 and ``parallel`` dictionary keys. The values must either be ``True`` or
431 ``False``. The default ``engine_kwargs`` for the ``'numba'`` engine is
432 ``{'nopython': True, 'nogil': False, 'parallel': False}`` and will be
433 applied to the function
434
435 Returns
436 -------
437 OnlineExponentialMovingWindow
438 """
439 return OnlineExponentialMovingWindow(
440 obj=self.obj,
441 com=self.com,
442 span=self.span,
443 halflife=self.halflife,
444 alpha=self.alpha,
445 min_periods=self.min_periods,
446 adjust=self.adjust,
447 ignore_na=self.ignore_na,
448 times=self.times,
449 engine=engine,
450 engine_kwargs=engine_kwargs,
451 selection=self._selection,
452 )
453
454 def aggregate(self, func=None, *args, **kwargs):
455 """
456 Aggregate using one or more operations over the specified axis.
457
458 Parameters
459 ----------
460 func : function, str, list or dict
461 Function to use for aggregating the data. If a function, must either
462 work when passed a Series/Dataframe or when passed to
463 Series/Dataframe.apply.
464
465 Accepted combinations are:
466
467 - function
468 - string function name
469 - list of functions and/or function names, e.g. ``[np.sum, 'mean']``
470 - dict of axis labels -> functions, function names or list of such.
471 *args
472 Positional arguments to pass to `func`.
473 **kwargs
474 Keyword arguments to pass to `func`.
475
476 Returns
477 -------
478 scalar, Series or DataFrame
479
480 The return can be:
481
482 * scalar : when Series.agg is called with single function
483 * Series : when DataFrame.agg is called with a single function
484 * DataFrame : when DataFrame.agg is called with several functions
485
486 See Also
487 --------
488 pandas.DataFrame.rolling.aggregate
489
490 Notes
491 -----
492 The aggregation operations are always performed over an axis, either the
493 index (default) or the column axis. This behavior is different from
494 `numpy` aggregation functions (`mean`, `median`, `prod`, `sum`, `std`,
495 `var`), where the default is to compute the aggregation of the flattened
496 array, e.g., ``numpy.mean(arr_2d)`` as opposed to
497 ``numpy.mean(arr_2d, axis=0)``.
498
499 `agg` is an alias for `aggregate`. Use the alias.
500
501 Functions that mutate the passed object can produce unexpected
502 behavior or errors and are not supported. See :ref:`gotchas.udf-mutation`
503 for more details.
504
505 A passed user-defined-function will be passed a Series for evaluation.
506
507 If ``func`` defines an index relabeling, ``axis`` must be ``0`` or ``index``.
508
509 Examples
510 --------
511 >>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]})
512 >>> df
513 A B C
514 0 1 4 7
515 1 2 5 8
516 2 3 6 9
517
518 >>> df.ewm(alpha=0.5).mean()
519 A B C
520 0 1.000000 4.000000 7.000000
521 1 1.666667 4.666667 7.666667
522 2 2.428571 5.428571 8.428571
523 """
524 return super().aggregate(func, *args, **kwargs)
525
526 agg = aggregate
527
528 def mean(
529 self,
530 numeric_only: bool = False,
531 engine=None,
532 engine_kwargs=None,
533 ):
534 """
535 Calculate the ewm (exponential weighted moment) mean.
536
537 Parameters
538 ----------
539 numeric_only : bool, default False
540 Include only float, int, boolean columns.
541
542 engine : str, default None
543 * ``'cython'`` : Runs the operation through C-extensions from cython.
544 * ``'numba'`` : Runs the operation through JIT compiled code from numba.
545 * ``None`` : Defaults to ``'cython'`` or globally setting
546 ``compute.use_numba``
547
548 engine_kwargs : dict, default None
549 * For ``'cython'`` engine, there are no accepted ``engine_kwargs``
550 * For ``'numba'`` engine, the engine can accept ``nopython``, ``nogil``
551 and ``parallel`` dictionary keys. The values must either be ``True`` or
552 ``False``. The default ``engine_kwargs`` for the ``'numba'`` engine is
553 ``{'nopython': True, 'nogil': False, 'parallel': False}``
554
555 Returns
556 -------
557 Series or DataFrame
558 Return type is the same as the original object with ``np.float64`` dtype.
559
560 See Also
561 --------
562 Series.ewm : Calling ewm with Series data.
563 DataFrame.ewm : Calling ewm with DataFrames.
564 Series.mean : Aggregating mean for Series.
565 DataFrame.mean : Aggregating mean for DataFrame.
566
567 Notes
568 -----
569 See :ref:`window.numba_engine` and :ref:`enhancingperf.numba` for
570 extended documentation and performance considerations for the Numba engine.
571
572 Examples
573 --------
574 >>> ser = pd.Series([1, 2, 3, 4])
575 >>> ser.ewm(alpha=0.2).mean()
576 0 1.000000
577 1 1.555556
578 2 2.147541
579 3 2.775068
580 dtype: float64
581 """
582 if maybe_use_numba(engine):
583 if self.method == "single":
584 func = generate_numba_ewm_func
585 else:
586 func = generate_numba_ewm_table_func
587 ewm_func = func(
588 **get_jit_arguments(engine_kwargs),
589 com=self._com,
590 adjust=self.adjust,
591 ignore_na=self.ignore_na,
592 deltas=tuple(self._deltas),
593 normalize=True,
594 )
595 return self._apply(ewm_func, name="mean")
596 elif engine in ("cython", None):
597 if engine_kwargs is not None:
598 raise ValueError("cython engine does not accept engine_kwargs")
599
600 deltas = None if self.times is None else self._deltas
601 window_func = partial(
602 window_aggregations.ewm,
603 com=self._com,
604 adjust=self.adjust,
605 ignore_na=self.ignore_na,
606 deltas=deltas,
607 normalize=True,
608 )
609 return self._apply(window_func, name="mean", numeric_only=numeric_only)
610 else:
611 raise ValueError("engine must be either 'numba' or 'cython'")
612
613 def sum(
614 self,
615 numeric_only: bool = False,
616 engine=None,
617 engine_kwargs=None,
618 ):
619 """
620 Calculate the ewm (exponential weighted moment) sum.
621
622 Parameters
623 ----------
624 numeric_only : bool, default False
625 Include only float, int, boolean columns.
626 engine : str, default None
627 * ``'cython'`` : Runs the operation through C-extensions from cython.
628 * ``'numba'`` : Runs the operation through JIT compiled code from numba.
629 * ``None`` : Defaults to ``'cython'`` or globally setting
630 ``compute.use_numba``
631 engine_kwargs : dict, default None
632 * For ``'cython'`` engine, there are no accepted ``engine_kwargs``
633 * For ``'numba'`` engine, the engine can accept ``nopython``, ``nogil``
634 and ``parallel`` dictionary keys. The values must either be ``True`` or
635 ``False``. The default ``engine_kwargs`` for the ``'numba'`` engine is
636 ``{'nopython': True, 'nogil': False, 'parallel': False}``
637
638 Returns
639 -------
640 Series or DataFrame
641 Return type is the same as the original object with ``np.float64`` dtype.
642
643 See Also
644 --------
645 Series.ewm : Calling ewm with Series data.
646 DataFrame.ewm : Calling ewm with DataFrames.
647 Series.sum : Aggregating sum for Series.
648 DataFrame.sum : Aggregating sum for DataFrame.
649
650 Notes
651 -----
652 See :ref:`window.numba_engine` and :ref:`enhancingperf.numba` for extended
653 documentation and performance considerations for the Numba engine.
654
655 Examples
656 --------
657 >>> ser = pd.Series([1, 2, 3, 4])
658 >>> ser.ewm(alpha=0.2).sum()
659 0 1.000
660 1 2.800
661 2 5.240
662 3 8.192
663 dtype: float64
664 """
665 if not self.adjust:
666 raise NotImplementedError("sum is not implemented with adjust=False")
667 if self.times is not None:
668 raise NotImplementedError("sum is not implemented with times")
669 if maybe_use_numba(engine):
670 if self.method == "single":
671 func = generate_numba_ewm_func
672 else:
673 func = generate_numba_ewm_table_func
674 ewm_func = func(
675 **get_jit_arguments(engine_kwargs),
676 com=self._com,
677 adjust=self.adjust,
678 ignore_na=self.ignore_na,
679 deltas=tuple(self._deltas),
680 normalize=False,
681 )
682 return self._apply(ewm_func, name="sum")
683 elif engine in ("cython", None):
684 if engine_kwargs is not None:
685 raise ValueError("cython engine does not accept engine_kwargs")
686
687 deltas = None if self.times is None else self._deltas
688 window_func = partial(
689 window_aggregations.ewm,
690 com=self._com,
691 adjust=self.adjust,
692 ignore_na=self.ignore_na,
693 deltas=deltas,
694 normalize=False,
695 )
696 return self._apply(window_func, name="sum", numeric_only=numeric_only)
697 else:
698 raise ValueError("engine must be either 'numba' or 'cython'")
699
700 def std(self, bias: bool = False, numeric_only: bool = False):
701 """
702 Calculate the ewm (exponential weighted moment) standard deviation.
703
704 Parameters
705 ----------
706 bias : bool, default False
707 Use a standard estimation bias correction.
708 numeric_only : bool, default False
709 Include only float, int, boolean columns.
710
711 Returns
712 -------
713 Series or DataFrame
714 Return type is the same as the original object with ``np.float64`` dtype.
715
716 See Also
717 --------
718 Series.ewm : Calling ewm with Series data.
719 DataFrame.ewm : Calling ewm with DataFrames.
720 Series.std : Aggregating std for Series.
721 DataFrame.std : Aggregating std for DataFrame.
722
723 Examples
724 --------
725 >>> ser = pd.Series([1, 2, 3, 4])
726 >>> ser.ewm(alpha=0.2).std()
727 0 NaN
728 1 0.707107
729 2 0.995893
730 3 1.277320
731 dtype: float64
732 """
733 if (
734 numeric_only
735 and self._selected_obj.ndim == 1
736 and not is_numeric_dtype(self._selected_obj.dtype)
737 ):
738 # Raise directly so error message says std instead of var
739 raise NotImplementedError(
740 f"{type(self).__name__}.std does not implement numeric_only"
741 )
742 if self.times is not None:
743 raise NotImplementedError("std is not implemented with times")
744 return zsqrt(self.var(bias=bias, numeric_only=numeric_only))
745
746 def var(self, bias: bool = False, numeric_only: bool = False):
747 """
748 Calculate the ewm (exponential weighted moment) variance.
749
750 Parameters
751 ----------
752 bias : bool, default False
753 Use a standard estimation bias correction.
754 numeric_only : bool, default False
755 Include only float, int, boolean columns.
756
757 Returns
758 -------
759 Series or DataFrame
760 Return type is the same as the original object with ``np.float64`` dtype.
761
762 See Also
763 --------
764 Series.ewm : Calling ewm with Series data.
765 DataFrame.ewm : Calling ewm with DataFrames.
766 Series.var : Aggregating var for Series.
767 DataFrame.var : Aggregating var for DataFrame.
768
769 Examples
770 --------
771 >>> ser = pd.Series([1, 2, 3, 4])
772 >>> ser.ewm(alpha=0.2).var()
773 0 NaN
774 1 0.500000
775 2 0.991803
776 3 1.631547
777 dtype: float64
778 """
779 if self.times is not None:
780 raise NotImplementedError("var is not implemented with times")
781 window_func = window_aggregations.ewmcov
782 wfunc = partial(
783 window_func,
784 com=self._com,
785 adjust=self.adjust,
786 ignore_na=self.ignore_na,
787 bias=bias,
788 )
789
790 def var_func(values, begin, end, min_periods):
791 return wfunc(values, begin, end, min_periods, values)
792
793 return self._apply(var_func, name="var", numeric_only=numeric_only)
794
795 def cov(
796 self,
797 other: DataFrame | Series | None = None,
798 pairwise: bool | None = None,
799 bias: bool = False,
800 numeric_only: bool = False,
801 ):
802 """
803 Calculate the ewm (exponential weighted moment) sample covariance.
804
805 Parameters
806 ----------
807 other : Series or DataFrame , optional
808 If not supplied then will default to self and produce pairwise
809 output.
810 pairwise : bool, default None
811 If False then only matching columns between self and other will be
812 used and the output will be a DataFrame.
813 If True then all pairwise combinations will be calculated and the
814 output will be a MultiIndex DataFrame in the case of DataFrame
815 inputs. In the case of missing elements, only complete pairwise
816 observations will be used.
817 bias : bool, default False
818 Use a standard estimation bias correction.
819 numeric_only : bool, default False
820 Include only float, int, boolean columns.
821
822 Returns
823 -------
824 Series or DataFrame
825 Return type is the same as the original object with ``np.float64`` dtype.
826
827 See Also
828 --------
829 Series.ewm : Calling ewm with Series data.
830 DataFrame.ewm : Calling ewm with DataFrames.
831 Series.cov : Aggregating cov for Series.
832 DataFrame.cov : Aggregating cov for DataFrame.
833
834 Examples
835 --------
836 >>> ser1 = pd.Series([1, 2, 3, 4])
837 >>> ser2 = pd.Series([10, 11, 13, 16])
838 >>> ser1.ewm(alpha=0.2).cov(ser2)
839 0 NaN
840 1 0.500000
841 2 1.524590
842 3 3.408836
843 dtype: float64
844 """
845 if self.times is not None:
846 raise NotImplementedError("cov is not implemented with times")
847
848 from pandas import Series
849
850 self._validate_numeric_only("cov", numeric_only)
851
852 def cov_func(x, y):
853 x_array = self._prep_values(x)
854 y_array = self._prep_values(y)
855 window_indexer = self._get_window_indexer()
856 min_periods = (
857 self.min_periods
858 if self.min_periods is not None
859 else window_indexer.window_size
860 )
861 start, end = window_indexer.get_window_bounds(
862 num_values=len(x_array),
863 min_periods=min_periods,
864 center=self.center,
865 closed=self.closed,
866 step=self.step,
867 )
868 result = window_aggregations.ewmcov(
869 x_array,
870 start,
871 end,
872 # error: Argument 4 to "ewmcov" has incompatible type
873 # "Optional[int]"; expected "int"
874 self.min_periods, # type: ignore[arg-type]
875 y_array,
876 self._com,
877 self.adjust,
878 self.ignore_na,
879 bias,
880 )
881 return Series(result, index=x.index, name=x.name, copy=False)
882
883 return self._apply_pairwise(
884 self._selected_obj, other, pairwise, cov_func, numeric_only
885 )
886
887 def corr(
888 self,
889 other: DataFrame | Series | None = None,
890 pairwise: bool | None = None,
891 numeric_only: bool = False,
892 ):
893 """
894 Calculate the ewm (exponential weighted moment) sample correlation.
895
896 Parameters
897 ----------
898 other : Series or DataFrame, optional
899 If not supplied then will default to self and produce pairwise
900 output.
901 pairwise : bool, default None
902 If False then only matching columns between self and other will be
903 used and the output will be a DataFrame.
904 If True then all pairwise combinations will be calculated and the
905 output will be a MultiIndex DataFrame in the case of DataFrame
906 inputs. In the case of missing elements, only complete pairwise
907 observations will be used.
908 numeric_only : bool, default False
909 Include only float, int, boolean columns.
910
911 Returns
912 -------
913 Series or DataFrame
914 Return type is the same as the original object with ``np.float64`` dtype.
915
916 See Also
917 --------
918 Series.ewm : Calling ewm with Series data.
919 DataFrame.ewm : Calling ewm with DataFrames.
920 Series.corr : Aggregating corr for Series.
921 DataFrame.corr : Aggregating corr for DataFrame.
922
923 Examples
924 --------
925 >>> ser1 = pd.Series([1, 2, 3, 4])
926 >>> ser2 = pd.Series([10, 11, 13, 16])
927 >>> ser1.ewm(alpha=0.2).corr(ser2)
928 0 NaN
929 1 1.000000
930 2 0.982821
931 3 0.977802
932 dtype: float64
933 """
934 if self.times is not None:
935 raise NotImplementedError("corr is not implemented with times")
936
937 from pandas import Series
938
939 self._validate_numeric_only("corr", numeric_only)
940
941 def cov_func(x, y):
942 x_array = self._prep_values(x)
943 y_array = self._prep_values(y)
944 window_indexer = self._get_window_indexer()
945 min_periods = (
946 self.min_periods
947 if self.min_periods is not None
948 else window_indexer.window_size
949 )
950 start, end = window_indexer.get_window_bounds(
951 num_values=len(x_array),
952 min_periods=min_periods,
953 center=self.center,
954 closed=self.closed,
955 step=self.step,
956 )
957
958 def _cov(X, Y):
959 return window_aggregations.ewmcov(
960 X,
961 start,
962 end,
963 min_periods,
964 Y,
965 self._com,
966 self.adjust,
967 self.ignore_na,
968 True,
969 )
970
971 with np.errstate(all="ignore"):
972 cov = _cov(x_array, y_array)
973 x_var = _cov(x_array, x_array)
974 y_var = _cov(y_array, y_array)
975 result = cov / zsqrt(x_var * y_var)
976 return Series(result, index=x.index, name=x.name, copy=False)
977
978 return self._apply_pairwise(
979 self._selected_obj, other, pairwise, cov_func, numeric_only
980 )
981
982
983@set_module("pandas.api.typing")
984class ExponentialMovingWindowGroupby(BaseWindowGroupby, ExponentialMovingWindow):
985 """
986 Provide an exponential moving window groupby implementation.
987 """
988
989 _attributes = ExponentialMovingWindow._attributes + BaseWindowGroupby._attributes
990
991 def __init__(self, obj, *args, _grouper=None, **kwargs) -> None:
992 super().__init__(obj, *args, _grouper=_grouper, **kwargs)
993
994 if not obj.empty and self.times is not None:
995 # sort the times and recalculate the deltas according to the groups
996 groupby_order = np.concatenate(list(self._grouper.indices.values()))
997 self._deltas = _calculate_deltas(
998 self.times.take(groupby_order),
999 self.halflife,
1000 )
1001
1002 def _get_window_indexer(self) -> GroupbyIndexer:
1003 """
1004 Return an indexer class that will compute the window start and end bounds
1005
1006 Returns
1007 -------
1008 GroupbyIndexer
1009 """
1010 window_indexer = GroupbyIndexer(
1011 groupby_indices=self._grouper.indices,
1012 window_indexer=ExponentialMovingWindowIndexer,
1013 )
1014 return window_indexer
1015
1016
1017class OnlineExponentialMovingWindow(ExponentialMovingWindow):
1018 def __init__(
1019 self,
1020 obj: NDFrame,
1021 com: float | None = None,
1022 span: float | None = None,
1023 halflife: float | TimedeltaConvertibleTypes | None = None,
1024 alpha: float | None = None,
1025 min_periods: int | None = 0,
1026 adjust: bool = True,
1027 ignore_na: bool = False,
1028 times: np.ndarray | NDFrame | None = None,
1029 engine: str = "numba",
1030 engine_kwargs: dict[str, bool] | None = None,
1031 *,
1032 selection=None,
1033 ) -> None:
1034 if times is not None:
1035 raise NotImplementedError(
1036 "times is not implemented with online operations."
1037 )
1038 super().__init__(
1039 obj=obj,
1040 com=com,
1041 span=span,
1042 halflife=halflife,
1043 alpha=alpha,
1044 min_periods=min_periods,
1045 adjust=adjust,
1046 ignore_na=ignore_na,
1047 times=times,
1048 selection=selection,
1049 )
1050 self._mean = EWMMeanState(self._com, self.adjust, self.ignore_na, obj.shape)
1051 if maybe_use_numba(engine):
1052 self.engine = engine
1053 self.engine_kwargs = engine_kwargs
1054 else:
1055 raise ValueError("'numba' is the only supported engine")
1056
1057 def reset(self) -> None:
1058 """
1059 Reset the state captured by `update` calls.
1060 """
1061 self._mean.reset()
1062
1063 def aggregate(self, func=None, *args, **kwargs):
1064 raise NotImplementedError("aggregate is not implemented.")
1065
1066 def std(self, bias: bool = False, *args, **kwargs):
1067 raise NotImplementedError("std is not implemented.")
1068
1069 def corr(
1070 self,
1071 other: DataFrame | Series | None = None,
1072 pairwise: bool | None = None,
1073 numeric_only: bool = False,
1074 ):
1075 raise NotImplementedError("corr is not implemented.")
1076
1077 def cov(
1078 self,
1079 other: DataFrame | Series | None = None,
1080 pairwise: bool | None = None,
1081 bias: bool = False,
1082 numeric_only: bool = False,
1083 ):
1084 raise NotImplementedError("cov is not implemented.")
1085
1086 def var(self, bias: bool = False, numeric_only: bool = False):
1087 raise NotImplementedError("var is not implemented.")
1088
1089 def mean(self, *args, update=None, update_times=None, **kwargs):
1090 """
1091 Calculate an online exponentially weighted mean.
1092
1093 Parameters
1094 ----------
1095 update: DataFrame or Series, default None
1096 New values to continue calculating the
1097 exponentially weighted mean from the last values and weights.
1098 Values should be float64 dtype.
1099
1100 ``update`` needs to be ``None`` the first time the
1101 exponentially weighted mean is calculated.
1102
1103 update_times: Series or 1-D np.ndarray, default None
1104 New times to continue calculating the
1105 exponentially weighted mean from the last values and weights.
1106 If ``None``, values are assumed to be evenly spaced
1107 in time.
1108 This feature is currently unsupported.
1109
1110 Returns
1111 -------
1112 DataFrame or Series
1113
1114 Examples
1115 --------
1116 >>> df = pd.DataFrame({"a": range(5), "b": range(5, 10)})
1117 >>> online_ewm = df.head(2).ewm(0.5).online()
1118 >>> online_ewm.mean()
1119 a b
1120 0 0.00 5.00
1121 1 0.75 5.75
1122 >>> online_ewm.mean(update=df.tail(3))
1123 a b
1124 2 1.615385 6.615385
1125 3 2.550000 7.550000
1126 4 3.520661 8.520661
1127 >>> online_ewm.reset()
1128 >>> online_ewm.mean()
1129 a b
1130 0 0.00 5.00
1131 1 0.75 5.75
1132 """
1133 result_kwargs = {}
1134 is_frame = self._selected_obj.ndim == 2
1135 if update_times is not None:
1136 raise NotImplementedError("update_times is not implemented.")
1137 update_deltas = np.ones(
1138 max(self._selected_obj.shape[-1] - 1, 0), dtype=np.float64
1139 )
1140 if update is not None:
1141 if self._mean.last_ewm is None:
1142 raise ValueError(
1143 "Must call mean with update=None first before passing update"
1144 )
1145 result_from = 1
1146 result_kwargs["index"] = update.index
1147 if is_frame:
1148 last_value = self._mean.last_ewm[np.newaxis, :]
1149 result_kwargs["columns"] = update.columns
1150 else:
1151 last_value = self._mean.last_ewm
1152 result_kwargs["name"] = update.name
1153 np_array = np.concatenate((last_value, update.to_numpy()))
1154 else:
1155 result_from = 0
1156 result_kwargs["index"] = self._selected_obj.index
1157 if is_frame:
1158 result_kwargs["columns"] = self._selected_obj.columns
1159 else:
1160 result_kwargs["name"] = self._selected_obj.name
1161 np_array = self._selected_obj.astype(np.float64).to_numpy()
1162 ewma_func = generate_online_numba_ewma_func(
1163 **get_jit_arguments(self.engine_kwargs)
1164 )
1165 result = self._mean.run_ewm(
1166 np_array if is_frame else np_array[:, np.newaxis],
1167 update_deltas,
1168 self.min_periods,
1169 ewma_func,
1170 )
1171 if not is_frame:
1172 result = result.squeeze()
1173 result = result[result_from:]
1174 result = self._selected_obj._constructor(result, **result_kwargs)
1175 return result