Most time-series models assume the series is stationary — that its behaviour doesn't drift over time. A series climbing steadily upward breaks that assumption immediately. Differencing fixes it by modelling the changes instead of the levels.
One pass replaces each value with the difference from the one before it:
The first value has no predecessor, so each pass makes the series one shorter.
Task: write difference(series, order) returning the series after differencing it order times.
order is 0 or more. At order = 0 the series comes back unchanged.len(series) - order.What each order removes is worth knowing. First differencing kills a linear trend: a series going up by 5 every step becomes a constant 5. Second differencing kills a quadratic one — the squares 1, 4, 9, 16 become 3, 5, 7 and then the constant 2, 2. That's the d in ARIMA, and almost nobody needs it above 2.
The cost is paid in two places: you lose a data point per pass, and your model now predicts changes rather than values, so you have to add the levels back to get a usable forecast.