Computational tools

Statistical Functions

Percent Change

Series, DataFrame, and Panel all have a method pct_change() to compute the percent change over a given number of periods (using fill_method to fill NA/null values before computing the percent change).

In [1]: ser = pd.Series(np.random.randn(8))

In [2]: ser.pct_change()
Out[2]: 
0         NaN
1   -1.602976
2    4.334938
3   -0.247456
4   -2.067345
5   -1.142903
6   -1.688214
7   -9.759729
dtype: float64
In [3]: df = pd.DataFrame(np.random.randn(10, 4))

In [4]: df.pct_change(periods=3)
Out[4]: 
          0         1         2         3
0       NaN       NaN       NaN       NaN
1       NaN       NaN       NaN       NaN
2       NaN       NaN       NaN       NaN
3 -0.218320 -1.054001  1.987147 -0.510183
4 -0.439121 -1.816454  0.649715 -4.822809
5 -0.127833 -3.042065 -5.866604 -1.776977
6 -2.596833 -1.959538 -2.111697 -3.798900
7 -0.117826 -2.169058  0.036094 -0.067696
8  2.492606 -1.357320 -1.205802 -1.558697
9 -1.012977  2.324558 -1.003744 -0.371806

Covariance

Series.cov() can be used to compute covariance between series (excluding missing values).

In [5]: s1 = pd.Series(np.random.randn(1000))

In [6]: s2 = pd.Series(np.random.randn(1000))

In [7]: s1.cov(s2)
Out[7]: 0.0006801088174310797

Analogously, DataFrame.cov() to compute pairwise covariances among the series in the DataFrame, also excluding NA/null values.

Note

Assuming the missing data are missing at random this results in an estimate for the covariance matrix which is unbiased. However, for many applications this estimate may not be acceptable because the estimated covariance matrix is not guaranteed to be positive semi-definite. This could lead to estimated correlations having absolute values which are greater than one, and/or a non-invertible covariance matrix. See Estimation of covariance matrices for more details.

In [8]: frame = pd.DataFrame(np.random.randn(1000, 5), columns=['a', 'b', 'c', 'd', 'e'])

In [9]: frame.cov()
Out[9]: 
          a         b         c         d         e
a  1.000882 -0.003177 -0.002698 -0.006889  0.031912
b -0.003177  1.024721  0.000191  0.009212  0.000857
c -0.002698  0.000191  0.950735 -0.031743 -0.005087
d -0.006889  0.009212 -0.031743  1.002983 -0.047952
e  0.031912  0.000857 -0.005087 -0.047952  1.042487

DataFrame.cov also supports an optional min_periods keyword that specifies the required minimum number of observations for each column pair in order to have a valid result.

In [10]: frame = pd.DataFrame(np.random.randn(20, 3), columns=['a', 'b', 'c'])

In [11]: frame.loc[frame.index[:5], 'a'] = np.nan

In [12]: frame.loc[frame.index[5:10], 'b'] = np.nan

In [13]: frame.cov()
Out[13]: 
          a         b         c
a  1.123670 -0.412851  0.018169
b -0.412851  1.154141  0.305260
c  0.018169  0.305260  1.301149

In [14]: frame.cov(min_periods=12)
Out[14]: 
          a         b         c
a  1.123670       NaN  0.018169
b       NaN  1.154141  0.305260
c  0.018169  0.305260  1.301149

Correlation

Correlation may be computed using the corr() method. Using the method parameter, several methods for computing correlations are provided:

Method name Description
pearson (default) Standard correlation coefficient
kendall Kendall Tau correlation coefficient
spearman Spearman rank correlation coefficient

All of these are currently computed using pairwise complete observations. Wikipedia has articles covering the above correlation coefficients:

Note

Please see the caveats associated with this method of calculating correlation matrices in the covariance section.

In [15]: frame = pd.DataFrame(np.random.randn(1000, 5), columns=['a', 'b', 'c', 'd', 'e'])

In [16]: frame.iloc[::2] = np.nan

# Series with Series
In [17]: frame['a'].corr(frame['b'])
Out[17]: 0.013479040400098752

In [18]: frame['a'].corr(frame['b'], method='spearman')
Out[18]: -0.007289885159540637

# Pairwise correlation of DataFrame columns
In [19]: frame.corr()
Out[19]: 
          a         b         c         d         e
a  1.000000  0.013479 -0.049269 -0.042239 -0.028525
b  0.013479  1.000000 -0.020433 -0.011139  0.005654
c -0.049269 -0.020433  1.000000  0.018587 -0.054269
d -0.042239 -0.011139  0.018587  1.000000 -0.017060
e -0.028525  0.005654 -0.054269 -0.017060  1.000000

Note that non-numeric columns will be automatically excluded from the correlation calculation.

Like cov, corr also supports the optional min_periods keyword:

In [20]: frame = pd.DataFrame(np.random.randn(20, 3), columns=['a', 'b', 'c'])

