Rana Maninder Singh
Lesson 1 of 7Time Series Forecasting

What Is Time Series?

Lesson opener

In one line: Forecasting is not magic: it extrapolates patterns that already exist.

Why it matters: Order and spacing carry information that tabular ML rows throw away when you treat each day as an independent sample.

Before this lesson: A/B Testing / Inferential stats / Python basics

Before you start


What you will learn

  • What makes a series a time series (ordered index, frequency, gaps)
  • How Indian workplace KPIs look as daily or weekly series
  • Building a DatetimeIndex with pandas==2.2.3 and checking frequency
  • Lags, differences, and why random shuffle destroys the problem

Pinned libraries for this course

Install the course pins once and reuse them across lessons:

pip install -r docs/timeseries/requirements.txt

Pinned in docs/timeseries/requirements.txt:

numpy==2.1.3
pandas==2.2.3
statsmodels==0.14.4
scipy==1.14.1

This lesson uses numpy and pandas for offline demos. Later lessons add statsmodels for decomposition, Holt-Winters, and ARIMA. Pin versions so analysts in Bengaluru and Pune reproduce the same numbers in CI.


The problem it solves

A Bengaluru D2C ops lead asks: how many orders should we staff for next week? Yesterday's count alone is not enough — Mondays differ from Sundays, festival weeks spike, and a warehouse delay last Tuesday still sits in the history. A time series is a sequence of measurements indexed by time, in order, usually at a regular frequency (daily, hourly, weekly).

WHY Order and spacing carry information that tabular ML rows throw away when you treat each day as an independent sample.

WHEN The question is about future values of a KPI that already has a history — demand, tickets, UPI volume, DAU — not about classifying a single user.

Forecasting is not magic: it extrapolates patterns that already exist. It does not invent a Diwali spike if your training window never saw one, and it does not replace a capacity plan when suppliers fail. It answers: given this history and a chosen model class, what is a useful point (and later, interval) forecast?

Demo 1 — Daily orders as a series

Stakeholders talk in meetings. Analysts talk in indexed frames. Encode the KPI so every row is one period and the index is time.

# Offline demo: daily order KPI with a DatetimeIndex
import numpy as np
import pandas as pd

rng = np.random.default_rng(7)
dates = pd.date_range("2026-01-01", periods=28, freq="D")
trend = np.linspace(420, 480, 28)
weekly = 35 * np.sin(2 * np.pi * np.arange(28) / 7)
noise = rng.normal(0, 12, 28)
orders = np.clip(trend + weekly + noise, 1, None).round().astype(int)
s = pd.Series(orders, index=dates, name="orders")
print(s.head())
print("freq:", s.index.freq)
assert len(s) == 28
assert s.index.freqstr == "D"

Walk this shape with ops before anyone debates ARIMA. If dates are strings, duplicates, or missing Sundays silently, the forecast is already wrong.


Frequency, gaps, and the index

Frequency is the intended spacing (D, H, W-MON). Many warehouse extracts arrive as irregular event logs; you must resample to the decision cadence (usually daily for staffing, weekly for purchases).

Gaps matter. A missing day is not zero orders unless you proved the store was closed. Imputing with zero invents a crash; forward-fill invents a plateau. Document the rule in the ticket.

WHY Models assume a regular grid. Gaps become NaNs or wrong zeros and bias seasonality.

WHEN At ingestion — before plotting or fitting anything.

Demo 2 — Resample event logs to daily counts

# Offline demo: event timestamps → daily order counts
import pandas as pd

events = pd.DataFrame(
    {
        "ts": pd.to_datetime(
            [
                "2026-03-01 09:10",
                "2026-03-01 18:40",
                "2026-03-02 11:05",
                "2026-03-04 08:00",  # gap on Mar 3
            ]
        )
    }
)
daily = events.set_index("ts").resample("D").size().rename("orders")
print(daily)
assert daily.loc["2026-03-03"] == 0  # empty bin after resample
assert daily.sum() == 4

[!important] Resample turning a quiet day into 0 is a modelling choice — confirm with the business whether the channel was closed.

Demo 3 — Lag features preserve order

Supervised ML on tabular rows often adds lag_1, lag_7. That only works if you never shuffle across time when validating.

# Offline demo: lag columns for a daily KPI
import pandas as pd

s = pd.Series(
    [100, 110, 105, 120, 115, 130, 125],
    index=pd.date_range("2026-04-01", periods=7, freq="D"),
    name="tickets",
)
df = s.to_frame()
df["lag_1"] = df["tickets"].shift(1)
df["lag_7"] = df["tickets"].shift(7)
print(df)
assert pd.isna(df.iloc[0]["lag_1"])
assert df.iloc[1]["lag_1"] == 100

