Module 11: Time Series Analysis
Learning Objectives
By the end of this module, you will be able to:
Parse dates and create
DatetimeIndexobjectsPerform time-based indexing, slicing, and filtering
Resample time series data at different frequencies
Compute rolling statistics and moving averages
Handle time zones and date offsets
Extract seasonal patterns and trends
Note
Time series analysis is one of the most common use cases for Pandas. From financial markets to IoT sensors to climate data, understanding temporal patterns is essential for data-driven decision making.
DateTime Basics
Creating Timestamps
import pandas as pd
import numpy as np
# From a string
ts = pd.Timestamp("2024-07-01")
print(ts)
# With time
ts = pd.Timestamp("2024-07-01 14:30:00")
print(ts)
# Current timestamp
print(pd.Timestamp.now())
# From components
ts = pd.Timestamp(year=2024, month=7, day=1, hour=14, minute=30)
print(ts)
Parsing dates in DataFrames
df = pd.DataFrame({
"Date": ["2024-01-15", "2024-02-20", "2024-03-10", "2024-04-05"],
"Value": [100, 150, 130, 170],
})
# Convert column to datetime
df["Date"] = pd.to_datetime(df["Date"])
# Set as index
df = df.set_index("Date")
print(df)
Tip
Always parse dates when loading data using parse_dates=True in pd.read_csv() — it saves a conversion step and enables time-based indexing immediately.
Creating Date Ranges
# Daily range
dates = pd.date_range(start="2024-01-01", end="2024-01-10", freq="D")
print(dates)
# Business days
b_dates = pd.date_range(start="2024-01-01", periods=10, freq="B")
print(b_dates)
# Hourly
h_dates = pd.date_range(start="2024-01-01", periods=5, freq="h")
print(h_dates)
# Monthly
m_dates = pd.date_range(start="2024-01-01", periods=12, freq="M")
print(m_dates)
# Custom frequency
custom = pd.date_range(start="2024-01-01", periods=6, freq="2D12h")
print(custom)
Common frequency aliases
Alias |
Description |
|---|---|
|
Calendar day |
|
Business day |
|
Weekly |
|
Month end |
|
Month start |
|
Quarter end |
|
Year end |
|
Hourly |
|
Minutely |
|
Secondly |
Time-Based Indexing
# Generate sample time series
np.random.seed(42)
idx = pd.date_range("2024-01-01", periods=100, freq="D")
ts_df = pd.DataFrame({
"Sales": np.random.randint(100, 500, 100),
"Temperature": np.round(np.random.uniform(15, 35, 100), 1),
}, index=idx)
# Select by year
print(ts_df.loc["2024"])
# Select by month
print(ts_df.loc["2024-03"])
# Select by date range
print(ts_df.loc["2024-01-15":"2024-02-15"])
# Partial string matching
print(ts_df.loc["2024-01"]) # All of January
# Truncate
print(ts_df.truncate(before="2024-03-01", after="2024-03-15"))
Warning
Time-based slicing with .loc[] is inclusive of both start and end — unlike integer-based slicing, which is exclusive of the end.
Resampling
Resampling changes the frequency of time series data.
Downsampling (higher → lower frequency)
# Convert daily to monthly mean
monthly_mean = ts_df["Sales"].resample("M").mean()
print(monthly_mean)
# Multiple aggregations
monthly_stats = ts_df["Sales"].resample("M").agg(["sum", "mean", "std", "min", "max"])
print(monthly_stats.head())
Upsampling (lower → higher frequency)
# Create weekly data
weekly = ts_df.resample("W").mean()
# Upsample back to daily via interpolation
daily_from_weekly = weekly.resample("D").interpolate(method="linear")
print(daily_from_weekly.head())
Custom resampling functions
def first_last(series):
return pd.Series({
"first": series.iloc[0],
"last": series.iloc[-1],
"change": series.iloc[-1] - series.iloc[0],
})
print(ts_df["Sales"].resample("M").apply(first_last).head())
Tip
The .resample() method is essentially a time-based .groupby(). Use it with the same aggregation functions you would use for grouping.
Rolling Statistics and Moving Averages
Simple moving average
# 7-day rolling mean
ts_df["Sales_SMA_7"] = ts_df["Sales"].rolling(window=7).mean()
# 30-day rolling mean
ts_df["Sales_SMA_30"] = ts_df["Sales"].rolling(window=30).mean()
Rolling with min_periods
# Require at least 5 observations
ts_df["Sales_Rolling_7"] = ts_df["Sales"].rolling(window=7, min_periods=5).mean()
Other rolling statistics
# Rolling standard deviation (volatility)
ts_df["Sales_Volatility"] = ts_df["Sales"].rolling(window=7).std()
# Rolling max/min
ts_df["Sales_Max_7"] = ts_df["Sales"].rolling(window=7).max()
ts_df["Sales_Min_7"] = ts_df["Sales"].rolling(window=7).min()
# Rolling correlation
ts_df["Rolling_Corr"] = (
ts_df["Sales"]
.rolling(window=14)
.corr(ts_df["Temperature"])
)
Expanding windows
# Cumulative statistics (expanding window)
ts_df["Sales_Cumsum"] = ts_df["Sales"].expanding().sum()
ts_df["Sales_Cummean"] = ts_df["Sales"].expanding().mean()
ts_df["Sales_Cummax"] = ts_df["Sales"].expanding().max()
Note
An expanding window starts with the first observation and grows to include all subsequent data. It is useful for running totals and cumulative averages.
Exponentially Weighted Moving Average (EWMA)
EWMA gives more weight to recent observations.
# EWMA with span=7 (equivalent to 7-day SMA)
ts_df["Sales_EWMA_7"] = ts_df["Sales"].ewm(span=7, adjust=False).mean()
# EWMA with alpha parameter
ts_df["Sales_EWMA_alpha"] = ts_df["Sales"].ewm(alpha=0.3, adjust=False).mean()
Time Zones
# Create time-zone naive timestamp
ts_naive = pd.Timestamp("2024-07-01 12:00:00")
# Localize to a timezone
ts_utc = ts_naive.tz_localize("UTC")
print(ts_utc)
# Convert to another timezone
ts_ny = ts_utc.tz_convert("America/New_York")
print(ts_ny)
# DataFrame with timezone
tz_df = pd.DataFrame({
"Timestamp": pd.date_range("2024-01-01", periods=5, freq="h", tz="UTC"),
"Value": np.random.randn(5),
})
print(tz_df)
# Convert DataFrame index to another timezone
tz_df.index = tz_df["Timestamp"]
tz_df_est = tz_df.tz_convert("US/Eastern")
print(tz_df_est)
Shift and Lag
# Shift values (lag)
ts_df["Sales_Lag_1"] = ts_df["Sales"].shift(1) # Previous day
ts_df["Sales_Lag_7"] = ts_df["Sales"].shift(7) # Same day last week
# Lead (negative shift)
ts_df["Sales_Lead_1"] = ts_df["Sales"].shift(-1) # Next day
# Day-over-day change
ts_df["Sales_Diff"] = ts_df["Sales"].diff()
ts_df["Sales_Diff_Pct"] = ts_df["Sales"].pct_change() * 100
# Compare to same period
ts_df["Sales_Lag_1_Return"] = (ts_df["Sales"] - ts_df["Sales"].shift(1)) / ts_df["Sales"].shift(1) * 100
Seasonal Analysis
Extracting date components
ts_df["Year"] = ts_df.index.year
ts_df["Month"] = ts_df.index.month
ts_df["Day"] = ts_df.index.day
ts_df["DayOfWeek"] = ts_df.index.dayofweek # Monday=0, Sunday=6
ts_df["DayName"] = ts_df.index.day_name()
ts_df["Quarter"] = ts_df.index.quarter
ts_df["WeekOfYear"] = ts_df.index.isocalendar().week
ts_df["IsWeekend"] = ts_df.index.dayofweek >= 5
Seasonal decomposition
from statsmodels.tsa.seasonal import seasonal_decompose
# Requires statsmodels: pip install statsmodels
decomposition = seasonal_decompose(
ts_df["Sales"],
model="additive",
period=7, # Weekly seasonality
)
ts_df["Trend"] = decomposition.trend
ts_df["Seasonal"] = decomposition.seasonal
ts_df["Residual"] = decomposition.resid
Group by seasonal period
# Average sales by day of week
day_pattern = ts_df.groupby(ts_df.index.dayofweek)["Sales"].agg(["mean", "std", "count"])
day_pattern.index = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
print(day_pattern)
# Monthly seasonal pattern
monthly_pattern = ts_df.groupby(ts_df.index.month)["Sales"].mean()
print(monthly_pattern)
Practical Example: Climate Data Analysis
# Generate realistic temperature data
np.random.seed(42)
date_range = pd.date_range("2020-01-01", "2024-12-31", freq="D")
# Simulate temperature with annual seasonality and noise
days = np.arange(len(date_range))
temperature = (
20 # Base
+ 10 * np.sin(2 * np.pi * days / 365 - 1.5) # Seasonal cycle
+ np.random.normal(0, 3, len(date_range)) # Random noise
)
climate = pd.DataFrame({
"Temperature": temperature,
"Rainfall": np.random.exponential(5, len(date_range)),
}, index=date_range)
# Annual trend
annual = climate.resample("A")["Temperature"].mean()
print(annual)
# 30-day rolling average
climate["Temp_SMA_30"] = climate["Temperature"].rolling(30).mean()
# Seasonal comparison
climate["Month"] = climate.index.month
seasonal = climate.groupby("Month")["Temperature"].agg(["mean", "std", "min", "max"])
print(seasonal)
# Extract summer months (June-August)
summer = climate[climate.index.month.isin([6, 7, 8])]
print(f"Summer mean temp: {summer['Temperature'].mean():.1f}°C")
# Year-over-year comparison
climate["Year"] = climate.index.year
yoy = climate.groupby("Year")["Temperature"].agg(["mean", "min", "max"])
print(yoy)
Tip
When analysing seasonal data, always check for the number of observations per period. Uneven sampling can introduce bias in seasonal averages.
Performance Considerations
# Use PeriodIndex for monthly analysis (more memory efficient)
monthly_idx = pd.period_range("2024-01", periods=24, freq="M")
print(monthly_idx)
# Downsampling large datasets with groupby + Grouper
large_df = pd.DataFrame({
"value": np.random.randn(1_000_000),
}, index=pd.date_range("2020-01-01", periods=1_000_000, freq="min"))
# Fast resample via Grouper
result = large_df.groupby(pd.Grouper(freq="h"))["value"].mean()
print(f"Downsampled from {len(large_df)} to {len(result)} rows")
Summary
Use
pd.to_datetime()to parse date columns andpd.date_range()to generate date sequencesTime-based indexing with
.loc[]supports partial string matching.resample()changes frequency with aggregation (downsampling) or interpolation (upsampling).rolling()computes moving windows for averages, standard deviations, and correlations.expanding()computes cumulative statistics.ewm()provides exponentially weighted moving averagesTime zones can be localised and converted with
tz_localize()andtz_convert().shift()and.diff()create lagged and differenced series for time series modelling
Exercises
Using this dataset:
import pandas as pd
import numpy as np
np.random.seed(42)
idx = pd.date_range("2024-01-01", periods=200, freq="D")
df = pd.DataFrame({
"Sales": np.random.randint(200, 800, 200),
"Visitors": np.random.randint(50, 300, 200),
"Holiday": np.random.choice([0, 1], 200, p=[0.8, 0.2]),
}, index=idx)
Resample the data to weekly frequency, computing the mean for Sales and sum for Visitors
Compute a 7-day rolling average for Sales and add it as a new column
Calculate the day-over-day percentage change for Sales
Extract the day of week, month, and quarter into separate columns
Create a holiday indicator analysis — compare average Sales on holidays vs non-holidays
Compute the expanding cumulative sum of Visitors
Use
.shift()to create a column showing Sales from 7 days ago, then compute the week-over-week change