65. How to Forecast Sales with Time Series in Python (pandas and sklearn)
65.4 Moving Average Forecast
65.4 Moving average forecast
Last month spike असू शकतो. Short average noise शांत करतो.
हे का शिकायचं?
Why. Last month can be a spike. A short average smooths noise. Banks and clinics use this as a calm baseline.
What. A moving average (MA) of the last k points. For a flat forecast, use the MA of the last k train points for every future month (simple teaching version).
कसं करायचं?
How.
MA(3) flat forecast
- Take the last 3 train values.
- Compute their mean.
- Use that mean as the prediction for each test month.
- Later you can also roll the window forward one step at a time.
Worked example A — MA(3) on Mauli train tail.
import pandas as pd
import numpy as np
df = pd.read_csv("mauli_monthly_sales.csv", parse_dates=["month"]).sort_values("month")
train = df.iloc[:30]
test = df.iloc[30:]
ma3 = float(train["sales_inr"].iloc[-3:].mean())
pred = np.full(len(test), int(round(ma3)))
print("Last 3 train values:", train["sales_inr"].iloc[-3:].tolist())
print("MA3:", round(ma3, 2))
print(list(zip(test["month"].dt.strftime("%Y-%m"), pred)))
Output you should see.
Last 3 train values: [539600, 594100, 631700]
MA3: 588466.67
[('2026-05', 588467), ('2026-06', 588467), ('2026-07', 588467), ('2026-08', 588467), ('2026-09', 588467), ('2026-10', 588467)]
याचा अर्थ. Smoother than last-value (631700), but still flat — it cannot rise into festival months by itself.
Worked example B — US bank deposits ($).
Dataset note: fictional Hilltop Bank Austin branch new deposits. 8 rows. Columns: month, new_deposits_usd.
import pandas as pd
bank = pd.DataFrame({
"month": pd.date_range("2025-01-01", periods=8, freq="MS"),
"new_deposits_usd": [1200000, 1150000, 1300000, 1280000, 1400000, 1350000, 1500000, 1480000],
})
bank["ma3"] = bank["new_deposits_usd"].rolling(3).mean().round(0)
print(bank.to_string(index=False))
Output you should see.
month new_deposits_usd ma3
2025-01-01 1200000 NaN
2025-02-01 1150000 NaN
2025-03-01 1300000 1216667.0
...
2025-08-01 1480000 1443333.0
याचा अर्थ. First two MA3 cells are NaN (need 3 points). August MA3 ≈ $1.44M — a calm view of recent deposits.
Worked example C — When MA loses.
If sales jump every October, a flat MA under-shoots. Seasonal naive or lag-12 features handle that better.
Ravindra Bagale's Tip
MA is a calm baseline. If festivals jump, do not trust MA alone — keep a seasonal method.
Ravindra Bagale's Tip – मराठी
MA = शांत baseline. Festival jump असेल तर फक्त MA वर अवलंबून राहू नका — season method ठेवा.
Ravindra Bagale's Tip – हिंदी
MA शांत baseline है। Festival jump हो तो सिर्फ MA पर मत जाओ — season method रखो।