What time series forecasting is not

Teams in Hyderabad SaaS and Mumbai fintech sometimes misuse the label:

  1. Fit a regression on random 80/20 row split — that leaks future into train and invents accuracy.
  2. Average last year and call it a forecast — that can be a baseline (next lessons), but it is not a fitted seasonal model.
  3. Ignore calendar — Indian payroll weeks, IPL finals, and GST filing deadlines move KPIs; a model blind to calendar still needs honest evaluation around those weeks.

WHY Wrong validation teaches leadership false confidence.

WHEN In the forecast brief: write the KPI, frequency, horizon, and holdout rule in one paragraph.

Demo 4 — Why shuffle breaks time order

# Offline demo: shuffled split vs chronological split
import numpy as np

y = np.arange(20, dtype=float)  # strictly increasing "trend"
rng = np.random.default_rng(0)
idx = np.arange(20)
shuffled = rng.permutation(idx)
# Chronological: train past, test future
chrono_test = y[16:]
# Naive leak: take random 20% including late values in "train"
train_idx = shuffled[:16]
# Future points that accidentally landed in train
leaked = set(train_idx) & set(range(16, 20))
print("chronological test mean:", chrono_test.mean())
print("future indices leaked into shuffled train:", sorted(leaked))
assert len(chrono_test) == 4
assert len(leaked) >= 1

Indian workplace framing

A Noida edtech tracking daily trial starts, a Jaipur D2C brand tracking COD orders, and a Pune SaaS tracking support tickets all share constraints: festival spikes, Monday batch jobs, and leadership asking for "next month" from eight weeks of clean history. Agree the horizon (7 days? 4 weeks?) and the decision use (staffing, purchase order, cash buffer) before choosing a model. If Diwali week will dominate the ask, either exclude it from a quiet-season model or accept that the forecast is about festival demand.

WHY The business question sets the horizon and the acceptable error.

WHEN Before picking Holt-Winters vs ARIMA — model class is secondary to KPI definition.

Demo 5 — Horizon and decision stub

# Offline demo: encode forecast brief fields
brief = {
    "kpi": "daily_orders",
    "city_ops": "Bengaluru",
    "freq": "D",
    "horizon_days": 7,
    "decision": "warehouse_shifts",
}


def validate_brief(b: dict) -> list[str]:
    required = ("kpi", "freq", "horizon_days", "decision")
    return [k for k in required if k not in b or b[k] in (None, "")]


assert validate_brief(brief) == []
bad = {"kpi": "daily_orders"}
assert "horizon_days" in validate_brief(bad)
print(brief)

Demo 6 — Simple difference for trend peek

First differences remove a linear drift so weekdays are easier to compare. Full stationarity tests come later with ARIMA intuition.

# Offline demo: first difference of a trending KPI
import numpy as np
import pandas as pd

y = pd.Series(np.linspace(200, 260, 15) + np.array([0, 5, -3, 4, 0] * 3))
d1 = y.diff().dropna()
print("level head:", y.head(3).tolist())
print("diff head:", d1.head(3).round(2).tolist())
assert len(d1) == len(y) - 1
assert abs(d1.mean() - (y.iloc[-1] - y.iloc[0]) / (len(y) - 1)) < 1.0

Failure modes before day one

  1. String dates sorted alphabetically → wrong order.
  2. Duplicate timestamps from double ingestion → inflated spikes.
  3. Timezone mix (UTC vs IST) → off-by-one days around midnight.
  4. KPI redefined mid-history (COD vs prepaid) without a break flag → fake level shift.

Official pandas time-series docs describe indexes and resampling; they do not replace your KPI dictionary. Pin libraries so every notebook matches CI.

Verified against numpy 2.1.3, pandas 2.2.3, statsmodels 0.14.4 (+1 more) documentation, September 2026.

Test yourself

  1. What makes a sequence a time series rather than a plain table?
  2. Why does frequency matter for daily order forecasts?
  3. What does resample("D").size() do to event timestamps?
  4. True or false: an 80/20 random shuffle is fine for forecasting validation.
  5. Name one Indian workplace KPI suited to daily forecasting.
  6. What is a forecast horizon?
  7. Why can a missing day becoming 0 after resample be dangerous?
  8. What does shift(1) create on a series?
  9. Which pinned pandas version does this course use?
  10. True or false: forecasting invents a festival spike with no festival in history.