Rolling Window Calculations On A Pandas Series

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
# rolling computations on a pandas data series
import pandas as pds

# A Python function definition
# that decides whether an account should get locked
def donotlock(collection):
    c1 = collection.astype(bool);
    falseCount = 0;

    for status in c1:
        if status is False:
            falseCount = falseCount + 1;

 

    if falseCount >= 3:
        return False;
    else:
        return True;

loginStatus    = [True, True, True, False, True, False, False, False];

sr             = pds.Series(data = loginStatus);

# Define a policy that an account will be locked after
# three consecutive login failures
tolerance     = 3;
window         = sr.rolling(window=tolerance);

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
# the moving average of a stock price
# over 30 ticks
import pandas as pds

# Price data as a Python list
price = [67.0, 67.1, 67.6, 67.0, 67.75, 68.0,
         67.8, 68.2, 67.5, 67.6, 67.4, 67.0,
         66.9, 67.2, 67.5, 67.0, 66.8, 66.7,
         67.0, 67.25, 67.40, 67.20, 67.30, 67.70,
         68.1, 68.5, 68.2, 67.75, 67.9, 67.6];

# Create a pandas series        
sr = pds.Series(data = price);

# Calculate the moving average
tickCount = 14;
print("Moving averages:");
print(sr.rolling(window=tickCount).mean());

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

 


Copyright 2023 © pythontic.com