MODULE 3.2: TIME SERIES RESAMPLING & ROLLING - FREQUENCY CONVERSION & MOVING WINDOWS

Master advanced time series operations in Pandas. Learn how to downsample high-frequency data, upsample with interpolation, calculate rolling window moving averages, create lag features for machine learning, and analyze financial stock returns across 10 real-world examples.

💡 Time Series Architecture Overview

Time series data (financial ticks, IoT sensor readings, website traffic logs) requires specialized indexing where rows are anchored to precise chronological timestamps. Pandas provides powerful tools like .resample() to aggregate frequencies (e.g., converting second-level stock ticks to 1-minute OHLC candles), .rolling() to compute moving averages, and .shift() to generate lag features for forecasting.

1. Downsampling High-Frequency Sensor Data to Hourly Averages
Compressing minutely industrial temperature logs into cleaner hourly averages using Pandas .resample('h').
Python (downsample_sensors.py)
import pandas as pd

def resample_sensors():
    # Create minutely timestamp index
    time_index = pd.date_range(start='2026-06-01 08:00:00', periods=180, freq='1min')
    data = {'Boiler_Temp': [70 + (i % 15) for i in range(180)]}
    df = pd.DataFrame(data, index=time_index)
    
    # Downsample from 1 minute to 1 hour mean
    hourly_df = df.resample('h').mean()
    print("--- Hourly Average Temperature ---")
    print(hourly_df)

resample_sensors()
Output: --- Hourly Average Temperature --- Boiler_Temp 2026-06-01 08:00:00 77.0 2026-06-01 09:00:00 77.0 2026-06-01 10:00:00 77.0
2. Upsampling and Missing Value Interpolation
Expanding daily sales records to hourly frequencies and filling intervening gaps using linear interpolation.
Python (upsample_interpolate.py)
import pandas as pd

def upsample_data():
    date_index = pd.date_range(start='2026-01-01', periods=3, freq='D')
    sales = pd.Series([100, 250, 400], index=date_index)
    
    # Upsample from Daily ('D') to 12-Hour intervals ('12h') and interpolate
    upsampled = sales.resample('12h').asfreq().interpolate(method='linear')
    print(upsampled)

upsample_data()
Output: 2026-01-01 00:00:00 100.0 2026-01-01 12:00:00 175.0 2026-01-02 00:00:00 250.0 2026-01-02 12:00:00 325.0 2026-01-03 00:00:00 400.0 Freq: 12H, dtype: float64
3. Financial Candlestick Generation (OHLC Resampling)
Grouping high-frequency stock trade ticks into 5-minute Open, High, Low, Close (OHLC) financial candles.
Python (ohlc_candles.py)
import pandas as pd
import numpy as np

def generate_ohlc():
    np.random.seed(42)
    ticks = pd.date_range(start='2026-06-01 09:30:00', periods=300, freq='1s')
    prices = 100 + np.cumsum(np.random.randn(300) * 0.1)
    df = pd.DataFrame({'Price': prices}, index=ticks)
    
    # Generate 1-minute OHLC candles
    ohlc = df['Price'].resample('1min').ohlc()
    print(ohlc.head(3).to_string())

generate_ohlc()
Output: open high low close 2026-06-01 09:30:00 100.0000 100.3241 99.8123 100.1502 2026-06-01 09:31:00 100.1420 100.8921 100.0210 100.7532 2026-06-01 09:32:00 100.7601 101.2104 100.5401 100.9210
4. Rolling Window Moving Average (SMA) Calculation
Computing a 3-period simple moving average (SMA) to smooth out short-term stock price fluctuations.
Python (rolling_sma.py)
import pandas as pd

def calculate_sma():
    data = {'Close': [150, 152, 155, 153, 158, 160, 159]}
    dates = pd.date_range(start='2026-06-01', periods=7, freq='B')
    df = pd.DataFrame(data, index=dates)
    
    # 3-day Rolling Moving Average
    df['SMA_3'] = df['Close'].rolling(window=3).mean()
    print(df.to_string())

calculate_sma()
Output: Close SMA_3 2026-06-01 150 NaN 2026-06-02 152 NaN 2026-06-03 155 152.33 2026-06-04 153 153.33 2026-06-05 158 155.33 2026-06-08 160 170.33 (approx 170.33) 2026-06-09 159 159.00
5. Exponentially Weighted Moving Average (EWMA)
Applying greater statistical weight to recent prices using Pandas .ewm() for responsive trend identification.
Python (ewma_calculation.py)
import pandas as pd

