Skip to Content
Course content

56: Time Series Analysis with forecast Package

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've seen this mistake more times than I can count: a developer gets a dataset of monthly sales or server loads and treats it like a standard regression problem. They throw it into a linear model, maybe add a trend line, and call it a "forecast." The problem is that time series data violates the most fundamental assumption of linear regression—that your observations are independent. In a time series, today's value is almost always heavily dependent on yesterday's value. If you ignore that autocorrelation, your confidence intervals are lies and your predictions will likely drift into uselessness the moment the trend shifts.

The temptation of the linear trend

Let's say we're tracking monthly electricity demand for a city. If you take the naive approach, you might just create a sequence of numbers for time and run a simple lm(). It looks great on a plot because the line cuts right through the middle of the data, but it completely ignores the "heartbeat" of the data—the seasonality. Electricity demand spikes every July and December; a linear model just sees this as "noise" or "error" around the trend line. When you use this to predict next year, you get a flat line that misses every peak and valley, leaving the grid operators completely unprepared for the summer heatwave.

# The naive way: Treating time as a simple independent variable
demand_data <- c(120, 130, 150, 170, 200, 210, 250, 240, 200, 160, 140, 130)
time_index <- 1:12
naive_model <- lm(demand_data ~ time_index)
# This ignores seasonality and autocorrelation entirely.

Letting auto.arima handle the heavy lifting

This is where the forecast package becomes your best friend. Instead of trying to manually figure out how many times to difference the data to make it stationary, or guessing which seasonal lag to use, we use auto.arima(). I prefer this approach because it systematically tests different combinations of p, d, and q parameters (the ARIMA components) and picks the one that minimizes information loss. It doesn't just look at the trend; it looks at the relationship between a point and its previous values, and its values from the same month last year.

First, you have to wrap your data in a ts() object. R needs to know the frequency—for monthly data, that's 12. Once you've done that, auto.arima() handles the math, and the forecast() function projects that logic into the future, giving you a range of probabilities rather than a single, overly-optimistic line.

library(forecast)

# Convert to a time series object with monthly frequency
demand_ts <- ts(demand_data, frequency = 12)

# Let the package find the best ARIMA parameters automatically
fit <- auto.arima(demand_ts)

# Forecast the next 6 months
future_demand <- forecast(fit, h = 6)
plot(future_demand)

Where the automation breaks

Now, I'll give you a warning: auto.arima() is powerful, but it's not a magic wand. It assumes the underlying patterns of the past will persist into the future. If your city suddenly installs a massive array of solar panels that fundamentally changes the demand curve, the model will keep predicting based on the old "heartbeat" until you feed it enough new data to override the old patterns. Also, be careful with very short datasets. If you only have six months of data and tell R the frequency is 12, the model will struggle to find a seasonal pattern because it hasn't even seen a full cycle yet. In those cases, you're better off sticking to a simple drift model or a naive seasonal forecast until you have more history to work with.




📋 Practical Task

Forecasting Quarterly Retail Revenue

You have been handed a vector representing the quarterly revenue (in millions) for a retail store over the last 3 years: revenue_vec <- c(15, 22, 28, 45, 18, 25, 31, 48, 21, 28, 35, 52).

Your task is to:

  • Convert this vector into a time series object with a quarterly frequency.
  • Use the forecast package to automatically determine the best ARIMA model for this data.
  • Generate a forecast for the next 4 quarters (one full year).
  • Print the forecast object to the console and identify the "Point Forecast" for the 4th quarter of the projection.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.