In [21]: frame.loc[frame.index[:5], 'a'] = np.nan

In [22]: frame.loc[frame.index[5:10], 'b'] = np.nan

In [23]: frame.corr()
Out[23]: 
          a         b         c
a  1.000000 -0.121111  0.069544
b -0.121111  1.000000  0.051742
c  0.069544  0.051742  1.000000

In [24]: frame.corr(min_periods=12)
Out[24]: 
          a         b         c
a  1.000000       NaN  0.069544
b       NaN  1.000000  0.051742
c  0.069544  0.051742  1.000000

A related method corrwith() is implemented on DataFrame to compute the correlation between like-labeled Series contained in different DataFrame objects.

In [25]: index = ['a', 'b', 'c', 'd', 'e']

In [26]: columns = ['one', 'two', 'three', 'four']

In [27]: df1 = pd.DataFrame(np.random.randn(5, 4), index=index, columns=columns)

In [28]: df2 = pd.DataFrame(np.random.randn(4, 4), index=index[:4], columns=columns)

In [29]: df1.corrwith(df2)
Out[29]: 
one     -0.125501
two     -0.493244
three    0.344056
four     0.004183
dtype: float64

In [30]: df2.corrwith(df1, axis=1)
Out[30]: 
a   -0.675817
b    0.458296
c    0.190809
d   -0.186275
e         NaN
dtype: float64

Data ranking

The rank() method produces a data ranking with ties being assigned the mean of the ranks (by default) for the group:

In [31]: s = pd.Series(np.random.np.random.randn(5), index=list('abcde'))
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-31-7de7bc1a15b6> in <module>()
----> 1 s = pd.Series(np.random.np.random.randn(5), index=list('abcde'))

AttributeError: module 'numpy.random' has no attribute 'np'

In [32]: s['d'] = s['b'] # so there's a tie
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

TypeError: an integer is required

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
<ipython-input-32-d2911cce3319> in <module>()
----> 1 s['d'] = s['b'] # so there's a tie

/build/pandas-8klttm/pandas-0.23.3+dfsg/debian/python3-pandas/usr/lib/python3/dist-packages/pandas/core/series.py in __getitem__(self, key)
    765         key = com._apply_if_callable(key, self)
    766         try:
--> 767             result = self.index.get_value(self, key)
    768 
    769             if not is_scalar(result):

/build/pandas-8klttm/pandas-0.23.3+dfsg/debian/python3-pandas/usr/lib/python3/dist-packages/pandas/core/indexes/base.py in get_value(self, series, key)
   3116         try:
   3117             return self._engine.get_value(s, k,
-> 3118                                           tz=getattr(series.dtype, 'tz', None))
   3119         except KeyError as e1:
   3120             if len(self) > 0 and self.inferred_type in ['integer', 'boolean']:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

KeyError: 'b'

In [33]: s.rank()
Out[33]: 
0    1.0
1    2.0
2    3.0
3    4.0
4    5.0
dtype: float64

rank() is also a DataFrame method and can rank either the rows (axis=0) or the columns (axis=1). NaN values are excluded from the ranking.

In [34]: df = pd.DataFrame(np.random.np.random.randn(10, 6))
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-34-940224fbefe5> in <module>()
----> 1 df = pd.DataFrame(np.random.np.random.randn(10, 6))

AttributeError: module 'numpy.random' has no attribute 'np'

In [35]: df[4] = df[2][:5] # some ties

In [36]: df
Out[36]: 
          0         1         2         3         4
0 -0.861849 -2.104569 -0.494929  1.071804 -0.494929
1  0.721555 -0.706771 -1.039575  0.271860 -1.039575
2 -0.424972  0.567020  0.276232 -1.087401  0.276232
3 -0.673690  0.113648 -1.478427  0.524988 -1.478427
4  0.404705  0.577046 -1.715002 -1.039268 -1.715002
5 -0.370647 -1.157892 -1.344312  0.844885       NaN
6  1.075770 -0.109050  1.643563 -1.469388       NaN
7  0.357021 -0.674600 -1.776904 -0.968914       NaN
8 -1.294524  0.413738  0.276662 -0.472035       NaN
9 -0.013960 -0.362543 -0.006154 -0.923061       NaN

In [37]: df.rank(1)
Out[37]: 
     0    1    2    3    4
0  2.0  1.0  3.5  5.0  3.5
1  5.0  3.0  1.5  4.0  1.5
2  2.0  5.0  3.5  1.0  3.5
3  3.0  4.0  1.5  5.0  1.5
4  4.0  5.0  1.5  3.0  1.5
5  3.0  2.0  1.0  4.0  NaN
6  3.0  2.0  4.0  1.0  NaN
7  4.0  3.0  1.0  2.0  NaN
8  1.0  4.0  3.0  2.0  NaN
9  3.0  2.0  4.0  1.0  NaN

rank optionally takes a parameter ascending which by default is true; when false, data is reverse-ranked, with larger values assigned a smaller rank.

rank supports different tie-breaking methods, specified with the method parameter:

  • average : average rank of tied group
  • min : lowest rank in the group
  • max : highest rank in the group
  • first : ranks assigned in the order they appear in the array

Window Functions

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 groupby docs.

Note

The API for window statistics is quite similar to the way one works with GroupBy objects, see the documentation here.

We work with rolling, expanding and exponentially weighted data through the corresponding objects, Rolling, Expanding and EWM.

In [38]: s = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))

In [39]: s = s.cumsum()

In [40]: s
Out[40]: 
2000-01-01     1.989494
2000-01-02     1.816922
2000-01-03     1.594010
2000-01-04     1.792245
2000-01-05     2.739214
2000-01-06     1.834266
2000-01-07     0.670729
                ...    
2002-09-20   -58.633456
2002-09-21   -60.743559
2002-09-22   -60.500497
2002-09-23   -59.047433
2002-09-24   -58.546875
2002-09-25   -59.121350
2002-09-26   -58.427026
Freq: D, Length: 1000, dtype: float64

These are created from methods on Series and DataFrame.

In [41]: r = s.rolling(window=60)

In [42]: r
Out[42]: Rolling [window=60,center=False,axis=0]

These object provide tab-completion of the available methods and properties.

In [14]: r.
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:

In [43]: r.mean()
Out[43]: 
2000-01-01          NaN
2000-01-02          NaN
2000-01-03          NaN
2000-01-04          NaN
2000-01-05          NaN
2000-01-06          NaN
2000-01-07          NaN
                ...    
2002-09-20   -54.675015
2002-09-21   -54.935441
2002-09-22   -55.174728
2002-09-23   -55.407191
2002-09-24   -55.661286
2002-09-25   -55.892375
2002-09-26   -56.083344
Freq: D, Length: 1000, dtype: float64
In [44]: s.plot(style='k--')
Out[44]: <matplotlib.axes._subplots.AxesSubplot at 0x7f0ea99ea490>

In [45]: r.mean().plot(style='k')
Out[45]: <matplotlib.axes._subplots.AxesSubplot at 0x7f0ea99ea490>
_images/rolling_mean_ex.png

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:

In [46]: df = pd.DataFrame(np.random.randn(1000, 4),
   ....:                   index=pd.date_range('1/1/2000', periods=1000),
   ....:                   columns=['A', 'B', 'C', 'D'])
   ....: 

In [47]: df = df.cumsum()

In [48]: df.rolling(window=60).sum().plot(subplots=True)
Out[48]: 
array([<matplotlib.axes._subplots.AxesSubplot object at 0x7f0ea97b4390>,
       <matplotlib.axes._subplots.AxesSubplot object at 0x7f0ea975fbd0>,
       <matplotlib.axes._subplots.AxesSubplot object at 0x7f0ea978be90>,
       <matplotlib.axes._subplots.AxesSubplot object at 0x7f0ea973fc10>],
      dtype=object)
_images/rolling_mean_frame.png

Method Summary

We provide a number of common statistical functions:

Method Description
count() Number of non-null observations
sum() Sum of values
mean() Mean of values
median() Arithmetic median of values
min() Minimum
max() Maximum
std() Bessel-corrected sample standard deviation
var() Unbiased variance
skew() Sample skewness (3rd moment)
kurt() Sample kurtosis (4th moment)
quantile() Sample quantile (value at %)
apply() Generic apply
cov() Unbiased covariance (binary)
corr() Correlation (binary)

The 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:

In [49]: mad = lambda x: np.fabs(x - x.mean()).mean()

In [50]: s.rolling(window=60).apply(mad, raw=True).plot(style='k')
Out[50]: <matplotlib.axes._subplots.AxesSubplot at 0x7f0ea951bfd0>
_images/rolling_apply_ex.png

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:

Method Description
sum() Sum of values
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).
In [51]: ser = pd.Series(np.random.randn(10), index=pd.date_range('1/1/2000', periods=10))

In [52]: ser.rolling(window=5, win_type='triang').mean()
Out[52]: 
2000-01-01         NaN
2000-01-02         NaN
2000-01-03         NaN
2000-01-04         NaN
2000-01-05   -0.701291
2000-01-06   -0.661360
2000-01-07   -0.390006
2000-01-08    0.157592
2000-01-09    0.227740
2000-01-10    0.398886
Freq: D, dtype: float64

Note that the boxcar window is equivalent to mean().

In [53]: ser.rolling(window=5, win_type='boxcar').mean()
Out[53]: 
2000-01-01         NaN
2000-01-02         NaN
2000-01-03         NaN
2000-01-04         NaN
2000-01-05   -0.490679
2000-01-06   -0.598709
2000-01-07   -0.349728
2000-01-08    0.128472
2000-01-09    0.019152
2000-01-10    0.393579
Freq: D, dtype: float64