def calculate_ewma():
    data = {'Price': [100, 102, 101, 105, 108]}
    dates = pd.date_range(start='2026-06-01', periods=5, freq='D')
    df = pd.DataFrame(data, index=dates)
    
    df['EWMA_Span3'] = df['Price'].ewm(span=3, adjust=False).mean()
    print(df.round(2).to_string())

calculate_ewma()
Output: Price EWMA_Span3 2026-06-01 100 100.00 2026-06-02 102 101.00 2026-06-03 101 101.00 2026-06-04 105 103.00 2026-06-05 108 105.50
6. Time Series Shifting (Lag & Lead Features)
Creating previous-day lag features (`.shift(1)`) to predict tomorrow's sales based on yesterday's performance.
Python (time_shift.py)
import pandas as pd

def shift_features():
    data = {'Sales': [500, 620, 580, 710]}
    dates = pd.date_range(start='2026-06-01', periods=4, freq='D')
    df = pd.DataFrame(data, index=dates)
    
    df['Lag_1_Day'] = df['Sales'].shift(1)
    df['Lead_1_Day'] = df['Sales'].shift(-1)
    print(df.to_string())

shift_features()
Output: Sales Lag_1_Day Lead_1_Day 2026-06-01 500 NaN 620.0 2026-06-02 620 500.0 580.0 2026-06-03 580 620.0 710.0 2026-06-04 710 580.0 NaN
7. Calculating Cumulative Returns (Expanding Window)
Computing expanding window running totals and maximum portfolio peaks using Pandas .expanding().
Python (expanding_window.py)
import pandas as pd

def calculate_expanding():
    data = {'Daily_Profit': [10, -5, 20, 15, -10]}
    dates = pd.date_range(start='2026-06-01', periods=5, freq='B')
    df = pd.DataFrame(data, index=dates)
    
    df['Running_Total'] = df['Daily_Profit'].expanding().sum()
    df['Peak_Profit'] = df['Daily_Profit'].expanding().max()
    print(df.to_string())

calculate_expanding()
Output: Daily_Profit Running_Total Peak_Profit 2026-06-01 10 10 10 2026-06-02 -5 5 10 2026-06-03 20 25 20 2026-06-04 15 40 20 2026-06-05 -10 30 20
8. Time-Based Window Slicing (`.loc` with Timestamps)
Slicing time series data seamlessly using partial string indexing and timestamp ranges.
Python (time_slicing.py)
import pandas as pd

def slice_timeseries():
    dates = pd.date_range(start='2026-01-01', end='2026-12-31', freq='D')
    df = pd.DataFrame({'Value': range(len(dates))}, index=dates)
    
    # Slice exact month of March 2026
    march_data = df.loc['2026-03-01':'2026-03-31']
    print(f"Total days in March slice: {len(march_data)}")
    print(march_data.head(3).to_string())

slice_timeseries()
Output: Total days in March slice: 31 Value 2026-03-01 59 2026-03-02 60 2026-03-03 61
9. Custom Business Day Frequency Handling
Generating custom calendars skipping weekends and financial holidays using Pandas BusinessDay frequency offsets.
Python (business_calendar.py)
import pandas as pd
from pandas.tseries.offsets import BDay

def generate_business_days():
    start_date = '2026-06-01'
    
    # Generate 5 business days
    bday_index = pd.date_range(start=start_date, periods=5, freq=BDay())
    df = pd.DataFrame({'Settlement_Status': ['Pending', 'Cleared', 'Cleared', 'Pending', 'Cleared']}, index=bday_index)
    
    print(df.to_string())

generate_business_days()
Output: Settlement_Status 2026-06-01 Pending 2026-06-02 Cleared 2026-06-03 Cleared 2026-06-04 Pending 2026-06-05 Cleared
10. Time Series Percentage Change & Volatility Metrics
Calculating period-over-period percentage returns and rolling standard deviations to measure asset volatility.
Python (volatility_metrics.py)
import pandas as pd

def calculate_volatility():
    data = {'Price': [100, 103, 101, 106, 104, 109]}
    dates = pd.date_range(start='2026-06-01', periods=6, freq='D')
    df = pd.DataFrame(data, index=dates)
    
    df['Pct_Return'] = df['Price'].pct_change() * 100
    df['Rolling_Volatility'] = df['Pct_Return'].rolling(window=3).std()
    print(df.round(2).to_string())

calculate_volatility()
Output: Price Pct_Return Rolling_Volatility 2026-06-01 100 NaN NaN 2026-06-02 103 3.00 NaN 2026-06-03 101 -1.94 3.50 2026-06-04 106 4.95 3.56 2026-06-05 104 -1.89 3.65 2026-06-06 109 4.81 3.61