diff --git a/doc/source/reference/window.rst b/doc/source/reference/window.rst index 77697b966df18..a255b3ae8081e 100644 --- a/doc/source/reference/window.rst +++ b/doc/source/reference/window.rst @@ -10,8 +10,10 @@ Rolling objects are returned by ``.rolling`` calls: :func:`pandas.DataFrame.roll Expanding objects are returned by ``.expanding`` calls: :func:`pandas.DataFrame.expanding`, :func:`pandas.Series.expanding`, etc. ExponentialMovingWindow objects are returned by ``.ewm`` calls: :func:`pandas.DataFrame.ewm`, :func:`pandas.Series.ewm`, etc. -Standard moving window functions --------------------------------- +.. _api.functions_rolling: + +Rolling window functions +------------------------ .. currentmodule:: pandas.core.window.rolling .. autosummary:: @@ -33,6 +35,16 @@ Standard moving window functions Rolling.aggregate Rolling.quantile Rolling.sem + +.. _api.functions_window: + +Weighted window functions +------------------------- +.. currentmodule:: pandas.core.window.rolling + +.. autosummary:: + :toctree: api/ + Window.mean Window.sum Window.var @@ -40,8 +52,8 @@ Standard moving window functions .. _api.functions_expanding: -Standard expanding window functions ------------------------------------ +Expanding window functions +-------------------------- .. currentmodule:: pandas.core.window.expanding .. autosummary:: @@ -64,8 +76,10 @@ Standard expanding window functions Expanding.quantile Expanding.sem -Exponentially-weighted moving window functions ----------------------------------------------- +.. _api.functions_ewm: + +Exponentially-weighted window functions +--------------------------------------- .. currentmodule:: pandas.core.window.ewm .. autosummary:: @@ -77,6 +91,8 @@ Exponentially-weighted moving window functions ExponentialMovingWindow.corr ExponentialMovingWindow.cov +.. _api.indexers_window: + Window indexer -------------- .. currentmodule:: pandas diff --git a/doc/source/user_guide/basics.rst b/doc/source/user_guide/basics.rst index a21e5180004b2..ffecaa222e1f9 100644 --- a/doc/source/user_guide/basics.rst +++ b/doc/source/user_guide/basics.rst @@ -538,8 +538,8 @@ standard deviation of 1), very concisely: Note that methods like :meth:`~DataFrame.cumsum` and :meth:`~DataFrame.cumprod` preserve the location of ``NaN`` values. This is somewhat different from -:meth:`~DataFrame.expanding` and :meth:`~DataFrame.rolling`. -For more details please see :ref:`this note `. +:meth:`~DataFrame.expanding` and :meth:`~DataFrame.rolling` since ``NaN`` behavior +is furthermore dictated by a ``min_periods`` parameter. .. ipython:: python @@ -945,7 +945,7 @@ Aggregation API The aggregation API allows one to express possibly multiple aggregation operations in a single concise way. This API is similar across pandas objects, see :ref:`groupby API `, the -:ref:`window functions API `, and the :ref:`resample API `. +:ref:`window API `, and the :ref:`resample API `. The entry point for aggregation is :meth:`DataFrame.aggregate`, or the alias :meth:`DataFrame.agg`. diff --git a/doc/source/user_guide/computation.rst b/doc/source/user_guide/computation.rst index 45d15f29fcce8..f05eb9cc40402 100644 --- a/doc/source/user_guide/computation.rst +++ b/doc/source/user_guide/computation.rst @@ -205,991 +205,3 @@ parameter: - ``min`` : lowest rank in the group - ``max`` : highest rank in the group - ``first`` : ranks assigned in the order they appear in the array - -.. _stats.moments: - -Window functions ----------------- - -.. currentmodule:: pandas.core.window - -For working with data, a number of window functions are provided for -computing common *window* or *rolling* statistics. Among these are count, sum, -mean, median, correlation, variance, covariance, standard deviation, skewness, -and kurtosis. - -The ``rolling()`` and ``expanding()`` -functions can be used directly from DataFrameGroupBy objects, -see the :ref:`groupby docs `. - - -.. note:: - - The API for window statistics is quite similar to the way one works with ``GroupBy`` objects, see the documentation :ref:`here `. - -.. warning:: - - When using ``rolling()`` and an associated function the results are calculated with rolling sums. As a consequence - when having values differing with magnitude :math:`1/np.finfo(np.double).eps` this results in truncation. It must be - noted, that large values may have an impact on windows, which do not include these values. `Kahan summation - `__ is used - to compute the rolling sums to preserve accuracy as much as possible. The same holds true for ``Rolling.var()`` for - values differing with magnitude :math:`(1/np.finfo(np.double).eps)^{0.5}`. - -We work with ``rolling``, ``expanding`` and ``exponentially weighted`` data through the corresponding -objects, :class:`~pandas.core.window.Rolling`, :class:`~pandas.core.window.Expanding` and :class:`~pandas.core.window.ExponentialMovingWindow`. - -.. ipython:: python - - s = pd.Series(np.random.randn(1000), index=pd.date_range("1/1/2000", periods=1000)) - s = s.cumsum() - s - -These are created from methods on ``Series`` and ``DataFrame``. - -.. ipython:: python - - r = s.rolling(window=60) - r - -These object provide tab-completion of the available methods and properties. - -.. code-block:: ipython - - In [14]: r. # noqa: E225, E999 - r.agg r.apply r.count r.exclusions r.max r.median r.name r.skew r.sum - r.aggregate r.corr r.cov r.kurt r.mean r.min r.quantile r.std r.var - -Generally these methods all have the same interface. They all -accept the following arguments: - -- ``window``: size of moving window -- ``min_periods``: threshold of non-null data points to require (otherwise - result is NA) -- ``center``: boolean, whether to set the labels at the center (default is False) - -We can then call methods on these ``rolling`` objects. These return like-indexed objects: - -.. ipython:: python - - r.mean() - -.. ipython:: python - - s.plot(style="k--") - - @savefig rolling_mean_ex.png - r.mean().plot(style="k") - -.. ipython:: python - :suppress: - - plt.close("all") - -They can also be applied to DataFrame objects. This is really just syntactic -sugar for applying the moving window operator to all of the DataFrame's columns: - -.. ipython:: python - - df = pd.DataFrame( - np.random.randn(1000, 4), - index=pd.date_range("1/1/2000", periods=1000), - columns=["A", "B", "C", "D"], - ) - df = df.cumsum() - - @savefig rolling_mean_frame.png - df.rolling(window=60).sum().plot(subplots=True) - -.. _stats.summary: - -Method summary -~~~~~~~~~~~~~~ - -We provide a number of common statistical functions: - -.. currentmodule:: pandas.core.window - -.. csv-table:: - :header: "Method", "Description" - :widths: 20, 80 - - :meth:`~Rolling.count`, Number of non-null observations - :meth:`~Rolling.sum`, Sum of values - :meth:`~Rolling.mean`, Mean of values - :meth:`~Rolling.median`, Arithmetic median of values - :meth:`~Rolling.min`, Minimum - :meth:`~Rolling.max`, Maximum - :meth:`~Rolling.std`, Sample standard deviation - :meth:`~Rolling.var`, Sample variance - :meth:`~Rolling.skew`, Sample skewness (3rd moment) - :meth:`~Rolling.kurt`, Sample kurtosis (4th moment) - :meth:`~Rolling.quantile`, Sample quantile (value at %) - :meth:`~Rolling.apply`, Generic apply - :meth:`~Rolling.cov`, Sample covariance (binary) - :meth:`~Rolling.corr`, Sample correlation (binary) - :meth:`~Rolling.sem`, Standard error of mean - -.. _computation.window_variance.caveats: - -.. note:: - - Please note that :meth:`~Rolling.std` and :meth:`~Rolling.var` use the sample - variance formula by default, i.e. the sum of squared differences is divided by - ``window_size - 1`` and not by ``window_size`` during averaging. In statistics, - we use sample when the dataset is drawn from a larger population that we - don't have access to. Using it implies that the data in our window is a - random sample from the population, and we are interested not in the variance - inside the specific window but in the variance of some general window that - our windows represent. In this situation, using the sample variance formula - results in an unbiased estimator and so is preferred. - - Usually, we are instead interested in the variance of each window as we slide - it over the data, and in this case we should specify ``ddof=0`` when calling - these methods to use population variance instead of sample variance. Using - sample variance under the circumstances would result in a biased estimator - of the variable we are trying to determine. - - The same caveats apply to using any supported statistical sample methods. - -.. _stats.rolling_apply: - -Rolling apply -~~~~~~~~~~~~~ - -The :meth:`~Rolling.apply` function takes an extra ``func`` argument and performs -generic rolling computations. The ``func`` argument should be a single function -that produces a single value from an ndarray input. Suppose we wanted to -compute the mean absolute deviation on a rolling basis: - -.. ipython:: python - - def mad(x): - return np.fabs(x - x.mean()).mean() - - @savefig rolling_apply_ex.png - s.rolling(window=60).apply(mad, raw=True).plot(style="k") - -Using the Numba engine -~~~~~~~~~~~~~~~~~~~~~~ - -.. versionadded:: 1.0 - -Additionally, :meth:`~Rolling.apply` can leverage `Numba `__ -if installed as an optional dependency. The apply aggregation can be executed using Numba by specifying -``engine='numba'`` and ``engine_kwargs`` arguments (``raw`` must also be set to ``True``). -Numba will be applied in potentially two routines: - -1. If ``func`` is a standard Python function, the engine will `JIT `__ -the passed function. ``func`` can also be a JITed function in which case the engine will not JIT the function again. - -2. The engine will JIT the for loop where the apply function is applied to each window. - -The ``engine_kwargs`` argument is a dictionary of keyword arguments that will be passed into the -`numba.jit decorator `__. -These keyword arguments will be applied to *both* the passed function (if a standard Python function) -and the apply for loop over each window. Currently only ``nogil``, ``nopython``, and ``parallel`` are supported, -and their default values are set to ``False``, ``True`` and ``False`` respectively. - -.. note:: - - In terms of performance, **the first time a function is run using the Numba engine will be slow** - as Numba will have some function compilation overhead. However, the compiled functions are cached, - and subsequent calls will be fast. In general, the Numba engine is performant with - a larger amount of data points (e.g. 1+ million). - -.. code-block:: ipython - - In [1]: data = pd.Series(range(1_000_000)) - - In [2]: roll = data.rolling(10) - - In [3]: def f(x): - ...: return np.sum(x) + 5 - # Run the first time, compilation time will affect performance - In [4]: %timeit -r 1 -n 1 roll.apply(f, engine='numba', raw=True) # noqa: E225 - 1.23 s ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each) - # Function is cached and performance will improve - In [5]: %timeit roll.apply(f, engine='numba', raw=True) - 188 ms ± 1.93 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) - - In [6]: %timeit roll.apply(f, engine='cython', raw=True) - 3.92 s ± 59 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) - -.. _stats.rolling_window: - -Rolling windows -~~~~~~~~~~~~~~~ - -Passing ``win_type`` to ``.rolling`` generates a generic rolling window computation, that is weighted according the ``win_type``. -The following methods are available: - -.. csv-table:: - :header: "Method", "Description" - :widths: 20, 80 - - :meth:`~Window.sum`, Sum of values - :meth:`~Window.mean`, Mean of values - -The weights used in the window are specified by the ``win_type`` keyword. -The list of recognized types are the `scipy.signal window functions -`__: - -* ``boxcar`` -* ``triang`` -* ``blackman`` -* ``hamming`` -* ``bartlett`` -* ``parzen`` -* ``bohman`` -* ``blackmanharris`` -* ``nuttall`` -* ``barthann`` -* ``kaiser`` (needs beta) -* ``gaussian`` (needs std) -* ``general_gaussian`` (needs power, width) -* ``slepian`` (needs width) -* ``exponential`` (needs tau). - -.. versionadded:: 1.2.0 - -All Scipy window types, concurrent with your installed version, are recognized ``win_types``. - -.. ipython:: python - - ser = pd.Series(np.random.randn(10), index=pd.date_range("1/1/2000", periods=10)) - - ser.rolling(window=5, win_type="triang").mean() - -Note that the ``boxcar`` window is equivalent to :meth:`~Rolling.mean`. - -.. ipython:: python - - ser.rolling(window=5, win_type="boxcar").mean() - ser.rolling(window=5).mean() - -For some windowing functions, additional parameters must be specified: - -.. ipython:: python - - ser.rolling(window=5, win_type="gaussian").mean(std=0.1) - -.. _stats.moments.normalization: - -.. note:: - - For ``.sum()`` with a ``win_type``, there is no normalization done to the - weights for the window. Passing custom weights of ``[1, 1, 1]`` will yield a different - result than passing weights of ``[2, 2, 2]``, for example. When passing a - ``win_type`` instead of explicitly specifying the weights, the weights are - already normalized so that the largest weight is 1. - - In contrast, the nature of the ``.mean()`` calculation is - such that the weights are normalized with respect to each other. Weights - of ``[1, 1, 1]`` and ``[2, 2, 2]`` yield the same result. - -.. _stats.moments.ts: - -Time-aware rolling -~~~~~~~~~~~~~~~~~~ - -It is possible to pass an offset (or convertible) to a ``.rolling()`` method and have it produce -variable sized windows based on the passed time window. For each time point, this includes all preceding values occurring -within the indicated time delta. - -This can be particularly useful for a non-regular time frequency index. - -.. ipython:: python - - dft = pd.DataFrame( - {"B": [0, 1, 2, np.nan, 4]}, - index=pd.date_range("20130101 09:00:00", periods=5, freq="s"), - ) - dft - -This is a regular frequency index. Using an integer window parameter works to roll along the window frequency. - -.. ipython:: python - - dft.rolling(2).sum() - dft.rolling(2, min_periods=1).sum() - -Specifying an offset allows a more intuitive specification of the rolling frequency. - -.. ipython:: python - - dft.rolling("2s").sum() - -Using a non-regular, but still monotonic index, rolling with an integer window does not impart any special calculation. - - -.. ipython:: python - - dft = pd.DataFrame( - {"B": [0, 1, 2, np.nan, 4]}, - index=pd.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"), - ], - name="foo", - ), - ) - dft - dft.rolling(2).sum() - - -Using the time-specification generates variable windows for this sparse data. - -.. ipython:: python - - dft.rolling("2s").sum() - -Furthermore, we now allow an optional ``on`` parameter to specify a column (rather than the -default of the index) in a DataFrame. - -.. ipython:: python - - dft = dft.reset_index() - dft - dft.rolling("2s", on="foo").sum() - -.. _stats.custom_rolling_window: - -Custom window rolling -~~~~~~~~~~~~~~~~~~~~~ - -.. versionadded:: 1.0 - -In addition to accepting an integer or offset as a ``window`` argument, ``rolling`` also accepts -a ``BaseIndexer`` subclass that allows a user to define a custom method for calculating window bounds. -The ``BaseIndexer`` subclass will need to define a ``get_window_bounds`` method that returns -a tuple of two arrays, the first being the starting indices of the windows and second being the -ending indices of the windows. Additionally, ``num_values``, ``min_periods``, ``center``, ``closed`` -and will automatically be passed to ``get_window_bounds`` and the defined method must -always accept these arguments. - -For example, if we have the following ``DataFrame``: - -.. ipython:: python - - use_expanding = [True, False, True, False, True] - use_expanding - df = pd.DataFrame({"values": range(5)}) - df - -and we want to use an expanding window where ``use_expanding`` is ``True`` otherwise a window of size -1, we can create the following ``BaseIndexer`` subclass: - -.. code-block:: ipython - - In [2]: from pandas.api.indexers import BaseIndexer - ...: - ...: class CustomIndexer(BaseIndexer): - ...: - ...: def get_window_bounds(self, num_values, min_periods, center, closed): - ...: start = np.empty(num_values, dtype=np.int64) - ...: end = np.empty(num_values, dtype=np.int64) - ...: for i in range(num_values): - ...: if self.use_expanding[i]: - ...: start[i] = 0 - ...: end[i] = i + 1 - ...: else: - ...: start[i] = i - ...: end[i] = i + self.window_size - ...: return start, end - ...: - - In [3]: indexer = CustomIndexer(window_size=1, use_expanding=use_expanding) - - In [4]: df.rolling(indexer).sum() - Out[4]: - values - 0 0.0 - 1 1.0 - 2 3.0 - 3 3.0 - 4 10.0 - -You can view other examples of ``BaseIndexer`` subclasses `here `__ - -.. versionadded:: 1.1 - -One subclass of note within those examples is the ``VariableOffsetWindowIndexer`` that allows -rolling operations over a non-fixed offset like a ``BusinessDay``. - -.. ipython:: python - - from pandas.api.indexers import VariableOffsetWindowIndexer - - df = pd.DataFrame(range(10), index=pd.date_range("2020", periods=10)) - offset = pd.offsets.BDay(1) - indexer = VariableOffsetWindowIndexer(index=df.index, offset=offset) - df - df.rolling(indexer).sum() - -For some problems knowledge of the future is available for analysis. For example, this occurs when -each data point is a full time series read from an experiment, and the task is to extract underlying -conditions. In these cases it can be useful to perform forward-looking rolling window computations. -:func:`FixedForwardWindowIndexer ` class is available for this purpose. -This :func:`BaseIndexer ` subclass implements a closed fixed-width -forward-looking rolling window, and we can use it as follows: - -.. ipython:: ipython - - from pandas.api.indexers import FixedForwardWindowIndexer - indexer = FixedForwardWindowIndexer(window_size=2) - df.rolling(indexer, min_periods=1).sum() - -.. _stats.rolling_window.endpoints: - -Rolling window endpoints -~~~~~~~~~~~~~~~~~~~~~~~~ - -The inclusion of the interval endpoints in rolling window calculations can be specified with the ``closed`` -parameter: - -.. csv-table:: - :header: "``closed``", "Description", "Default for" - :widths: 20, 30, 30 - - ``right``, close right endpoint, - ``left``, close left endpoint, - ``both``, close both endpoints, - ``neither``, open endpoints, - -For example, having the right endpoint open is useful in many problems that require that there is no contamination -from present information back to past information. This allows the rolling window to compute statistics -"up to that point in time", but not including that point in time. - -.. ipython:: python - - df = pd.DataFrame( - {"x": 1}, - index=[ - pd.Timestamp("20130101 09:00:01"), - pd.Timestamp("20130101 09:00:02"), - pd.Timestamp("20130101 09:00:03"), - pd.Timestamp("20130101 09:00:04"), - pd.Timestamp("20130101 09:00:06"), - ], - ) - - df["right"] = df.rolling("2s", closed="right").x.sum() # default - df["both"] = df.rolling("2s", closed="both").x.sum() - df["left"] = df.rolling("2s", closed="left").x.sum() - df["neither"] = df.rolling("2s", closed="neither").x.sum() - - df - -.. _stats.iter_rolling_window: - -Iteration over window: -~~~~~~~~~~~~~~~~~~~~~~ - -.. versionadded:: 1.1.0 - -``Rolling`` and ``Expanding`` objects now support iteration. Be noted that ``min_periods`` is ignored in iteration. - -.. ipython:: - - In [1]: df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) - - In [2]: for i in df.rolling(2): - ...: print(i) - ...: - - -.. _stats.moments.ts-versus-resampling: - -Time-aware rolling vs. resampling -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Using ``.rolling()`` with a time-based index is quite similar to :ref:`resampling `. They -both operate and perform reductive operations on time-indexed pandas objects. - -When using ``.rolling()`` with an offset. The offset is a time-delta. Take a backwards-in-time looking window, and -aggregate all of the values in that window (including the end-point, but not the start-point). This is the new value -at that point in the result. These are variable sized windows in time-space for each point of the input. You will get -a same sized result as the input. - -When using ``.resample()`` with an offset. Construct a new index that is the frequency of the offset. For each frequency -bin, aggregate points from the input within a backwards-in-time looking window that fall in that bin. The result of this -aggregation is the output for that frequency point. The windows are fixed size in the frequency space. Your result -will have the shape of a regular frequency between the min and the max of the original input object. - -To summarize, ``.rolling()`` is a time-based window operation, while ``.resample()`` is a frequency-based window operation. - -Centering windows -~~~~~~~~~~~~~~~~~ - -By default the labels are set to the right edge of the window, but a -``center`` keyword is available so the labels can be set at the center. - -.. ipython:: python - - ser.rolling(window=5).mean() - ser.rolling(window=5, center=True).mean() - -.. _stats.moments.binary: - -Binary window functions -~~~~~~~~~~~~~~~~~~~~~~~ - -:meth:`~Rolling.cov` and :meth:`~Rolling.corr` can compute moving window statistics about -two ``Series`` or any combination of ``DataFrame/Series`` or -``DataFrame/DataFrame``. Here is the behavior in each case: - -* two ``Series``: compute the statistic for the pairing. -* ``DataFrame/Series``: compute the statistics for each column of the DataFrame - with the passed Series, thus returning a DataFrame. -* ``DataFrame/DataFrame``: by default compute the statistic for matching column - names, returning a DataFrame. If the keyword argument ``pairwise=True`` is - passed then computes the statistic for each pair of columns, returning a - ``MultiIndexed DataFrame`` whose ``index`` are the dates in question (see :ref:`the next section - `). - -For example: - -.. ipython:: python - - df = pd.DataFrame( - np.random.randn(1000, 4), - index=pd.date_range("1/1/2000", periods=1000), - columns=["A", "B", "C", "D"], - ) - df = df.cumsum() - - df2 = df[:20] - df2.rolling(window=5).corr(df2["B"]) - -.. _stats.moments.corr_pairwise: - -Computing rolling pairwise covariances and correlations -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -In financial data analysis and other fields it's common to compute covariance -and correlation matrices for a collection of time series. Often one is also -interested in moving-window covariance and correlation matrices. This can be -done by passing the ``pairwise`` keyword argument, which in the case of -``DataFrame`` inputs will yield a MultiIndexed ``DataFrame`` whose ``index`` are the dates in -question. In the case of a single DataFrame argument the ``pairwise`` argument -can even be omitted: - -.. note:: - - Missing values are ignored and each entry is computed using the pairwise - complete observations. Please see the :ref:`covariance section - ` for :ref:`caveats - ` associated with this method of - calculating covariance and correlation matrices. - -.. ipython:: python - - covs = ( - df[["B", "C", "D"]] - .rolling(window=50) - .cov(df[["A", "B", "C"]], pairwise=True) - ) - covs.loc["2002-09-22":] - -.. ipython:: python - - correls = df.rolling(window=50).corr() - correls.loc["2002-09-22":] - -You can efficiently retrieve the time series of correlations between two -columns by reshaping and indexing: - -.. ipython:: python - :suppress: - - plt.close("all") - -.. ipython:: python - - @savefig rolling_corr_pairwise_ex.png - correls.unstack(1)[("A", "C")].plot() - -.. _stats.aggregate: - -Aggregation ------------ - -Once the ``Rolling``, ``Expanding`` or ``ExponentialMovingWindow`` objects have been created, several methods are available to -perform multiple computations on the data. These operations are similar to the :ref:`aggregating API `, -:ref:`groupby API `, and :ref:`resample API `. - - -.. ipython:: python - - dfa = pd.DataFrame( - np.random.randn(1000, 3), - index=pd.date_range("1/1/2000", periods=1000), - columns=["A", "B", "C"], - ) - r = dfa.rolling(window=60, min_periods=1) - r - -We can aggregate by passing a function to the entire DataFrame, or select a -Series (or multiple Series) via standard ``__getitem__``. - -.. ipython:: python - - r.aggregate(np.sum) - - r["A"].aggregate(np.sum) - - r[["A", "B"]].aggregate(np.sum) - -As you can see, the result of the aggregation will have the selected columns, or all -columns if none are selected. - -.. _stats.aggregate.multifunc: - -Applying multiple functions -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -With windowed ``Series`` you can also pass a list of functions to do -aggregation with, outputting a DataFrame: - -.. ipython:: python - - r["A"].agg([np.sum, np.mean, np.std]) - -On a windowed DataFrame, you can pass a list of functions to apply to each -column, which produces an aggregated result with a hierarchical index: - -.. ipython:: python - - r.agg([np.sum, np.mean]) - -Passing a dict of functions has different behavior by default, see the next -section. - -Applying different functions to DataFrame columns -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -By passing a dict to ``aggregate`` you can apply a different aggregation to the -columns of a ``DataFrame``: - -.. ipython:: python - - r.agg({"A": np.sum, "B": lambda x: np.std(x, ddof=1)}) - -The function names can also be strings. In order for a string to be valid it -must be implemented on the windowed object - -.. ipython:: python - - r.agg({"A": "sum", "B": "std"}) - -Furthermore you can pass a nested dict to indicate different aggregations on different columns. - -.. ipython:: python - - r.agg({"A": ["sum", "std"], "B": ["mean", "std"]}) - - -.. _stats.moments.expanding: - -Expanding windows ------------------ - -A common alternative to rolling statistics is to use an *expanding* window, -which yields the value of the statistic with all the data available up to that -point in time. - -These follow a similar interface to ``.rolling``, with the ``.expanding`` method -returning an :class:`~pandas.core.window.Expanding` object. - -As these calculations are a special case of rolling statistics, -they are implemented in pandas such that the following two calls are equivalent: - -.. ipython:: python - - df.rolling(window=len(df), min_periods=1).mean()[:5] - - df.expanding(min_periods=1).mean()[:5] - -These have a similar set of methods to ``.rolling`` methods. - -Method summary -~~~~~~~~~~~~~~ - -.. currentmodule:: pandas.core.window - -.. csv-table:: - :header: "Function", "Description" - :widths: 20, 80 - - :meth:`~Expanding.count`, Number of non-null observations - :meth:`~Expanding.sum`, Sum of values - :meth:`~Expanding.mean`, Mean of values - :meth:`~Expanding.median`, Arithmetic median of values - :meth:`~Expanding.min`, Minimum - :meth:`~Expanding.max`, Maximum - :meth:`~Expanding.std`, Sample standard deviation - :meth:`~Expanding.var`, Sample variance - :meth:`~Expanding.skew`, Sample skewness (3rd moment) - :meth:`~Expanding.kurt`, Sample kurtosis (4th moment) - :meth:`~Expanding.quantile`, Sample quantile (value at %) - :meth:`~Expanding.apply`, Generic apply - :meth:`~Expanding.cov`, Sample covariance (binary) - :meth:`~Expanding.corr`, Sample correlation (binary) - :meth:`~Expanding.sem`, Standard error of mean - -.. note:: - - Using sample variance formulas for :meth:`~Expanding.std` and - :meth:`~Expanding.var` comes with the same caveats as using them with rolling - windows. See :ref:`this section ` for more - information. - - The same caveats apply to using any supported statistical sample methods. - -.. currentmodule:: pandas - -Aside from not having a ``window`` parameter, these functions have the same -interfaces as their ``.rolling`` counterparts. Like above, the parameters they -all accept are: - -* ``min_periods``: threshold of non-null data points to require. Defaults to - minimum needed to compute statistic. No ``NaNs`` will be output once - ``min_periods`` non-null data points have been seen. -* ``center``: boolean, whether to set the labels at the center (default is False). - -.. _stats.moments.expanding.note: -.. note:: - - The output of the ``.rolling`` and ``.expanding`` methods do not return a - ``NaN`` if there are at least ``min_periods`` non-null values in the current - window. For example: - - .. ipython:: python - - sn = pd.Series([1, 2, np.nan, 3, np.nan, 4]) - sn - sn.rolling(2).max() - sn.rolling(2, min_periods=1).max() - - In case of expanding functions, this differs from :meth:`~DataFrame.cumsum`, - :meth:`~DataFrame.cumprod`, :meth:`~DataFrame.cummax`, - and :meth:`~DataFrame.cummin`, which return ``NaN`` in the output wherever - a ``NaN`` is encountered in the input. In order to match the output of ``cumsum`` - with ``expanding``, use :meth:`~DataFrame.fillna`: - - .. ipython:: python - - sn.expanding().sum() - sn.cumsum() - sn.cumsum().fillna(method="ffill") - - -An expanding window statistic will be more stable (and less responsive) than -its rolling window counterpart as the increasing window size decreases the -relative impact of an individual data point. As an example, here is the -:meth:`~core.window.Expanding.mean` output for the previous time series dataset: - -.. ipython:: python - :suppress: - - plt.close("all") - -.. ipython:: python - - s.plot(style="k--") - - @savefig expanding_mean_frame.png - s.expanding().mean().plot(style="k") - - -.. _stats.moments.exponentially_weighted: - -Exponentially weighted windows ------------------------------- - -.. currentmodule:: pandas.core.window - -A related set of functions are exponentially weighted versions of several of -the above statistics. A similar interface to ``.rolling`` and ``.expanding`` is accessed -through the ``.ewm`` method to receive an :class:`~ExponentialMovingWindow` object. -A number of expanding EW (exponentially weighted) -methods are provided: - - -.. csv-table:: - :header: "Function", "Description" - :widths: 20, 80 - - :meth:`~ExponentialMovingWindow.mean`, EW moving average - :meth:`~ExponentialMovingWindow.var`, EW moving variance - :meth:`~ExponentialMovingWindow.std`, EW moving standard deviation - :meth:`~ExponentialMovingWindow.corr`, EW moving correlation - :meth:`~ExponentialMovingWindow.cov`, EW moving covariance - -In general, a weighted moving average is calculated as - -.. math:: - - y_t = \frac{\sum_{i=0}^t w_i x_{t-i}}{\sum_{i=0}^t w_i}, - -where :math:`x_t` is the input, :math:`y_t` is the result and the :math:`w_i` -are the weights. - -The EW functions support two variants of exponential weights. -The default, ``adjust=True``, uses the weights :math:`w_i = (1 - \alpha)^i` -which gives - -.. 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`` is specified, moving averages are calculated as - -.. math:: - - y_0 &= x_0 \\ - y_t &= (1 - \alpha) y_{t-1} + \alpha x_t, - -which is equivalent to using weights - -.. math:: - - w_i = \begin{cases} - \alpha (1 - \alpha)^i & \text{if } i < t \\ - (1 - \alpha)^i & \text{if } i = t. - \end{cases} - -.. note:: - - These equations are sometimes written in terms of :math:`\alpha' = 1 - \alpha`, e.g. - - .. math:: - - y_t = \alpha' y_{t-1} + (1 - \alpha') x_t. - -The difference between the above two variants arises because we are -dealing with series which have finite history. Consider a series of infinite -history, with ``adjust=True``: - -.. math:: - - y_t = \frac{x_t + (1 - \alpha)x_{t-1} + (1 - \alpha)^2 x_{t-2} + ...} - {1 + (1 - \alpha) + (1 - \alpha)^2 + ...} - -Noting that the denominator is a geometric series with initial term equal to 1 -and a ratio of :math:`1 - \alpha` we have - -.. math:: - - y_t &= \frac{x_t + (1 - \alpha)x_{t-1} + (1 - \alpha)^2 x_{t-2} + ...} - {\frac{1}{1 - (1 - \alpha)}}\\ - &= [x_t + (1 - \alpha)x_{t-1} + (1 - \alpha)^2 x_{t-2} + ...] \alpha \\ - &= \alpha x_t + [(1-\alpha)x_{t-1} + (1 - \alpha)^2 x_{t-2} + ...]\alpha \\ - &= \alpha x_t + (1 - \alpha)[x_{t-1} + (1 - \alpha) x_{t-2} + ...]\alpha\\ - &= \alpha x_t + (1 - \alpha) y_{t-1} - -which is the same expression as ``adjust=False`` above and therefore -shows the equivalence of the two variants for infinite series. -When ``adjust=False``, we have :math:`y_0 = x_0` and -:math:`y_t = \alpha x_t + (1 - \alpha) y_{t-1}`. -Therefore, there is an assumption that :math:`x_0` is not an ordinary value -but rather an exponentially weighted moment of the infinite series up to that -point. - -One must have :math:`0 < \alpha \leq 1`, and while it is possible to pass -:math:`\alpha` directly, it's often easier to think about either the -**span**, **center of mass (com)** or **half-life** of an EW moment: - -.. math:: - - \alpha = - \begin{cases} - \frac{2}{s + 1}, & \text{for span}\ s \geq 1\\ - \frac{1}{1 + c}, & \text{for center of mass}\ c \geq 0\\ - 1 - \exp^{\frac{\log 0.5}{h}}, & \text{for half-life}\ h > 0 - \end{cases} - -One must specify precisely one of **span**, **center of mass**, **half-life** -and **alpha** to the EW functions: - -* **Span** corresponds to what is commonly called an "N-day EW moving average". -* **Center of mass** has a more physical interpretation and can be thought of - in terms of span: :math:`c = (s - 1) / 2`. -* **Half-life** is the period of time for the exponential weight to reduce to - one half. -* **Alpha** specifies the smoothing factor directly. - -.. versionadded:: 1.1.0 - -You can also specify ``halflife`` in terms of a timedelta convertible unit to specify the amount of -time it takes for an observation to decay to half its value when also specifying a sequence -of ``times``. - -.. ipython:: python - - df = pd.DataFrame({"B": [0, 1, 2, np.nan, 4]}) - df - 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() - -The following formula is used to compute exponentially weighted mean with an input vector of times: - -.. math:: - - y_t = \frac{\sum_{i=0}^t 0.5^\frac{t_{t} - t_{i}}{\lambda} x_{t-i}}{0.5^\frac{t_{t} - t_{i}}{\lambda}}, - -Here is an example for a univariate time series: - -.. ipython:: python - - s.plot(style="k--") - - @savefig ewma_ex.png - s.ewm(span=20).mean().plot(style="k") - -ExponentialMovingWindow has a ``min_periods`` argument, which has the same -meaning it does for all the ``.expanding`` and ``.rolling`` methods: -no output values will be set until at least ``min_periods`` non-null values -are encountered in the (expanding) window. - -ExponentialMovingWindow also has an ``ignore_na`` argument, which determines how -intermediate null values affect the calculation of the weights. -When ``ignore_na=False`` (the default), weights are calculated based on absolute -positions, so that intermediate null values affect the result. -When ``ignore_na=True``, -weights are calculated by ignoring intermediate null values. -For example, assuming ``adjust=True``, if ``ignore_na=False``, the weighted -average of ``3, NaN, 5`` would be calculated as - -.. math:: - - \frac{(1-\alpha)^2 \cdot 3 + 1 \cdot 5}{(1-\alpha)^2 + 1}. - -Whereas if ``ignore_na=True``, the weighted average would be calculated as - -.. math:: - - \frac{(1-\alpha) \cdot 3 + 1 \cdot 5}{(1-\alpha) + 1}. - -The :meth:`~Ewm.var`, :meth:`~Ewm.std`, and :meth:`~Ewm.cov` functions have a ``bias`` argument, -specifying whether the result should contain biased or unbiased statistics. -For example, if ``bias=True``, ``ewmvar(x)`` is calculated as -``ewmvar(x) = ewma(x**2) - ewma(x)**2``; -whereas if ``bias=False`` (the default), the biased variance statistics -are scaled by debiasing factors - -.. math:: - - \frac{\left(\sum_{i=0}^t w_i\right)^2}{\left(\sum_{i=0}^t w_i\right)^2 - \sum_{i=0}^t w_i^2}. - -(For :math:`w_i = 1`, this reduces to the usual :math:`N / (N - 1)` factor, -with :math:`N = t + 1`.) -See `Weighted Sample Variance `__ -on Wikipedia for further details. diff --git a/doc/source/user_guide/enhancingperf.rst b/doc/source/user_guide/enhancingperf.rst index 39257c06feffe..42621c032416d 100644 --- a/doc/source/user_guide/enhancingperf.rst +++ b/doc/source/user_guide/enhancingperf.rst @@ -375,7 +375,7 @@ Numba as an argument Additionally, we can leverage the power of `Numba `__ by calling it as an argument in :meth:`~Rolling.apply`. See :ref:`Computation tools -` for an extensive example. +` for an extensive example. Vectorize ~~~~~~~~~ diff --git a/doc/source/user_guide/groupby.rst b/doc/source/user_guide/groupby.rst index 87ead5a1b80f0..e19dace572e59 100644 --- a/doc/source/user_guide/groupby.rst +++ b/doc/source/user_guide/groupby.rst @@ -478,7 +478,7 @@ Aggregation Once the GroupBy object has been created, several methods are available to perform a computation on the grouped data. These operations are similar to the -:ref:`aggregating API `, :ref:`window functions API `, +:ref:`aggregating API `, :ref:`window API `, and :ref:`resample API `. An obvious one is aggregation via the diff --git a/doc/source/user_guide/index.rst b/doc/source/user_guide/index.rst index 2fc9e066e6712..901f42097b911 100644 --- a/doc/source/user_guide/index.rst +++ b/doc/source/user_guide/index.rst @@ -40,6 +40,7 @@ Further information on any specific method can be obtained in the visualization computation groupby + window timeseries timedeltas style diff --git a/doc/source/user_guide/timeseries.rst b/doc/source/user_guide/timeseries.rst index ac8ba2fd929a6..169c0cfbbb87e 100644 --- a/doc/source/user_guide/timeseries.rst +++ b/doc/source/user_guide/timeseries.rst @@ -1580,11 +1580,6 @@ some advanced strategies. The ``resample()`` method can be used directly from ``DataFrameGroupBy`` objects, see the :ref:`groupby docs `. -.. note:: - - ``.resample()`` is similar to using a :meth:`~Series.rolling` operation with - a time-based offset, see a discussion :ref:`here `. - Basics ~~~~~~ @@ -1730,7 +1725,7 @@ We can instead only resample those groups where we have points as follows: Aggregation ~~~~~~~~~~~ -Similar to the :ref:`aggregating API `, :ref:`groupby API `, and the :ref:`window functions API `, +Similar to the :ref:`aggregating API `, :ref:`groupby API `, and the :ref:`window API `, a ``Resampler`` can be selectively resampled. Resampling a ``DataFrame``, the default will be to act on all columns with the same function. diff --git a/doc/source/user_guide/window.rst b/doc/source/user_guide/window.rst new file mode 100644 index 0000000000000..47ef1e9c8c4d7 --- /dev/null +++ b/doc/source/user_guide/window.rst @@ -0,0 +1,593 @@ +.. _window: + +{{ header }} + +******************** +Windowing Operations +******************** + +pandas contains a compact set of APIs for performing windowing operations - an operation that performs +an aggregation over a sliding partition of values. The API functions similarly to the ``groupby`` API +in that :class:`Series` and :class:`DataFrame` call the windowing method with +necessary parameters and then subsequently call the aggregation function. + +.. ipython:: python + + s = pd.Series(range(5)) + s.rolling(window=2).sum() + +The windows are comprised by looking back the length of the window from the current observation. +The result above can be derived by taking the sum of the following windowed partitions of data: + +.. ipython:: python + + for window in s.rolling(window=2): + print(window) + + +.. _window.overview: + +Overview +-------- + +pandas supports 4 types of windowing operations: + +#. Rolling window: Generic fixed or variable sliding window over the values. +#. Weighted window: Weighted, non-rectangular window supplied by the ``scipy.signal`` library. +#. Expanding window: Accumulating window over the values. +#. Exponentially Weighted window: Accumulating and exponentially weighted window over the values. + +============================= ================= =========================== =========================== ======================== +Concept Method Returned Object Supports time-based windows Supports chained groupby +============================= ================= =========================== =========================== ======================== +Rolling window ``rolling`` ``Rolling`` Yes Yes +Weighted window ``rolling`` ``Window`` No No +Expanding window ``expanding`` ``Expanding`` No Yes +Exponentially Weighted window ``ewm`` ``ExponentialMovingWindow`` No No +============================= ================= =========================== =========================== ======================== + +As noted above, some operations support specifying a window based on a time offset: + +.. ipython:: python + + s = pd.Series(range(5), index=pd.date_range('2020-01-01', periods=5, freq='1D')) + s.rolling(window='2D').sum() + +Additionally, some methods support chaining a ``groupby`` operation with a windowing operation +which will first group the data by the specified keys and then perform a windowing operation per group. + +.. ipython:: python + + df = pd.DataFrame({'A': ['a', 'b', 'a', 'b', 'a'], 'B': range(5)}) + df.groupby('A').expanding().sum() + +.. note:: + + Windowing operations currently only support numeric data (integer and float) + and will always return ``float64`` values. + +.. warning:: + + Some windowing aggregation, ``mean``, ``sum``, ``var`` and ``std`` methods may suffer from numerical + imprecision due to the underlying windowing algorithms accumulating sums. When values differ + with magnitude :math:`1/np.finfo(np.double).eps` this results in truncation. It must be + noted, that large values may have an impact on windows, which do not include these values. `Kahan summation + `__ is used + to compute the rolling sums to preserve accuracy as much as possible. + + +All windowing operations support a ``min_periods`` argument that dictates the minimum amount of +non-``np.nan`` values a window must have; otherwise, the resulting value is ``np.nan``. +``min_peridos`` defaults to 1 for time-based windows and ``window`` for fixed windows + +.. ipython:: python + + s = pd.Series([np.nan, 1, 2, np.nan, np.nan, 3]) + s.rolling(window=3, min_periods=1).sum() + s.rolling(window=3, min_periods=2).sum() + # Equivalent to min_periods=3 + s.rolling(window=3, min_periods=None).sum() + + +Additionally, all windowing operations supports the ``aggregate`` method for returning a result +of multiple aggregations applied to a window. + +.. ipython:: python + + df = pd.DataFrame({"A": range(5), "B": range(10, 15)}) + df.expanding().agg([np.sum, np.mean, np.std]) + + +.. _window.generic: + +Rolling window +-------------- + +Generic rolling windows support specifying windows as a fixed number of observations or variable +number of observations based on an offset. If a time based offset is provided, the corresponding +time based index must be monotonic. + +.. ipython:: python + + times = ['2020-01-01', '2020-01-03', '2020-01-04', '2020-01-05', '2020-01-29'] + s = pd.Series(range(5), index=pd.DatetimeIndex(times)) + s + # Window with 2 observations + s.rolling(window=2).sum() + # Window with 2 days worth of observations + s.rolling(window='2D').sum() + +For all supported aggregation functions, see :ref:`api.functions_rolling`. + +.. _window.center: + +Centering windows +~~~~~~~~~~~~~~~~~ + +By default the labels are set to the right edge of the window, but a +``center`` keyword is available so the labels can be set at the center. + +.. ipython:: python + + s = pd.Series(range(10)) + s.rolling(window=5).mean() + s.rolling(window=5, center=True).mean() + + +.. _window.endpoints: + +Rolling window endpoints +~~~~~~~~~~~~~~~~~~~~~~~~ + +The inclusion of the interval endpoints in rolling window calculations can be specified with the ``closed`` +parameter: + +============= ==================== +Value Behavior +============= ==================== +``right'`` close right endpoint +``'left'`` close left endpoint +``'both'`` close both endpoints +``'neither'`` open endpoints +============= ==================== + +For example, having the right endpoint open is useful in many problems that require that there is no contamination +from present information back to past information. This allows the rolling window to compute statistics +"up to that point in time", but not including that point in time. + +.. ipython:: python + + df = pd.DataFrame( + {"x": 1}, + index=[ + pd.Timestamp("20130101 09:00:01"), + pd.Timestamp("20130101 09:00:02"), + pd.Timestamp("20130101 09:00:03"), + pd.Timestamp("20130101 09:00:04"), + pd.Timestamp("20130101 09:00:06"), + ], + ) + + df["right"] = df.rolling("2s", closed="right").x.sum() # default + df["both"] = df.rolling("2s", closed="both").x.sum() + df["left"] = df.rolling("2s", closed="left").x.sum() + df["neither"] = df.rolling("2s", closed="neither").x.sum() + + df + + +.. _window.custom_rolling_window: + +Custom window rolling +~~~~~~~~~~~~~~~~~~~~~ + +.. versionadded:: 1.0 + +In addition to accepting an integer or offset as a ``window`` argument, ``rolling`` also accepts +a ``BaseIndexer`` subclass that allows a user to define a custom method for calculating window bounds. +The ``BaseIndexer`` subclass will need to define a ``get_window_bounds`` method that returns +a tuple of two arrays, the first being the starting indices of the windows and second being the +ending indices of the windows. Additionally, ``num_values``, ``min_periods``, ``center``, ``closed`` +and will automatically be passed to ``get_window_bounds`` and the defined method must +always accept these arguments. + +For example, if we have the following :class:``DataFrame``: + +.. ipython:: python + + use_expanding = [True, False, True, False, True] + use_expanding + df = pd.DataFrame({"values": range(5)}) + df + +and we want to use an expanding window where ``use_expanding`` is ``True`` otherwise a window of size +1, we can create the following ``BaseIndexer`` subclass: + +.. code-block:: ipython + + In [2]: from pandas.api.indexers import BaseIndexer + ...: + ...: class CustomIndexer(BaseIndexer): + ...: + ...: def get_window_bounds(self, num_values, min_periods, center, closed): + ...: start = np.empty(num_values, dtype=np.int64) + ...: end = np.empty(num_values, dtype=np.int64) + ...: for i in range(num_values): + ...: if self.use_expanding[i]: + ...: start[i] = 0 + ...: end[i] = i + 1 + ...: else: + ...: start[i] = i + ...: end[i] = i + self.window_size + ...: return start, end + ...: + + In [3]: indexer = CustomIndexer(window_size=1, use_expanding=use_expanding) + + In [4]: df.rolling(indexer).sum() + Out[4]: + values + 0 0.0 + 1 1.0 + 2 3.0 + 3 3.0 + 4 10.0 + +You can view other examples of ``BaseIndexer`` subclasses `here `__ + +.. versionadded:: 1.1 + +One subclass of note within those examples is the ``VariableOffsetWindowIndexer`` that allows +rolling operations over a non-fixed offset like a ``BusinessDay``. + +.. ipython:: python + + from pandas.api.indexers import VariableOffsetWindowIndexer + + df = pd.DataFrame(range(10), index=pd.date_range("2020", periods=10)) + offset = pd.offsets.BDay(1) + indexer = VariableOffsetWindowIndexer(index=df.index, offset=offset) + df + df.rolling(indexer).sum() + +For some problems knowledge of the future is available for analysis. For example, this occurs when +each data point is a full time series read from an experiment, and the task is to extract underlying +conditions. In these cases it can be useful to perform forward-looking rolling window computations. +:func:`FixedForwardWindowIndexer ` class is available for this purpose. +This :func:`BaseIndexer ` subclass implements a closed fixed-width +forward-looking rolling window, and we can use it as follows: + +.. ipython:: ipython + + from pandas.api.indexers import FixedForwardWindowIndexer + indexer = FixedForwardWindowIndexer(window_size=2) + df.rolling(indexer, min_periods=1).sum() + + +.. _window.rolling_apply: + +Rolling apply +~~~~~~~~~~~~~ + +The :meth:`~Rolling.apply` function takes an extra ``func`` argument and performs +generic rolling computations. The ``func`` argument should be a single function +that produces a single value from an ndarray input. ``raw`` specifies whether +the windows are cast as :class:`Series` objects (``raw=False``) or ndarray objects (``raw=True``). + +.. ipython:: python + + def mad(x): + return np.fabs(x - x.mean()).mean() + + s = pd.Series(range(10)) + s.rolling(window=4).apply(mad, raw=True) + + +.. _window.numba_engine: + +Numba engine +~~~~~~~~~~~~ + +.. versionadded:: 1.0 + +Additionally, :meth:`~Rolling.apply` can leverage `Numba `__ +if installed as an optional dependency. The apply aggregation can be executed using Numba by specifying +``engine='numba'`` and ``engine_kwargs`` arguments (``raw`` must also be set to ``True``). +Numba will be applied in potentially two routines: + +#. If ``func`` is a standard Python function, the engine will `JIT `__ the passed function. ``func`` can also be a JITed function in which case the engine will not JIT the function again. +#. The engine will JIT the for loop where the apply function is applied to each window. + +The ``engine_kwargs`` argument is a dictionary of keyword arguments that will be passed into the +`numba.jit decorator `__. +These keyword arguments will be applied to *both* the passed function (if a standard Python function) +and the apply for loop over each window. Currently only ``nogil``, ``nopython``, and ``parallel`` are supported, +and their default values are set to ``False``, ``True`` and ``False`` respectively. + +.. note:: + + In terms of performance, **the first time a function is run using the Numba engine will be slow** + as Numba will have some function compilation overhead. However, the compiled functions are cached, + and subsequent calls will be fast. In general, the Numba engine is performant with + a larger amount of data points (e.g. 1+ million). + +.. code-block:: ipython + + In [1]: data = pd.Series(range(1_000_000)) + + In [2]: roll = data.rolling(10) + + In [3]: def f(x): + ...: return np.sum(x) + 5 + # Run the first time, compilation time will affect performance + In [4]: %timeit -r 1 -n 1 roll.apply(f, engine='numba', raw=True) # noqa: E225, E999 + 1.23 s ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each) + # Function is cached and performance will improve + In [5]: %timeit roll.apply(f, engine='numba', raw=True) + 188 ms ± 1.93 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) + + In [6]: %timeit roll.apply(f, engine='cython', raw=True) + 3.92 s ± 59 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) + +.. _window.cov_corr: + +Binary window functions +~~~~~~~~~~~~~~~~~~~~~~~ + +:meth:`~Rolling.cov` and :meth:`~Rolling.corr` can compute moving window statistics about +two :class:`Series` or any combination of :class:`DataFrame`/:class:`Series` or +:class:`DataFrame`/:class:`DataFrame`. Here is the behavior in each case: + +* two :class:`Series`: compute the statistic for the pairing. +* :class:`DataFrame`/:class:`Series`: compute the statistics for each column of the DataFrame + with the passed Series, thus returning a DataFrame. +* :class:`DataFrame`/:class:`DataFrame`: by default compute the statistic for matching column + names, returning a DataFrame. If the keyword argument ``pairwise=True`` is + passed then computes the statistic for each pair of columns, returning a + ``MultiIndexed DataFrame`` whose ``index`` are the dates in question (see :ref:`the next section + `). + +For example: + +.. ipython:: python + + df = pd.DataFrame( + np.random.randn(10, 4), + index=pd.date_range("2020-01-01", periods=10), + columns=["A", "B", "C", "D"], + ) + df = df.cumsum() + + df2 = df[:4] + df2.rolling(window=2).corr(df2["B"]) + +.. _window.corr_pairwise: + +Computing rolling pairwise covariances and correlations +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In financial data analysis and other fields it's common to compute covariance +and correlation matrices for a collection of time series. Often one is also +interested in moving-window covariance and correlation matrices. This can be +done by passing the ``pairwise`` keyword argument, which in the case of +:class:`DataFrame` inputs will yield a MultiIndexed :class:`DataFrame` whose ``index`` are the dates in +question. In the case of a single DataFrame argument the ``pairwise`` argument +can even be omitted: + +.. note:: + + Missing values are ignored and each entry is computed using the pairwise + complete observations. Please see the :ref:`covariance section + ` for :ref:`caveats + ` associated with this method of + calculating covariance and correlation matrices. + +.. ipython:: python + + covs = ( + df[["B", "C", "D"]] + .rolling(window=4) + .cov(df[["A", "B", "C"]], pairwise=True) + ) + covs + + +.. _window.weighted: + +Weighted window +--------------- + +The ``win_type`` argument in ``.rolling`` generates a weighted windows that are commonly used in filtering +and spectral estimation. ``win_type`` must be string that corresponds to a `scipy.signal window function +`__. +Scipy must be installed in order to use these windows, and supplementary arguments +that the Scipy window methods take must be specified in the aggregation function. + + +.. ipython:: python + + s = pd.Series(range(10)) + s.rolling(window=5).mean() + s.rolling(window=5, win_type="triang").mean() + # Supplementary Scipy arguments passed in the aggregation function + s.rolling(window=5, win_type="gaussian").mean(std=0.1) + +For all supported aggregation functions, see :ref:`api.functions_window`. + +.. _window.expanding: + +Expanding window +---------------- + +An expanding window yields the value of an aggregation statistic with all the data available up to that +point in time. Since these calculations are a special case of rolling statistics, +they are implemented in pandas such that the following two calls are equivalent: + +.. ipython:: python + + df = pd.DataFrame(range(5)) + df.rolling(window=len(df), min_periods=1).mean() + df.expanding(min_periods=1).mean() + +For all supported aggregation functions, see :ref:`api.functions_expanding`. + + +.. _window.exponentially_weighted: + +Exponentially Weighted window +----------------------------- + +An exponentially weighted window is similar to an expanding window but with each prior point +being exponentially weighted down relative to the current point. + +In general, a weighted moving average is calculated as + +.. math:: + + y_t = \frac{\sum_{i=0}^t w_i x_{t-i}}{\sum_{i=0}^t w_i}, + +where :math:`x_t` is the input, :math:`y_t` is the result and the :math:`w_i` +are the weights. + +For all supported aggregation functions, see :ref:`api.functions_ewm`. + +The EW functions support two variants of exponential weights. +The default, ``adjust=True``, uses the weights :math:`w_i = (1 - \alpha)^i` +which gives + +.. 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`` is specified, moving averages are calculated as + +.. math:: + + y_0 &= x_0 \\ + y_t &= (1 - \alpha) y_{t-1} + \alpha x_t, + +which is equivalent to using weights + +.. math:: + + w_i = \begin{cases} + \alpha (1 - \alpha)^i & \text{if } i < t \\ + (1 - \alpha)^i & \text{if } i = t. + \end{cases} + +.. note:: + + These equations are sometimes written in terms of :math:`\alpha' = 1 - \alpha`, e.g. + + .. math:: + + y_t = \alpha' y_{t-1} + (1 - \alpha') x_t. + +The difference between the above two variants arises because we are +dealing with series which have finite history. Consider a series of infinite +history, with ``adjust=True``: + +.. math:: + + y_t = \frac{x_t + (1 - \alpha)x_{t-1} + (1 - \alpha)^2 x_{t-2} + ...} + {1 + (1 - \alpha) + (1 - \alpha)^2 + ...} + +Noting that the denominator is a geometric series with initial term equal to 1 +and a ratio of :math:`1 - \alpha` we have + +.. math:: + + y_t &= \frac{x_t + (1 - \alpha)x_{t-1} + (1 - \alpha)^2 x_{t-2} + ...} + {\frac{1}{1 - (1 - \alpha)}}\\ + &= [x_t + (1 - \alpha)x_{t-1} + (1 - \alpha)^2 x_{t-2} + ...] \alpha \\ + &= \alpha x_t + [(1-\alpha)x_{t-1} + (1 - \alpha)^2 x_{t-2} + ...]\alpha \\ + &= \alpha x_t + (1 - \alpha)[x_{t-1} + (1 - \alpha) x_{t-2} + ...]\alpha\\ + &= \alpha x_t + (1 - \alpha) y_{t-1} + +which is the same expression as ``adjust=False`` above and therefore +shows the equivalence of the two variants for infinite series. +When ``adjust=False``, we have :math:`y_0 = x_0` and +:math:`y_t = \alpha x_t + (1 - \alpha) y_{t-1}`. +Therefore, there is an assumption that :math:`x_0` is not an ordinary value +but rather an exponentially weighted moment of the infinite series up to that +point. + +One must have :math:`0 < \alpha \leq 1`, and while it is possible to pass +:math:`\alpha` directly, it's often easier to think about either the +**span**, **center of mass (com)** or **half-life** of an EW moment: + +.. math:: + + \alpha = + \begin{cases} + \frac{2}{s + 1}, & \text{for span}\ s \geq 1\\ + \frac{1}{1 + c}, & \text{for center of mass}\ c \geq 0\\ + 1 - \exp^{\frac{\log 0.5}{h}}, & \text{for half-life}\ h > 0 + \end{cases} + +One must specify precisely one of **span**, **center of mass**, **half-life** +and **alpha** to the EW functions: + +* **Span** corresponds to what is commonly called an "N-day EW moving average". +* **Center of mass** has a more physical interpretation and can be thought of + in terms of span: :math:`c = (s - 1) / 2`. +* **Half-life** is the period of time for the exponential weight to reduce to + one half. +* **Alpha** specifies the smoothing factor directly. + +.. versionadded:: 1.1.0 + +You can also specify ``halflife`` in terms of a timedelta convertible unit to specify the amount of +time it takes for an observation to decay to half its value when also specifying a sequence +of ``times``. + +.. ipython:: python + + df = pd.DataFrame({"B": [0, 1, 2, np.nan, 4]}) + df + 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() + +The following formula is used to compute exponentially weighted mean with an input vector of times: + +.. math:: + + y_t = \frac{\sum_{i=0}^t 0.5^\frac{t_{t} - t_{i}}{\lambda} x_{t-i}}{0.5^\frac{t_{t} - t_{i}}{\lambda}}, + + +ExponentialMovingWindow also has an ``ignore_na`` argument, which determines how +intermediate null values affect the calculation of the weights. +When ``ignore_na=False`` (the default), weights are calculated based on absolute +positions, so that intermediate null values affect the result. +When ``ignore_na=True``, +weights are calculated by ignoring intermediate null values. +For example, assuming ``adjust=True``, if ``ignore_na=False``, the weighted +average of ``3, NaN, 5`` would be calculated as + +.. math:: + + \frac{(1-\alpha)^2 \cdot 3 + 1 \cdot 5}{(1-\alpha)^2 + 1}. + +Whereas if ``ignore_na=True``, the weighted average would be calculated as + +.. math:: + + \frac{(1-\alpha) \cdot 3 + 1 \cdot 5}{(1-\alpha) + 1}. + +The :meth:`~Ewm.var`, :meth:`~Ewm.std`, and :meth:`~Ewm.cov` functions have a ``bias`` argument, +specifying whether the result should contain biased or unbiased statistics. +For example, if ``bias=True``, ``ewmvar(x)`` is calculated as +``ewmvar(x) = ewma(x**2) - ewma(x)**2``; +whereas if ``bias=False`` (the default), the biased variance statistics +are scaled by debiasing factors + +.. math:: + + \frac{\left(\sum_{i=0}^t w_i\right)^2}{\left(\sum_{i=0}^t w_i\right)^2 - \sum_{i=0}^t w_i^2}. + +(For :math:`w_i = 1`, this reduces to the usual :math:`N / (N - 1)` factor, +with :math:`N = t + 1`.) +See `Weighted Sample Variance `__ +on Wikipedia for further details. diff --git a/doc/source/whatsnew/v0.14.0.rst b/doc/source/whatsnew/v0.14.0.rst index f2401c812a979..5b279a4973963 100644 --- a/doc/source/whatsnew/v0.14.0.rst +++ b/doc/source/whatsnew/v0.14.0.rst @@ -171,7 +171,7 @@ API changes ``expanding_cov``, ``expanding_corr`` to allow the calculation of moving window covariance and correlation matrices (:issue:`4950`). See :ref:`Computing rolling pairwise covariances and correlations - ` in the docs. + ` in the docs. .. code-block:: ipython diff --git a/doc/source/whatsnew/v0.15.0.rst b/doc/source/whatsnew/v0.15.0.rst index 1f054930b3709..fc2b070df4392 100644 --- a/doc/source/whatsnew/v0.15.0.rst +++ b/doc/source/whatsnew/v0.15.0.rst @@ -405,7 +405,7 @@ Rolling/expanding moments improvements - :func:`rolling_window` now normalizes the weights properly in rolling mean mode (`mean=True`) so that the calculated weighted means (e.g. 'triang', 'gaussian') are distributed about the same means as those - calculated without weighting (i.e. 'boxcar'). See :ref:`the note on normalization ` for further details. (:issue:`7618`) + calculated without weighting (i.e. 'boxcar'). See :ref:`the note on normalization ` for further details. (:issue:`7618`) .. ipython:: python @@ -490,7 +490,7 @@ Rolling/expanding moments improvements now have an optional ``adjust`` argument, just like :func:`ewma` does, affecting how the weights are calculated. The default value of ``adjust`` is ``True``, which is backwards-compatible. - See :ref:`Exponentially weighted moment functions ` for details. (:issue:`7911`) + See :ref:`Exponentially weighted moment functions ` for details. (:issue:`7911`) - :func:`ewma`, :func:`ewmstd`, :func:`ewmvol`, :func:`ewmvar`, :func:`ewmcov`, and :func:`ewmcorr` now have an optional ``ignore_na`` argument. @@ -595,7 +595,7 @@ Rolling/expanding moments improvements 3 1.425439 dtype: float64 - See :ref:`Exponentially weighted moment functions ` for details. (:issue:`7912`) + See :ref:`Exponentially weighted moment functions ` for details. (:issue:`7912`) .. _whatsnew_0150.sql: diff --git a/doc/source/whatsnew/v0.18.0.rst b/doc/source/whatsnew/v0.18.0.rst index ef5242b0e33c8..636414cdab8d8 100644 --- a/doc/source/whatsnew/v0.18.0.rst +++ b/doc/source/whatsnew/v0.18.0.rst @@ -53,7 +53,7 @@ New features Window functions are now methods ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -Window functions have been refactored to be methods on ``Series/DataFrame`` objects, rather than top-level functions, which are now deprecated. This allows these window-type functions, to have a similar API to that of ``.groupby``. See the full documentation :ref:`here ` (:issue:`11603`, :issue:`12373`) +Window functions have been refactored to be methods on ``Series/DataFrame`` objects, rather than top-level functions, which are now deprecated. This allows these window-type functions, to have a similar API to that of ``.groupby``. See the full documentation :ref:`here ` (:issue:`11603`, :issue:`12373`) .. ipython:: python diff --git a/doc/source/whatsnew/v0.19.0.rst b/doc/source/whatsnew/v0.19.0.rst index 2ac7b0f54361b..340e1ce9ee1ef 100644 --- a/doc/source/whatsnew/v0.19.0.rst +++ b/doc/source/whatsnew/v0.19.0.rst @@ -135,7 +135,7 @@ Method ``.rolling()`` is now time-series aware ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ``.rolling()`` objects are now time-series aware and can accept a time-series offset (or convertible) for the ``window`` argument (:issue:`13327`, :issue:`12995`). -See the full documentation :ref:`here `. +See the full documentation :ref:`here `. .. ipython:: python diff --git a/doc/source/whatsnew/v0.20.0.rst b/doc/source/whatsnew/v0.20.0.rst index a9e57f0039735..8ae5ea5726fe9 100644 --- a/doc/source/whatsnew/v0.20.0.rst +++ b/doc/source/whatsnew/v0.20.0.rst @@ -459,7 +459,7 @@ Selecting via a scalar value that is contained *in* the intervals. Other enhancements ^^^^^^^^^^^^^^^^^^ -- ``DataFrame.rolling()`` now accepts the parameter ``closed='right'|'left'|'both'|'neither'`` to choose the rolling window-endpoint closedness. See the :ref:`documentation ` (:issue:`13965`) +- ``DataFrame.rolling()`` now accepts the parameter ``closed='right'|'left'|'both'|'neither'`` to choose the rolling window-endpoint closedness. See the :ref:`documentation ` (:issue:`13965`) - Integration with the ``feather-format``, including a new top-level ``pd.read_feather()`` and ``DataFrame.to_feather()`` method, see :ref:`here `. - ``Series.str.replace()`` now accepts a callable, as replacement, which is passed to ``re.sub`` (:issue:`15055`) - ``Series.str.replace()`` now accepts a compiled regular expression as a pattern (:issue:`15446`) @@ -988,7 +988,7 @@ A binary window operation, like ``.corr()`` or ``.cov()``, when operating on a ` will now return a 2-level ``MultiIndexed DataFrame`` rather than a ``Panel``, as ``Panel`` is now deprecated, see :ref:`here `. These are equivalent in function, but a MultiIndexed ``DataFrame`` enjoys more support in pandas. -See the section on :ref:`Windowed Binary Operations ` for more information. (:issue:`15677`) +See the section on :ref:`Windowed Binary Operations ` for more information. (:issue:`15677`) .. ipython:: python diff --git a/doc/source/whatsnew/v0.6.1.rst b/doc/source/whatsnew/v0.6.1.rst index 8ee80fa2c44b1..139c6e2d1cb0c 100644 --- a/doc/source/whatsnew/v0.6.1.rst +++ b/doc/source/whatsnew/v0.6.1.rst @@ -25,12 +25,12 @@ New features constructor (:issue:`444`) - DataFrame.convert_objects method for :ref:`inferring better dtypes ` for object columns (:issue:`302`) -- Add :ref:`rolling_corr_pairwise ` function for +- Add :ref:`rolling_corr_pairwise ` function for computing Panel of correlation matrices (:issue:`189`) - Add :ref:`margins ` option to :ref:`pivot_table ` for computing subgroup aggregates (:issue:`114`) - Add ``Series.from_csv`` function (:issue:`482`) -- :ref:`Can pass ` DataFrame/DataFrame and +- :ref:`Can pass ` DataFrame/DataFrame and DataFrame/Series to rolling_corr/rolling_cov (GH #462) - MultiIndex.get_level_values can :ref:`accept the level name ` diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 8f9ceb30a947a..6512e4cce02a9 100755 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -46,7 +46,7 @@ We've added an ``engine`` keyword to :meth:`~core.window.rolling.Rolling.apply` that allows the user to execute the routine using `Numba `__ instead of Cython. Using the Numba engine can yield significant performance gains if the apply function can operate on numpy arrays and the data set is larger (1 million rows or greater). For more details, see -:ref:`rolling apply documentation ` (:issue:`28987`, :issue:`30936`) +:ref:`rolling apply documentation ` (:issue:`28987`, :issue:`30936`) .. _whatsnew_100.custom_window: @@ -57,7 +57,7 @@ We've added a :func:`pandas.api.indexers.BaseIndexer` class that allows users to window bounds are created during ``rolling`` operations. Users can define their own ``get_window_bounds`` method on a :func:`pandas.api.indexers.BaseIndexer` subclass that will generate the start and end indices used for each window during the rolling aggregation. For more details and example usage, see -the :ref:`custom window rolling documentation ` +the :ref:`custom window rolling documentation ` .. _whatsnew_100.to_markdown: diff --git a/pandas/core/window/ewm.py b/pandas/core/window/ewm.py index 9f7040943d9a3..b601bacec35f1 100644 --- a/pandas/core/window/ewm.py +++ b/pandas/core/window/ewm.py @@ -172,7 +172,7 @@ class ExponentialMovingWindow(BaseWindow): ----- More details can be found at: - :ref:`Exponentially weighted windows `. + :ref:`Exponentially weighted windows `. Examples -------- diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index 5d561c84ab462..f65452cb2f17f 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -1270,7 +1270,7 @@ def count(self): Notes ----- - See :ref:`stats.rolling_apply` for extended documentation and performance + See :ref:`window.numba_engine` for extended documentation and performance considerations for the Numba engine. """ )