Reading history

Time Series Forecasting with Machine Learning in Python

6 min read 1 views

Learn time series forecasting with machine learning in Python: lag and rolling features, time-ordered splits, baselines and TimeSeriesSplit.

A time series is a list of values in time order: daily sales, hourly temperature, monthly electricity bills. To forecast it with an ordinary machine learning model, you turn the past into columns. “Sales yesterday” and “sales on the same day last week” become features, and tomorrow’s sales becomes the target. The one rule you must never break is to train only on the past and test only on the future.

In this lesson you will learn

  • Building lag and rolling-mean features with pandas
  • Splitting time data without shuffling
  • Comparing a model against simple baseline forecasts
  • Why tree models struggle with trends
  • Cross-validation for time series with TimeSeriesSplit

You should know linear regression, MAE and pandas DataFrames.

Turning the Past Into Features

The example data is 120 days of ice-cream sales. Sales rise slowly over time, jump by about 40 at weekends, and have some random noise.

import numpy as np
import pandas as pd

rng = np.random.default_rng(7)
days = pd.date_range("2026-01-01", periods=120, freq="D")
# Daily ice-cream sales: rising trend + weekend boost + noise
trend = np.linspace(100, 160, 120)
weekend = np.where(days.dayofweek >= 5, 40, 0)
sales = (trend + weekend + rng.normal(0, 8, 120)).round()
df = pd.DataFrame({"sales": sales}, index=days)

df["lag_1"] = df["sales"].shift(1)        # yesterday
df["lag_7"] = df["sales"].shift(7)        # same day last week
df["mean_7"] = df["sales"].shift(1).rolling(7).mean()   # average of the previous 7 days
df["weekend"] = (df.index.dayofweek >= 5).astype(int)
df = df.dropna()
print(df.head(3).round(1))
print("Rows left after dropping the first 7 days:", len(df))

Output

            sales  lag_1  lag_7  mean_7  weekend
2026-01-08  114.0  104.0  100.0   110.4        0
2026-01-09  100.0  114.0  103.0   112.4        0
2026-01-10  140.0  100.0  139.0   112.0        1
Rows left after dropping the first 7 days: 113
  • shift(1) moves every value down one row, so each day sees yesterday’s sales. shift(7) gives the same weekday last week.
  • shift(1).rolling(7).mean() is the average of the previous seven days. The shift(1) comes first so the average never includes today’s value, which would leak the answer.
  • weekend is 1 on Saturday and Sunday. 10 January 2026 is a Saturday, and its sales of 140 show the weekend boost.
  • The first seven days have no week-old value, so dropna() removes them, leaving 113 rows.

Training and Testing in Time Order

import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import TimeSeriesSplit, cross_val_score

rng = np.random.default_rng(7)
days = pd.date_range("2026-01-01", periods=120, freq="D")
sales = np.linspace(100, 160, 120) + np.where(days.dayofweek >= 5, 40, 0) + rng.normal(0, 8, 120)
df = pd.DataFrame({"sales": sales.round()}, index=days)
df["lag_1"] = df["sales"].shift(1)
df["lag_7"] = df["sales"].shift(7)
df["mean_7"] = df["sales"].shift(1).rolling(7).mean()
df["weekend"] = (df.index.dayofweek >= 5).astype(int)
df = df.dropna()
X, y = df[["lag_1", "lag_7", "mean_7", "weekend"]], df["sales"]

# Train on everything except the last 28 days; never shuffle time data
X_train, X_test, y_train, y_test = X[:-28], X[-28:], y[:-28], y[-28:]
print("Test period:", X_test.index[0].date(), "to", X_test.index[-1].date())

print("\nMean absolute error on the last 28 days:")
print("  'Same as yesterday':", round(mean_absolute_error(y_test, X_test["lag_1"]), 1))
print("  'Same as last week':", round(mean_absolute_error(y_test, X_test["lag_7"]), 1))
for model in [RandomForestRegressor(n_estimators=300, random_state=0), LinearRegression()]:
    model.fit(X_train, y_train)
    print(f"  {type(model).__name__:<21}", round(mean_absolute_error(y_test, model.predict(X_test)), 1))