In [54]: ser.rolling(window=5).mean()
Out[54]: 
2000-01-01         NaN
2000-01-02         NaN
2000-01-03         NaN
2000-01-04         NaN
2000-01-05   -0.490679
2000-01-06   -0.598709
2000-01-07   -0.349728
2000-01-08    0.128472
2000-01-09    0.019152
2000-01-10    0.393579
Freq: D, dtype: float64

For some windowing functions, additional parameters must be specified:

In [55]: ser.rolling(window=5, win_type='gaussian').mean(std=0.1)
Out[55]: 
2000-01-01         NaN
2000-01-02         NaN
2000-01-03         NaN
2000-01-04         NaN
2000-01-05   -0.966162
2000-01-06   -0.332601
2000-01-07   -1.327330
2000-01-08    1.225847
2000-01-09   -0.348395
2000-01-10    1.424840
Freq: D, dtype: float64

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.

Time-aware Rolling

New in version 0.19.0.

New in version 0.19.0 are the ability 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.

In [56]: dft = pd.DataFrame({'B': [0, 1, 2, np.nan, 4]},
   ....:                    index=pd.date_range('20130101 09:00:00', periods=5, freq='s'))
   ....: 

In [57]: dft
Out[57]: 
                       B
2013-01-01 09:00:00  0.0
2013-01-01 09:00:01  1.0
2013-01-01 09:00:02  2.0
2013-01-01 09:00:03  NaN
2013-01-01 09:00:04  4.0

This is a regular frequency index. Using an integer window parameter works to roll along the window frequency.

In [58]: dft.rolling(2).sum()
Out[58]: 
                       B
2013-01-01 09:00:00  NaN
2013-01-01 09:00:01  1.0
2013-01-01 09:00:02  3.0
2013-01-01 09:00:03  NaN
2013-01-01 09:00:04  NaN

In [59]: dft.rolling(2, min_periods=1).sum()
Out[59]: 
                       B
2013-01-01 09:00:00  0.0
2013-01-01 09:00:01  1.0
2013-01-01 09:00:02  3.0
2013-01-01 09:00:03  2.0
2013-01-01 09:00:04  4.0

Specifying an offset allows a more intuitive specification of the rolling frequency.

In [60]: dft.rolling('2s').sum()
Out[60]: 
                       B
2013-01-01 09:00:00  0.0
2013-01-01 09:00:01  1.0
2013-01-01 09:00:02  3.0
2013-01-01 09:00:03  2.0
2013-01-01 09:00:04  4.0

Using a non-regular, but still monotonic index, rolling with an integer window does not impart any special calculation.

In [61]: 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'))
   ....: 

In [62]: dft
Out[62]: 
                       B
foo                     
2013-01-01 09:00:00  0.0
2013-01-01 09:00:02  1.0
2013-01-01 09:00:03  2.0
2013-01-01 09:00:05  NaN
2013-01-01 09:00:06  4.0

In [63]: dft.rolling(2).sum()
Out[63]: 
                       B
foo                     
2013-01-01 09:00:00  NaN
2013-01-01 09:00:02  1.0
2013-01-01 09:00:03  3.0
2013-01-01 09:00:05  NaN
2013-01-01 09:00:06  NaN

Using the time-specification generates variable windows for this sparse data.

In [64]: dft.rolling('2s').sum()
Out[64]: 
                       B
foo                     
2013-01-01 09:00:00  0.0
2013-01-01 09:00:02  1.0
2013-01-01 09:00:03  3.0
2013-01-01 09:00:05  NaN
2013-01-01 09:00:06  4.0

Furthermore, we now allow an optional on parameter to specify a column (rather than the default of the index) in a DataFrame.

In [65]: dft = dft.reset_index()

In [66]: dft
Out[66]: 
                  foo    B
0 2013-01-01 09:00:00  0.0
1 2013-01-01 09:00:02  1.0
2 2013-01-01 09:00:03  2.0
3 2013-01-01 09:00:05  NaN
4 2013-01-01 09:00:06  4.0

In [67]: dft.rolling('2s', on='foo').sum()
Out[67]: 
                  foo    B
0 2013-01-01 09:00:00  0.0
1 2013-01-01 09:00:02  1.0
2 2013-01-01 09:00:03  3.0
3 2013-01-01 09:00:05  NaN
4 2013-01-01 09:00:06  4.0

Rolling Window Endpoints

New in version 0.20.0.

The inclusion of the interval endpoints in rolling window calculations can be specified with the closed parameter:

closed Description Default for
right close right endpoint time-based windows
left close left endpoint  
both close both endpoints fixed windows
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.

In [68]: 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')])
   ....: 

In [69]: df["right"] = df.rolling('2s', closed='right').x.sum()  # default

In [70]: df["both"] = df.rolling('2s', closed='both').x.sum()

In [71]: df["left"] = df.rolling('2s', closed='left').x.sum()

In [72]: df["neither"] = df.rolling('2s', closed='neither').x.sum()

In [73]: df
Out[73]: 
                     x  right  both  left  neither
