ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Pandas Tutorial• 7 min read

Time Series Analysis & DatetimeIndex

pd.to_datetime, date parsing, dt accessor, resampling, and rolling windows

Pandas was originally created at AQR Capital Management for quantitative financial time series. It provides exceptional datetime manipulation capabilities.

Working with Datetime in Pandas

pd.to_datetime(col): Converts strings and timestamps into robust pd.Timestamp objects.

The .dt accessor: Extracts date components (.dt.year, .dt.day_name(), .dt.hour).

Setting a DatetimeIndex: When dates are the DataFrame index, powerful date slicing (df["2024-01":"2024-03"]) is enabled.

df.resample("ME").mean(): Frequency conversion (e.g. daily to monthly end), like a groupby for time intervals.

df["price"].rolling(window=7).mean(): Computes moving averages over time windows.

Calculating 7-Day Moving Average
import pandas as pd
import numpy as np

# Create daily date range for January 2024
dates = pd.date_range(start="2024-01-01", periods=10, freq="D")
df = pd.DataFrame({
    "price": [100, 102, 105, 103, 108, 112, 110, 115, 118, 120]
}, index=dates)

# Compute 3-day rolling moving average
df["3_day_ma"] = df["price"].rolling(window=3).mean()
print("Stock prices with Moving Average:
", df)
Rolling windows compute moving averages crucial for smoothing financial time series.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which method frequency-converts a time-series DataFrame (e.g. from daily transactions to monthly sums)?