65. How to Forecast Sales with Time Series in Python (pandas and sklearn)
65.1 Why Forecast Next Months from Past Months
Why. Priya Deshmukh (Pune ops) asks: “How many rupees of stock should Mauli Kirana order for Diwali month?” Looking at only last week is weak. Looking at the same month last year is better. A clear forecast turns a guess into a plan.
What.
- Forecast — a careful guess of future values from past values.
- Time series — data points in time order (day, week, month).
- Horizon — how far ahead you predict (next 1 month, next 6 months).
How.
Frame the business ask
- Write the question in one line (“Next 6 months of sales in ₹”).
- Name the grain (daily / weekly / monthly).
- Collect past values in time order.
- Hold back the newest months as a test.
- Compare methods with MAE / MAPE before you trust one number.
Worked example A — Retail in Pune (₹).
Dataset note: fictional Mauli Kirana monthly sales. 36 rows. Columns: month, sales_inr. Path used in labs: mauli_monthly_sales.csv.
import pandas as pd
df = pd.read_csv("mauli_monthly_sales.csv", parse_dates=["month"])
print(df.head(3))
print(df.tail(3))
print("rows:", len(df), "columns:", list(df.columns))
Output you should see.
month sales_inr
0 2023-11-01 440000
1 2023-12-01 357700
2 2024-01-01 363000
month sales_inr
33 2026-08-01 694700
34 2026-09-01 799900
35 2026-10-01 878700
rows: 36 columns: ['month', 'sales_inr']
What it means. Oldest month first. Newest month last. That order matters for every method in this chapter.
Worked example B — Healthcare in Manchester (£).
Dataset note: fictional City Light Clinic monthly appointments. 6 rows. Columns: month, appointments. Fee context £45 per visit.
import pandas as pd
clinic = pd.DataFrame({
"month": pd.date_range("2025-05-01", periods=6, freq="MS"),
"appointments": [210, 198, 205, 240, 255, 248],
})
print(clinic)
print("Naive guess for next month:", int(clinic["appointments"].iloc[-1]))
Output you should see.
month appointments
0 2025-05-01 210
1 2025-06-01 198
2 2025-07-01 205
3 2025-08-01 240
4 2025-09-01 255
5 2025-10-01 248
Naive guess for next month: 248
What it means. A first forecast can be “same as last month” — we improve it later.
Worked example C — Comparison card.
| Approach | Good for | Weak when |
|---|---|---|
Excel FORECAST / chart trend |
Quick slide | Season + many products |
| Regular regression on random rows | Cross-section data | Time order ignored |
| Time-series methods (this chapter) | Next months from past months | You shuffle dates |
Ravindra Bagale's Tip
Write the question first: which number, which grain, how many months ahead. Then pick a method. A forecast is a plan, not magic.
Ravindra Bagale's Tip – मराठी
आधी प्रश्न लिहा: कोणता number, कोणता grain, किती months पुढे. मग model. Forecast = plan, magic नाही.
Ravindra Bagale's Tip – हिंदी
पहले सवाल लिखो: कौन सा number, कौन सा grain, कितने months आगे। फिर model। Forecast = plan है, जादू नहीं।