2013-01-01 09:00:01  1    1.0   1.0   NaN      NaN
2013-01-01 09:00:02  1    2.0   2.0   1.0      1.0
2013-01-01 09:00:03  1    2.0   3.0   2.0      1.0
2013-01-01 09:00:04  1    2.0   3.0   2.0      1.0
2013-01-01 09:00:06  1    1.0   2.0   1.0      NaN

Currently, this feature is only implemented for time-based windows. For fixed windows, the closed parameter cannot be set and the rolling window will always have both endpoints closed.

Time-aware Rolling vs. Resampling

Using .rolling() with a time-based index is quite similar to 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.

In [74]: ser.rolling(window=5).mean()
Out[74]: 
2000-01-01         NaN
2000-01-02         NaN
2000-01-03         NaN
2000-01-04         NaN
2000-01-05   -0.490679
2000-01-06   -0.598709
2000-01-07   -0.349728
2000-01-08    0.128472
2000-01-09    0.019152
2000-01-10    0.393579
Freq: D, dtype: float64

In [75]: ser.rolling(window=5, center=True).mean()
Out[75]: 
2000-01-01         NaN
2000-01-02         NaN
2000-01-03   -0.490679
2000-01-04   -0.598709
2000-01-05   -0.349728
2000-01-06    0.128472
2000-01-07    0.019152
2000-01-08    0.393579
2000-01-09         NaN
2000-01-10         NaN
Freq: D, dtype: float64

Binary Window Functions

cov() and 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 the next section).

For example:

In [76]: df = pd.DataFrame(np.random.randn(1000, 4),
   ....:                   index=pd.date_range('1/1/2000', periods=1000),
   ....:                   columns=['A', 'B', 'C', 'D'])
   ....: 

In [77]: df = df.cumsum()

In [78]: df2 = df[:20]

In [79]: df2.rolling(window=5).corr(df2['B'])
Out[79]: 
                   A    B         C         D
2000-01-01       NaN  NaN       NaN       NaN
2000-01-02       NaN  NaN       NaN       NaN
2000-01-03       NaN  NaN       NaN       NaN
2000-01-04       NaN  NaN       NaN       NaN
2000-01-05  0.532299  1.0  0.520149  0.585541
2000-01-06  0.117698  1.0 -0.352358  0.473843
2000-01-07 -0.491341  1.0  0.097946  0.474779
...              ...  ...       ...       ...
2000-01-14  0.490346  1.0  0.705476  0.494088
2000-01-15  0.661533  1.0  0.799612  0.529948
2000-01-16  0.668355  1.0  0.766766  0.440176
2000-01-17  0.461535  1.0  0.585742  0.077218
2000-01-18  0.931746  1.0  0.602153  0.231768
2000-01-19  0.975174  1.0 -0.386150 -0.342242
2000-01-20  0.989240  1.0  0.659323 -0.809968

[20 rows x 4 columns]

Computing rolling pairwise covariances and correlations

Warning

Prior to version 0.20.0 if pairwise=True was passed, a Panel would be returned. This will now return a 2-level MultiIndexed DataFrame, see the whatsnew here.

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 covariance section for caveats associated with this method of calculating covariance and correlation matrices.

In [80]: covs = df[['B','C','D']].rolling(window=50).cov(df[['A','B','C']], pairwise=True)

In [81]: covs.loc['2002-09-22':]
Out[81]: 
                      B          C          D
2002-09-22 A  -3.887218  -4.943538  -4.127504
           B  16.729843   5.803418   9.318315
           C   5.803418  16.782740   9.186227
2002-09-23 A  -4.236124  -4.912936  -4.532487
           B  17.513716   6.249705  10.276327
           C   6.249705  15.658931   9.602833
2002-09-24 A  -4.599046  -4.760673  -4.800065
           B  18.202744   6.676929  10.962595
           C   6.676929  14.317074   9.628494
2002-09-25 A  -4.789654  -4.448610  -4.834256
           B  18.735144   6.728264  11.315752
           C   6.728264  12.775589   9.230852
2002-09-26 A  -5.128358  -4.190604  -4.746201
           B  19.471919   6.877523  11.513655
           C   6.877523  11.684676   8.656401
In [82]: correls = df.rolling(window=50).corr()

In [83]: correls.loc['2002-09-22':]
Out[83]: 
                     A         B         C         D
2002-09-22 A  1.000000 -0.562762 -0.714560 -0.725886
           B -0.562762  1.000000  0.346343  0.676614
           C -0.714560  0.346343  1.000000  0.665970
           D -0.725886  0.676614  0.665970  1.000000
2002-09-23 A  1.000000 -0.587448 -0.720526 -0.744120
           B -0.587448  1.000000  0.377389  0.694649
           C -0.720526  0.377389  1.000000  0.686491
...                ...       ...       ...       ...
2002-09-25 B -0.631624  1.000000  0.434895  0.719735
           C -0.710422  0.434895  1.000000  0.710999
           D -0.759679  0.719735  0.710999  1.000000
