TExcelTAD
Home › Data Science › DS Time Series Basics

DS Time Series Basics

A time series is a sequence of measurements in time order: daily rides, hourly temperatures, monthly revenue. Time adds structure that ordinary tables don't have — trends, weekly or yearly cycles, and the fact that today usually resembles yesterday. pandas has excellent tools for it, built around a DatetimeIndex.

A date index

Set the date column as the index, and pandas can select by date strings and resample by calendar periods:

python · try it yourself
import numpy as np
import pandas as pd

rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
                      "humidity": humidity, "weekend": weekend, "rides": rides})

ts = bikes.set_index("date")["rides"]
print(ts["2024-05-01":"2024-05-05"])
print()
print("April total:", ts["2024-04"].sum(), "| May total:", ts["2024-05"].sum())
print()
print(ts.resample("MS").agg(["sum", "mean"]).round(1))
date
2024-05-01    266
2024-05-02    496
2024-05-03    268
2024-05-04    357
2024-05-05    378
Name: rides, dtype: int32

April total: 11079 | May total: 10247

              sum   mean
date
2024-04-01  11079  369.3
2024-05-01  10247  341.6

resample("MS") groups by month (labelled at month start), "W" by week, "D" by day. May was quieter than April, by about 28 rides per day. Both months have 30 days in our data, so the totals are comparable here; when periods have different lengths (or missing days), compare the means instead.

Smoothing with rolling windows

Daily data is noisy. A rolling mean averages each day with its neighbours and reveals the slower movement underneath. A 7-day window also removes the weekly cycle, since every window contains exactly one weekend:

python · try it yourself
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
                      "humidity": humidity, "weekend": weekend, "rides": rides})

ts = bikes.set_index("date")["rides"]
smooth = ts.rolling(7, center=True).mean()

fig, ax = plt.subplots(figsize=(9, 3.5))
ax.plot(ts.index, ts, color="lightgrey", label="daily")
ax.plot(smooth.index, smooth, color="#ff6f00", lw=2, label="7-day centred mean")
ax.set_ylabel("rides")
ax.legend()
plt.show()

print(smooth.dropna().round(1).iloc[::7])
date
2024-04-04    404.3
2024-04-11    390.7
2024-04-18    351.3
2024-04-25    356.6
2024-05-02    332.0
2024-05-09    315.1
2024-05-16    378.0
2024-05-23    343.4
Name: rides, dtype: float64

The first and last three days have no full window, so the centred rolling mean is NaN there. The smoothed line wanders between roughly 300 and 410 rides, following warm and cool spells rather than a steady trend.

Lags and autocorrelation

A lag is the series shifted in time: shift(1) gives yesterday's value on today's row. The correlation between a series and its own lags is its autocorrelation. Strong autocorrelation means yesterday is a good guide to today:

python · try it yourself
import numpy as np
import pandas as pd

rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
                      "humidity": humidity, "weekend": weekend, "rides": rides})

ts = bikes.set_index("date")["rides"]
frame = pd.DataFrame({"rides": ts, "yesterday": ts.shift(1), "last_week": ts.shift(7)})
print(frame.iloc[6:10])
print()
for lag in [1, 2, 7]:
    print(f"autocorrelation at lag {lag}: {ts.autocorr(lag):.2f}")
            rides  yesterday  last_week
date
2024-04-07    497      523.0        NaN
2024-04-08    428      497.0      414.0
2024-04-09    209      428.0      298.0
2024-04-10    368      209.0      439.0

autocorrelation at lag 1: 0.15
autocorrelation at lag 2: 0.10
autocorrelation at lag 7: 0.10

Our rides have little autocorrelation, because the simulated weather was drawn independently each day. Real weather comes in spells, so real rentals usually show clear lag-1 autocorrelation — and a weekly cycle would show up at lag 7.

Naive forecasts as baselines

The simplest forecasts use the past directly:

  • Naive: tomorrow = today.
  • Seasonal naive: tomorrow = same weekday last week.
  • Moving average: tomorrow = mean of the last 7 days.

Any serious model must beat them. Let's compare them with our weather regression on the last 14 days:

python · try it yourself
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf

rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
                      "humidity": humidity, "weekend": weekend, "rides": rides})

bikes["naive"] = bikes["rides"].shift(1)
bikes["seasonal_naive"] = bikes["rides"].shift(7)
bikes["moving_avg"] = bikes["rides"].shift(1).rolling(7).mean()

train, test = bikes.iloc[:46], bikes.iloc[46:]
model = smf.ols("rides ~ temp_c + rain_mm + weekend", data=train).fit()
test = test.assign(regression=model.predict(test))

for col in ["naive", "seasonal_naive", "moving_avg", "regression"]:
    mae = (test["rides"] - test[col]).abs().mean()
    print(f"{col:15} MAE = {mae:6.1f} rides")
naive           MAE =  110.2 rides
seasonal_naive  MAE =  116.9 rides
moving_avg      MAE =  102.1 rides
regression      MAE =   20.0 rides

The weather regression wins by a wide margin, because it uses the information that actually drives rides — the weather forecast. In practice, a forecast is only as good as its inputs: this model needs tomorrow's temperature and rain forecasts, which have their own errors.

Tip: For data with strong trends and seasonality, dedicated time-series models (exponential smoothing, ARIMA — both in statsmodels.tsa) go further. They all start from the ideas in this lesson: index by time, smooth, look at lags, and beat the naive baselines.

Test yourself

What does ts.resample("W").mean() compute?

  1. A 7-day rolling mean
  2. The mean for each calendar week
  3. The weekly autocorrelation
  4. The mean of every 7th value

What does ts.shift(7) put on each row?

  1. The value 7 days later
  2. The value from 7 days earlier
  3. The 7-day mean
  4. The 7th row

Why compare a forecasting model with naive forecasts?

  1. Naive forecasts are always best
  2. To check that the model adds value beyond simply repeating the past
  3. Because statsmodels requires it
  4. To make the plot nicer