Skip to content

ENH: ewm() default to using DatetimeIndex as times when halflife is a timedelta #54181

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions pandas/core/window/ewm.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
ExponentialMovingWindowIndexer,
GroupbyIndexer,
)
from pandas.core.indexes.api import DatetimeIndex
from pandas.core.util.numba_ import (
get_jit_arguments,
maybe_use_numba,
Expand Down Expand Up @@ -150,9 +151,10 @@ class ExponentialMovingWindow(BaseWindow):
: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.
If ``times`` is specified or the index is a DatetimeIndex, 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.

alpha : float, optional
Specify smoothing factor :math:`\alpha` directly
Expand Down Expand Up @@ -360,6 +362,12 @@ def __init__(
self.adjust = adjust
self.ignore_na = ignore_na
self.times = times
if (
self.halflife is not None
and isinstance(self.halflife, (str, datetime.timedelta, np.timedelta64))
and isinstance(self.obj.index, DatetimeIndex)
):
self.times = self.obj.index.values
if self.times is not None:
if not self.adjust:
raise NotImplementedError("times is not supported with adjust=False.")
Expand All @@ -384,7 +392,7 @@ def __init__(
):
raise ValueError(
"halflife can only be a timedelta convertible argument if "
"times is not None."
"times is not None or the index is a DatetimeIndex."
)
# Without times, points are equally spaced
self._deltas = np.ones(
Expand Down
32 changes: 32 additions & 0 deletions pandas/tests/window/test_ewm.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,38 @@ def test_ewma_with_times_variable_spacing(tz_aware_fixture):
tm.assert_frame_equal(result, expected)


@pytest.mark.parametrize(
"times",
[
np.arange(10).astype("datetime64[D]").astype("datetime64[ns]"),
date_range("2000", freq="D", periods=10),
date_range("2000", freq="D", periods=10).tz_localize("UTC"),
],
)
@pytest.mark.parametrize("min_periods", [0, 2])
def test_ewma_with_time_index_equal_spacing(halflife_with_times, times, min_periods):
halflife = halflife_with_times
data = np.arange(10.0)
data[::2] = np.nan
df = DataFrame({"A": data}, index=times)
result = df.ewm(halflife=halflife, min_periods=min_periods).mean()
expected = df.ewm(halflife=1.0, min_periods=min_periods).mean()
tm.assert_frame_equal(result, expected)


def test_ewma_with_time_index_variable_spacing(tz_aware_fixture):
tz = tz_aware_fixture
halflife = "23 days"
times = DatetimeIndex(
["2020-01-01", "2020-01-10T00:04:05", "2020-02-23T05:00:23"]
).tz_localize(tz)
data = np.arange(3)
df = DataFrame(data, index=times)
result = df.ewm(halflife=halflife).mean()
expected = DataFrame([0.0, 0.5674161888241773, 1.545239952073459], index=times)
tm.assert_frame_equal(result, expected)


def test_ewm_with_nat_raises(halflife_with_times):
# GH#38535
ser = Series(range(1))
Expand Down