2002-09-26 A  1.000000 -0.656923 -0.692961 -0.746662
           B -0.656923  1.000000  0.455952  0.726184
           C -0.692961  0.455952  1.000000  0.704801
           D -0.746662  0.726184  0.704801  1.000000

[20 rows x 4 columns]

You can efficiently retrieve the time series of correlations between two columns by reshaping and indexing:

In [84]: correls.unstack(1)[('A', 'C')].plot()
Out[84]: <matplotlib.axes._subplots.AxesSubplot at 0x7f0eaed13090>
_images/rolling_corr_pairwise_ex.png

Aggregation

Once the Rolling, Expanding or EWM objects have been created, several methods are available to perform multiple computations on the data. These operations are similar to the aggregating API, groupby API, and resample API.

In [85]: dfa = pd.DataFrame(np.random.randn(1000, 3),
   ....:                    index=pd.date_range('1/1/2000', periods=1000),
   ....:                    columns=['A', 'B', 'C'])
   ....: 

In [86]: r = dfa.rolling(window=60,min_periods=1)

In [87]: r
Out[87]: Rolling [window=60,min_periods=1,center=False,axis=0]

We can aggregate by passing a function to the entire DataFrame, or select a Series (or multiple Series) via standard __getitem__.

In [88]: r.aggregate(np.sum)
Out[88]: 
                    A         B         C
2000-01-01  -0.035715  2.380444  1.514821
2000-01-02   0.617125  2.575479  1.881391
2000-01-03   0.301457  3.389405  3.515396
2000-01-04  -0.740103  4.590531  3.699959
2000-01-05  -1.905634  4.578209  3.949194
2000-01-06  -1.856484  4.486062  2.832442
2000-01-07  -4.754045  7.342089  1.842772
...               ...       ...       ...
2002-09-20 -15.762234  4.241895  3.856386
2002-09-21 -16.296038  3.717334  1.916118
2002-09-22 -16.845385  5.128299  2.420853
2002-09-23 -16.206238  3.827806  3.580091
2002-09-24 -15.730539  3.400837  5.241771
2002-09-25 -14.061626  6.057178  8.039506
2002-09-26 -14.359736  6.725977  8.401128

[1000 rows x 3 columns]

In [89]: r['A'].aggregate(np.sum)
Out[89]: 
2000-01-01    -0.035715
2000-01-02     0.617125
2000-01-03     0.301457
2000-01-04    -0.740103
2000-01-05    -1.905634
2000-01-06    -1.856484
2000-01-07    -4.754045
                ...    
2002-09-20   -15.762234
2002-09-21   -16.296038
2002-09-22   -16.845385
2002-09-23   -16.206238
2002-09-24   -15.730539
2002-09-25   -14.061626
2002-09-26   -14.359736
Freq: D, Name: A, Length: 1000, dtype: float64

In [90]: r[['A','B']].aggregate(np.sum)
Out[90]: 
                    A         B
2000-01-01  -0.035715  2.380444
2000-01-02   0.617125  2.575479
2000-01-03   0.301457  3.389405
2000-01-04  -0.740103  4.590531
2000-01-05  -1.905634  4.578209
2000-01-06  -1.856484  4.486062
2000-01-07  -4.754045  7.342089
...               ...       ...
2002-09-20 -15.762234  4.241895
2002-09-21 -16.296038  3.717334
2002-09-22 -16.845385  5.128299
2002-09-23 -16.206238  3.827806
2002-09-24 -15.730539  3.400837
2002-09-25 -14.061626  6.057178
2002-09-26 -14.359736  6.725977

[1000 rows x 2 columns]

As you can see, the result of the aggregation will have the selected columns, or all columns if none are selected.

Applying multiple functions

With windowed Series you can also pass a list of functions to do aggregation with, outputting a DataFrame:

In [91]: r['A'].agg([np.sum, np.mean, np.std])
Out[91]: 
                  sum      mean       std
2000-01-01  -0.035715 -0.035715       NaN
2000-01-02   0.617125  0.308562  0.486882
2000-01-03   0.301457  0.100486  0.498412
2000-01-04  -0.740103 -0.185026  0.701197
2000-01-05  -1.905634 -0.381127  0.749023
2000-01-06  -1.856484 -0.309414  0.692593
2000-01-07  -4.754045 -0.679149  1.164760
...               ...       ...       ...
2002-09-20 -15.762234 -0.262704  1.120402
2002-09-21 -16.296038 -0.271601  1.125967
2002-09-22 -16.845385 -0.280756  1.128734
2002-09-23 -16.206238 -0.270104  1.145889
2002-09-24 -15.730539 -0.262176  1.150020
2002-09-25 -14.061626 -0.234360  1.160454
2002-09-26 -14.359736 -0.239329  1.157738

[1000 rows x 3 columns]

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:

In [92]: r.agg([np.sum, np.mean])
Out[92]: 
                    A              ...            C          
                  sum      mean    ...          sum      mean
