v Rolling Time Window - Machine Learning

Rolling Time Window

Preliminaries

# Load library
import pandas as pd

Create Date Data

# Create datetimes
time_index = pd.date_range('01/01/2010', periods=5, freq='M')

# Create data frame, set index
df = pd.DataFrame(index=time_index)

# Create feature
df['Stock_Price'] = [1,2,3,4,5]

Create A Rolling Time Window Of Two Rows

# Calculate rolling mean
df.rolling(window=2).mean()
Stock_Price
2010-01-31 NaN
2010-02-28 1.5
2010-03-31 2.5
2010-04-30 3.5
2010-05-31 4.5
# Identify max value in rolling time window
df.rolling(window=2).max()
Stock_Price
2010-01-31 NaN
2010-02-28 2.0
2010-03-31 3.0
2010-04-30 4.0
2010-05-31 5.0