tscv = TimeSeriesSplit(n_splits=4, test_size=14)
print("\nTimeSeriesSplit folds (train rows -> test rows):")
for tr, te in tscv.split(X):
    print(f"  {tr[0]}-{tr[-1]} -> {te[0]}-{te[-1]}")
mae = -cross_val_score(LinearRegression(), X, y, cv=tscv, scoring="neg_mean_absolute_error")
print("LinearRegression MAE per fold:", mae.round(1))

Output

Test period: 2026-04-03 to 2026-04-30

Mean absolute error on the last 28 days:
  'Same as yesterday': 18.2
  'Same as last week': 8.5
  RandomForestRegressor 9.8
  LinearRegression      6.1

TimeSeriesSplit folds (train rows -> test rows):
  0-56 -> 57-70
  0-70 -> 71-84
  0-84 -> 85-98
  0-98 -> 99-112
LinearRegression MAE per fold: [7.1 4.8 7.2 5.1]
  • The last 28 days are the test set, and everything before is training data. Using train_test_split with shuffling would let the model peek at the future.
  • Two baselines need no training at all. “Same as yesterday” is poor (MAE 18.2) because it misses the weekend jumps. “Same as last week” is much better (8.5).
  • The random forest scores 9.8, worse than the weekly baseline. Trees can only predict values in the range they saw in training, so they cannot follow a trend upward into new territory.
  • Linear regression continues the trend and wins with MAE 6.1.
  • TimeSeriesSplit makes folds that always train on earlier rows and test on the next 14. The training window grows with each fold.

Useful Features and Tools

Featurepandas codeCaptures
Lags.shift(k)Recent values
Rolling means.shift(1).rolling(w).mean()Recent level, smoothed
Calendarindex.dayofweek, index.monthWeekly and yearly patterns
Holiday flagindex.isin(holidays)Special days such as Eid
Differences.diff()Change instead of level, which removes a trend

For forecasts several days ahead, the lag-1 value for day 3 is not known yet. Either predict one day at a time and feed each forecast back in, or build features only from data available on the day you forecast. Dedicated libraries such as statsmodels (ARIMA, exponential smoothing) are also worth learning for classic time series work.

Common Mistakes

  1. Shuffling before splitting, which mixes future rows into training and makes scores look far too good.
  2. Rolling windows that include the current value. Always shift(1) before rolling.
  3. Skipping the baseline. If “same as last week” beats your model, the model is not useful yet.
  4. Using tree models on strongly trending data without first removing the trend, for example by predicting the change with diff().

Practice Exercises

Exercise 1. In the first script, add a feature with the sales from 14 days earlier, just before the dropna() line. How many rows are left?

Show answer
df["lag_14"] = df["sales"].shift(14)

106 rows. The first 14 days now have a missing value and are dropped.

Exercise 2. Make the random forest handle the trend by predicting the change from last week instead of the sales level.

Show answer
target = y - X["lag_7"]                       # change since last week
rf = RandomForestRegressor(n_estimators=300, random_state=0)
rf.fit(X_train, target[:-28])
pred = X_test["lag_7"] + rf.predict(X_test)  # add the change back
print(round(mean_absolute_error(y_test, pred), 1))

The MAE drops from 9.8 to 7.9. The weekly change has no long-term trend, so the forest no longer has to predict values outside its training range. Linear regression is still better on this data.

Frequently Asked Questions

Is time series forecasting regression?

Yes, when the target is a number. The difference is in how you build features and split the data, because row order carries meaning.

How much history do I need?

At least a few full cycles of the pattern you want to capture. For a weekly pattern, a few months is fine; for a yearly pattern, aim for two or more years.

Summary

  • Lags, rolling means and calendar flags turn a time series into a normal table.
  • Always split by time and use TimeSeriesSplit for cross-validation.
  • Compare every model with simple baselines such as “same as last week”.
  • Tree models cannot extrapolate a trend; predict the change instead, or use a linear model.

Next: Handling Missing Data in Python.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *