Introduction
Sales per day, temperature per hour, visitors per week: much real data is a time series, values measured one after another in time. Time adds questions that ordinary tables do not have. Is the value growing? Is this month unusual, or is it just December again? Is today's spike a problem? This lesson covers the basic tools, all in plain Python.
How it works
Order and aggregation. Records often arrive unsorted and at a finer level than needed, such as single orders with timestamps. First sort by time, then aggregate to the period that answers the question: total sales per day or per month. Dates written as YYYY-MM-DD sort correctly as plain strings, and the first seven characters, YYYY-MM, are the month.
Percentage change compares each period with the previous one: (new − old) ÷ old × 100. Going from 150 to 180 is +20%; from 180 to 135 is −25%. Note that a fall of 50% followed by a rise of 50% does not return to the start: 100 becomes 50, then 75.
Moving averages. Day-to-day values are noisy. The moving average of window k replaces each value by the average of the last k values, which smooths the noise and shows the trend. With window 3, the series 10, 20, 30, 40, 50 gives 20, 30, 40. A larger window is smoother but reacts more slowly. The first k − 1 positions have no full window.
Seasonality. Many series repeat a pattern: shops sell more in December, electricity use peaks every evening. Compare a value with the same period last year, or use a window as long as the season, so that the pattern does not look like growth.
Anomalies. To decide whether today is unusual, compare it with the recent past only: the mean and standard deviation of the previous k values. A value more than 3 standard deviations from that mean is a candidate anomaly. Using future values, or the whole series, would let the anomaly influence its own threshold, and could not run live.
Example
# Time series: growth from month to month and a 3-month moving average.
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
sales = [120, 135, 128, 150, 162, 158]
for i in range(len(sales)):
line = f"{months[i]}: {sales[i]}"
if i > 0:
change = (sales[i] - sales[i - 1]) / sales[i - 1] * 100
line += f" change {change:+.1f}%"
if i >= 2:
line += f" 3-month average {sum(sales[i - 2:i + 1]) / 3:.1f}"
print(line)Line by line
- Six months of sales in time order.
- From February on, each month's change is computed against the month before.
- From March on, the average of the last three months smooths the series.
:+.1fprints the sign of the change, so growth and decline are both visible.
Expected result
Jan: 120
Feb: 135 change +12.5%
Mar: 128 change -5.2% 3-month average 127.7
Apr: 150 change +17.2% 3-month average 137.7
May: 162 change +8.0% 3-month average 146.7
Jun: 158 change -2.5% 3-month average 156.7
The monthly changes jump up and down, but the moving average rises steadily: the trend is up.
In the real world
Retailers plan stock from moving averages and seasonal patterns. Website monitoring tools raise alerts when traffic leaves the band set by recent values. Economists report inflation as the percentage change from the same month a year earlier, precisely to remove seasonality.
Common mistakes
- Analysing records in the order they arrived instead of sorting by time.
- Calling a seasonal peak growth by comparing December with November.
- Using future data to judge or smooth the past, which a live system cannot do.
- Averaging percentage changes instead of comparing the start and end values.
Best practices
- Sort, then aggregate to the period that matches the question.
- Show the raw series and a moving average together.
- Compare with the same period of the previous cycle when a season is present.
Summary
A time series is analysed in time order and at a sensible period. Percentage change measures growth between periods, a moving average shows the trend under the noise, seasonality must be separated from growth, and anomalies are values far from the mean of the recent past.
Quick check
Key takeaways
- Always sort by time and aggregate to a sensible period before analysing.
- Percentage change compares periods; a moving average shows the trend under the noise.
- Judge a value against the recent past, using only data before it.
Practice problems for this lesson
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.