2000-01-01  -0.035715 -0.035715    ...     1.514821  1.514821
2000-01-02   0.617125  0.308562    ...     1.881391  0.940696
2000-01-03   0.301457  0.100486    ...     3.515396  1.171799
2000-01-04  -0.740103 -0.185026    ...     3.699959  0.924990
2000-01-05  -1.905634 -0.381127    ...     3.949194  0.789839
2000-01-06  -1.856484 -0.309414    ...     2.832442  0.472074
2000-01-07  -4.754045 -0.679149    ...     1.842772  0.263253
...               ...       ...    ...          ...       ...
2002-09-20 -15.762234 -0.262704    ...     3.856386  0.064273
2002-09-21 -16.296038 -0.271601    ...     1.916118  0.031935
2002-09-22 -16.845385 -0.280756    ...     2.420853  0.040348
2002-09-23 -16.206238 -0.270104    ...     3.580091  0.059668
2002-09-24 -15.730539 -0.262176    ...     5.241771  0.087363
2002-09-25 -14.061626 -0.234360    ...     8.039506  0.133992
2002-09-26 -14.359736 -0.239329    ...     8.401128  0.140019

[1000 rows x 6 columns]

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:

In [93]: r.agg({'A' : np.sum,
   ....:        'B' : lambda x: np.std(x, ddof=1)})
   ....: 
Out[93]: 
                    A         B
2000-01-01  -0.035715       NaN
2000-01-02   0.617125  1.545317
2000-01-03   0.301457  1.126426
2000-01-04  -0.740103  0.920414
2000-01-05  -1.905634  0.951037
2000-01-06  -1.856484  0.944907
2000-01-07  -4.754045  1.174335
...               ...       ...
2002-09-20 -15.762234  1.030526
2002-09-21 -16.296038  1.033552
2002-09-22 -16.845385  1.036484
2002-09-23 -16.206238  1.047106
2002-09-24 -15.730539  1.050661
2002-09-25 -14.061626  1.003740
2002-09-26 -14.359736  1.013243

[1000 rows x 2 columns]

The function names can also be strings. In order for a string to be valid it must be implemented on the windowed object

In [94]: r.agg({'A' : 'sum', 'B' : 'std'})
Out[94]: 
                    A         B
2000-01-01  -0.035715       NaN
2000-01-02   0.617125  1.545317
2000-01-03   0.301457  1.126426
2000-01-04  -0.740103  0.920414
2000-01-05  -1.905634  0.951037
2000-01-06  -1.856484  0.944907
2000-01-07  -4.754045  1.174335
...               ...       ...
2002-09-20 -15.762234  1.030526
2002-09-21 -16.296038  1.033552
2002-09-22 -16.845385  1.036484
2002-09-23 -16.206238  1.047106
2002-09-24 -15.730539  1.050661
2002-09-25 -14.061626  1.003740
2002-09-26 -14.359736  1.013243

[1000 rows x 2 columns]

Furthermore you can pass a nested dict to indicate different aggregations on different columns.

In [95]: r.agg({'A' : ['sum','std'], 'B' : ['mean','std'] })
Out[95]: 
                    A                   B          
                  sum       std      mean       std
2000-01-01  -0.035715       NaN  2.380444       NaN
2000-01-02   0.617125  0.486882  1.287740  1.545317
2000-01-03   0.301457  0.498412  1.129802  1.126426
2000-01-04  -0.740103  0.701197  1.147633  0.920414
2000-01-05  -1.905634  0.749023  0.915642  0.951037
2000-01-06  -1.856484  0.692593  0.747677  0.944907
2000-01-07  -4.754045  1.164760  1.048870  1.174335
...               ...       ...       ...       ...
2002-09-20 -15.762234  1.120402  0.070698  1.030526
2002-09-21 -16.296038  1.125967  0.061956  1.033552
2002-09-22 -16.845385  1.128734  0.085472  1.036484
2002-09-23 -16.206238  1.145889  0.063797  1.047106
2002-09-24 -15.730539  1.150020  0.056681  1.050661
2002-09-25 -14.061626  1.160454  0.100953  1.003740
2002-09-26 -14.359736  1.157738  0.112100  1.013243

[1000 rows x 4 columns]

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 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:

In [96]: df.rolling(window=len(df), min_periods=1).mean()[:5]
Out[96]: 
                   A         B         C         D
2000-01-01  0.627214  0.696649  0.107734 -0.776466
2000-01-02 -0.001581  0.396308 -0.644692 -0.250442
2000-01-03 -0.015656 -0.582885 -0.900484 -0.477944
2000-01-04 -0.336948 -1.197418 -0.920933 -0.652247
2000-01-05 -0.674493 -1.314679 -1.107407 -0.865575

In [97]: df.expanding(min_periods=1).mean()[:5]
Out[97]: 
                   A         B         C         D
