Overview:
- Often it is required to perform calculations on the subsets of data of specific length continuously. For example, intra-day stock traders calculate various technical indicators using the past 14 minutes data continously. These subsets of the data are called as rolling windows.
- The Rolling class in pandas implements a rolling window for the Series and DataFrame classes. A call to the method rolling() on a series instance returns a Rolling object.
- A Rolling instance supports several standard computations like average, standard deviation and others. A pandas Rolling instance also supports the apply() method through which a function performing custom computations can be called.
Example 1 - Performing a custom rolling window calculation on a pandas series:
# Example Python program that peforms # A Python function definition for status in c1: if falseCount >= 3: loginStatus = [True, True, True, False, True, False, False, False]; sr = pds.Series(data = loginStatus); # Define a policy that an account will be locked after print(window.apply(func=donotlock, raw=False).astype(bool)); |
Output:
0 True 1 True 2 True 3 True 4 True 5 True 6 True 7 False dtype: bool |
Example 2 - Performing a standard rolling window calculation on a pandas Series
# Example Python program that calculates # Price data as a Python list # Create a pandas series # Calculate the moving average |
Output:
Moving averages: 0 NaN 1 NaN 2 NaN 3 NaN 4 NaN 5 NaN 6 NaN 7 NaN 8 NaN 9 NaN 10 NaN 11 NaN 12 NaN 13 67.432143 14 67.467857 15 67.460714 16 67.403571 17 67.382143 18 67.328571 19 67.275000 20 67.246429 21 67.175000 22 67.160714 23 67.167857 24 67.217857 25 67.325000 26 67.417857 27 67.457143 28 67.485714 29 67.528571 dtype: float64 |