2000-01-01  0.627214  0.696649  0.107734 -0.776466
2000-01-02 -0.001581  0.396308 -0.644692 -0.250442
2000-01-03 -0.015656 -0.582885 -0.900484 -0.477944
2000-01-04 -0.336948 -1.197418 -0.920933 -0.652247
2000-01-05 -0.674493 -1.314679 -1.107407 -0.865575

These have a similar set of methods to .rolling methods.

Method Summary

Function Description
count() Number of non-null observations
sum() Sum of values
mean() Mean of values
median() Arithmetic median of values
min() Minimum
max() Maximum
std() Unbiased standard deviation
var() Unbiased variance
skew() Unbiased skewness (3rd moment)
kurt() Unbiased kurtosis (4th moment)
quantile() Sample quantile (value at %)
apply() Generic apply
cov() Unbiased covariance (binary)
corr() Correlation (binary)

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).

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:

In [98]: sn = pd.Series([1, 2, np.nan, 3, np.nan, 4])

In [99]: sn
Out[99]: 
0    1.0
1    2.0
2    NaN
3    3.0
4    NaN
5    4.0
dtype: float64

In [100]: sn.rolling(2).max()
Out[100]: 
0    NaN
1    2.0
2    NaN
3    NaN
4    NaN
5    NaN
dtype: float64

In [101]: sn.rolling(2, min_periods=1).max()
Out[101]: 
0    1.0
1    2.0
2    2.0
3    3.0
4    3.0
5    4.0
dtype: float64

In case of expanding functions, this differs from cumsum(), cumprod(), cummax(), and 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 fillna():

In [102]: sn.expanding().sum()
Out[102]: 
0     1.0
1     3.0
2     3.0
3     6.0
4     6.0
5    10.0
dtype: float64

In [103]: sn.cumsum()
Out[103]: 
0     1.0
1     3.0
2     NaN
3     6.0
4     NaN
5    10.0
dtype: float64

In [104]: sn.cumsum().fillna(method='ffill')
Out[104]: 
0     1.0
1     3.0
2     3.0
3     6.0
4     6.0
5    10.0
dtype: float64

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 mean() output for the previous time series dataset:

In [105]: s.plot(style='k--')
Out[105]: <matplotlib.axes._subplots.AxesSubplot at 0x7f0eac6dfd90>

In [106]: s.expanding().mean().plot(style='k')
Out[106]: <matplotlib.axes._subplots.AxesSubplot at 0x7f0eac6dfd90>
_images/expanding_mean_frame.png

Exponentially Weighted Windows

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 EWM object. A number of expanding EW (exponentially weighted) methods are provided:

Function Description
mean() EW moving average
var() EW moving variance
std() EW moving standard deviation
corr() EW moving correlation
cov() EW moving covariance

In general, a weighted moving average is calculated as

\[y_t = \frac{\sum_{i=0}^t w_i x_{t-i}}{\sum_{i=0}^t w_i},\]

where \(x_t\) is the input, \(y_t\) is the result and the \(w_i\) are the weights.

The EW functions support two variants of exponential weights. The default, adjust=True, uses the weights \(w_i = (1 - \alpha)^i\) which gives

\[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

\[\begin{split}y_0 &= x_0 \\ y_t &= (1 - \alpha) y_{t-1} + \alpha x_t,\end{split}\]

which is equivalent to using weights

\[\begin{split}w_i = \begin{cases} \alpha (1 - \alpha)^i & \text{if } i < t \\ (1 - \alpha)^i & \text{if } i = t. \end{cases}\end{split}\]

Note

These equations are sometimes written in terms of \(\alpha' = 1 - \alpha\), e.g.

\[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:

\[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 \(1 - \alpha\) we have

\[\begin{split}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}\end{split}\]

which shows the equivalence of the above two variants for infinite series. When adjust=True we have \(y_0 = x_0\) and from the last representation above we have \(y_t = \alpha x_t + (1 - \alpha) y_{t-1}\), therefore there is an assumption that \(x_0\) is not an ordinary value but rather an exponentially weighted moment of the infinite series up to that point.

One must have \(0 < \alpha \leq 1\), and while since version 0.18.0 it has been possible to pass \(\alpha\) directly, it’s often easier to think about either the span, center of mass (com) or half-life of an EW moment:

\[\begin{split}\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}\end{split}\]

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: \(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.

Here is an example for a univariate time series:

In [107]: s.plot(style='k--')
Out[107]: <matplotlib.axes._subplots.AxesSubplot at 0x7f0ea96b63d0>

In [108]: s.ewm(span=20).mean().plot(style='k')
Out[108]: <matplotlib.axes._subplots.AxesSubplot at 0x7f0ea96b63d0>
_images/ewma_ex.png

EWM 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.

EWM 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

\[\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

\[\frac{(1-\alpha) \cdot 3 + 1 \cdot 5}{(1-\alpha) + 1}.\]

The var(), std(), and 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

\[\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 \(w_i = 1\), this reduces to the usual \(N / (N - 1)\) factor, with \(N = t + 1\).) See Weighted Sample Variance on Wikipedia for further details.

Scroll To Top