Last year's chaos: 500 customers left due to long lines. $8M lost in 24 hours.
📞 Emergency Board Meeting
November 21st, 3 days before Black Friday. Sarah's phone rings at 6 AM.
⚠️ CRITICAL SITUATION
CEO: "Sarah, last year was a disaster. We had lines wrapping around the building at 6 AM, ran out of doorbusters by 8 AM, and our website crashed at midnight. Competitors captured $8M of our sales."
"This year MUST be different. Can you predict hourly demand so we can staff correctly and stock properly?"
Sarah looks at the data from last year's Black Friday:
Midnight - 4 AM
Website crashed 50,000 lost visitors $2M lost sales
5 AM - 8 AM
Understaffed by 70% 2-hour wait times $3M lost sales
2 PM - 5 PM
Overstaffed by 200% Workers standing idle $500K wasted labor
6 PM - 11 PM
Surprise second surge Unprepared staff $2.5M lost sales
"If we can predict demand by the hour, we can prevent this disaster!"
📊 Last Year's Black Friday Pattern
🔍 Detect Patterns in the Chaos
Click on each pattern to understand Black Friday behavior:
🚪
Doorbuster Rush
5-8 AM mega spike
🍔
Lunch Lull
12-2 PM quiet period
🌙
Evening Surge
6-9 PM second wave
💻
Midnight Online
12-2 AM web rush
🤔 Why is hourly prediction crucial for Black Friday?
To impress the board with fancy charts
To optimize staffing levels and prevent customer loss
To predict total daily sales only
To compete with weather forecasters
📈 Time Series: Predicting the Future from the Past
Learn how patterns repeat and evolve over time
The Heartbeat Analogy
Imagine you're a doctor monitoring a patient's heartbeat. You see:
📍 Regular Pattern: Beat every 0.8 seconds (trend)
📊 Exercise Effect: Faster during activity (seasonality)
😴 Sleep Pattern: Slower at night (cyclical)
☕ Coffee Spike: Temporary increase (irregular)
Time series forecasting works the same way! We identify patterns and project them forward.
🔬 Decompose Black Friday Sales
🛠️ Build Your Own Time Series
🎯 Building Your Prediction Arsenal
Master ARIMA and Prophet for Black Friday forecasting
🤖 Choose Your Forecasting Weapon
📉
ARIMA
Classic statistical approach
92% accuracy
✅ Great for stable patterns
❌ Struggles with holidays
🔮
Prophet (Facebook)
Built for business data
95% accuracy
✅ Handles holidays well
✅ Robust to missing data
🧠
LSTM Neural Network
Deep learning approach
97% accuracy
✅ Captures complex patterns
❌ Needs lots of data
📊 ARIMA Model for Black Friday
import pandas as pd
import numpy as np
from statsmodels.tsa.arima.model import ARIMA
import warnings
warnings.filterwarnings('ignore')
# Load Black Friday historical data
dates = pd.date_range('2019-11-29', periods=24*4, freq='H') # 4 years of Black Friday
np.random.seed(42)
# Create realistic Black Friday pattern
hourly_pattern = []
for day in range(4): # 4 years
for hour in range(24):
base = 1000
# Midnight online rush (12 AM - 2 AM)
if hour in [0, 1]:
sales = base * 3.5
# Early morning dormant (2 AM - 5 AM)
elif 2 <= hour < 5:
sales = base * 0.3
# Doorbuster rush (5 AM - 9 AM)
elif 5 <= hour < 9:
sales = base * 5.2
# Morning shopping (9 AM - 12 PM)
elif 9 <= hour < 12:
sales = base * 3.8
# Lunch lull (12 PM - 2 PM)
elif 12 <= hour < 14:
sales = base * 1.5
# Afternoon steady (2 PM - 6 PM)
elif 14 <= hour < 18:
sales = base * 2.5
# Evening surge (6 PM - 9 PM)
elif 18 <= hour < 21:
sales = base * 4.2
# Night wind down (9 PM - 12 AM)
else:
sales = base * 2.0
# Add noise and yearly growth
sales *= (1 + day * 0.1) # 10% yearly growth
sales += np.random.normal(0, 200)
hourly_pattern.append(sales)
sales_data = pd.Series(hourly_pattern, index=dates[:len(hourly_pattern)])
print("📊 BLACK FRIDAY HISTORICAL DATA")
print("="*50)
print(f"Date range: {dates[0].date()} to {dates[-1].date()}")
print(f"Total hours: {len(sales_data)}")
print(f"Average hourly sales: ${sales_data.mean():,.2f}")
print(f"Peak hour sales: ${sales_data.max():,.2f}")
# Fit ARIMA model
print("\n🔧 TRAINING ARIMA MODEL")
print("="*50)
print("Finding optimal parameters...")
# ARIMA(p, d, q) - p=autoregressive, d=differencing, q=moving average
model = ARIMA(sales_data[:-24], order=(2, 1, 2))
fitted = model.fit()
print("✅ Model trained successfully!")
print(f"AIC Score: {fitted.aic:.2f}")
print(f"BIC Score: {fitted.bic:.2f}")
# Make predictions for next Black Friday (24 hours)
print("\n🔮 PREDICTIONS FOR THIS BLACK FRIDAY")
print("="*50)
forecast = fitted.forecast(steps=24)
actuals = sales_data[-24:]
for hour, (pred, actual) in enumerate(zip(forecast, actuals)):
time = f"{hour:02d}:00"
accuracy = 100 - abs(pred - actual) / actual * 100
print(f"{time} - Predicted: ${pred:,.0f} | Actual: ${actual:,.0f} | Accuracy: {accuracy:.1f}%")
# Calculate overall accuracy
mae = np.mean(np.abs(forecast - actuals))
mape = np.mean(np.abs((forecast - actuals) / actuals)) * 100
print("\n📈 MODEL PERFORMANCE")
print("="*50)
print(f"Mean Absolute Error: ${mae:,.2f}")
print(f"Mean Absolute Percentage Error: {mape:.1f}%")
print(f"Overall Accuracy: {100-mape:.1f}%")
🔮 Prophet Model - Facebook's Gift to Retail
from prophet import Prophet
import pandas as pd
import numpy as np
# Prepare data for Prophet
prophet_data = pd.DataFrame({
'ds': dates[:len(sales_data)], # Date column
'y': sales_data.values # Target variable
})
# Add Black Friday as a holiday
black_fridays = pd.DataFrame({
'holiday': 'black_friday',
'ds': pd.to_datetime(['2019-11-29', '2020-11-27', '2021-11-26', '2022-11-25', '2023-11-24']),
'lower_window': -1, # Include Thanksgiving
'upper_window': 2, # Include weekend
})
print("🔮 PROPHET MODEL - BUILT FOR BLACK FRIDAY")
print("="*50)
# Initialize Prophet with custom seasonality
model = Prophet(
changepoint_prior_scale=0.05, # Flexibility of trend
seasonality_prior_scale=10, # Strength of seasonality
holidays=black_fridays, # Include Black Friday effect
yearly_seasonality=True,
weekly_seasonality=False, # Not relevant for Black Friday
daily_seasonality=True # Critical for hourly patterns
)
# Add custom regressors for retail patterns
prophet_data['is_doorbuster'] = (prophet_data['ds'].dt.hour >= 5) & (prophet_data['ds'].dt.hour < 9)
prophet_data['is_online_rush'] = (prophet_data['ds'].dt.hour >= 0) & (prophet_data['ds'].dt.hour < 2)
prophet_data['is_evening_surge'] = (prophet_data['ds'].dt.hour >= 18) & (prophet_data['ds'].dt.hour < 21)
model.add_regressor('is_doorbuster')
model.add_regressor('is_online_rush')
model.add_regressor('is_evening_surge')
print("📊 Training on historical Black Friday data...")
model.fit(prophet_data[:-24])
# Make future predictions
future = model.make_future_dataframe(periods=24, freq='H')
future['is_doorbuster'] = (future['ds'].dt.hour >= 5) & (future['ds'].dt.hour < 9)
future['is_online_rush'] = (future['ds'].dt.hour >= 0) & (future['ds'].dt.hour < 2)
future['is_evening_surge'] = (future['ds'].dt.hour >= 18) & (future['ds'].dt.hour < 21)
print("✅ Model trained with special Black Friday patterns!")
# Generate forecast
forecast = model.predict(future)
print("\n🎯 BLACK FRIDAY HOURLY PREDICTIONS")
print("="*50)
predictions = forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail(24)
for _, row in predictions.iterrows():
hour = row['ds'].strftime('%H:00')
pred = row['yhat']
lower = row['yhat_lower']
upper = row['yhat_upper']
# Staffing recommendations based on predictions
staff_needed = int(pred / 200) # 1 staff per 200 customers/hour
print(f"{hour} - Sales: ${pred:,.0f} [{lower:,.0f}-{upper:,.0f}] | Staff needed: {staff_needed}")
print("\n💡 KEY INSIGHTS")
print("="*50)
print("• Peak hour: 6:00 AM - Prepare maximum staff")
print("• Online surge: 12:00 AM - Ensure website capacity")
print("• Lunch lull: 12:00 PM - Reduce staff, prepare for afternoon")
print("• Evening surge: 6:00 PM - Second wave preparation needed")
⚡ Black Friday Command Center
Optimize staffing and inventory in real-time
👥 Optimal Staffing Schedule
💰 Staffing Economics
Cost per hour per staff: $25 Revenue per customer served: $85 Customers per staff per hour: 15
Total staff hours needed:850 Total labor cost:$21,250 Expected revenue:$1,082,500
🎮 Black Friday Simulator
Adjust parameters and see the impact in real-time:
Total Revenue
$8.2M
Customers Served
96,470
Wait Time
12 min
📊 Black Friday Live Dashboard
$5.2M
Current Sales
2,847
Customers/Hour
142
Staff Active
8 min
Avg Wait Time
🏆 Black Friday Triumph!
Record-breaking sales with zero chaos
📰 Breaking News: MegaMart's Perfect Black Friday
November 25th, 6:00 PM - As Black Friday comes to a close, MegaMart celebrates its most successful shopping day in history.
📊 Black Friday 2024 Results
$18.7M
Total Revenue
↑ 127% vs last year
142,000
Customers Served
↑ 89% vs last year
5 min
Average Wait Time
↓ 92% improvement
4.9⭐
Customer Rating
Best ever!
🎯 How Sarah's Time Series Model Made the Difference
12:00 AM - Midnight Online Rush
Model predicted 3.5x normal traffic. We added 20 extra servers. Zero crashes!
5:00 AM - Doorbuster Success
Predicted 5,200 customers. Staffed 180 employees. 5-minute average wait!
6:00 PM - Evening Surge Handled
Model caught the second wave. Staff ready. No customer left unserved!
📱 CEO's Text to Sarah at 9 PM:
"Sarah, INCREDIBLE! Zero complaints, record sales, happy staff. Your hourly predictions were 96% accurate. The board is ecstatic. You've revolutionized how we handle peak days. Bonus coming your way! 🎉"
📈 Model Performance Metrics
96.2%
Prediction Accuracy
$312
MAE (Hourly)
3.8%
MAPE
0.94
R² Score
💰 Financial Impact
Additional Revenue Captured: $10.5M (vs last year's losses)
Labor Cost Optimization: $487K saved through proper staffing
Customer Lifetime Value: +$3.2M from improved experience
Total Impact: $14.2M improvement
ROI on Time Series Implementation: 2,840%
🏅 Time Series Master Certification
This certifies that
[YOUR NAME]
has successfully mastered Time Series Forecasting for Business
ARIMA
Mastered
Prophet
Mastered
96%
Accuracy
$14M
Impact
🧠 Skills Mastered
✓
Time Series Components: Trend, seasonality, cyclical patterns, and irregular variations
✓
ARIMA Modeling: AutoRegressive Integrated Moving Average for stationary data
✓
Prophet Framework: Facebook's tool for business forecasting with holidays
✓
Real-Time Optimization: Converting predictions to staffing and inventory decisions
✓
Peak Event Management: Handling extreme variations in demand
🚀 What's Next?
Module 6: Deep Learning for Complex Patterns
Sarah's next challenge: Can she predict customer behavior across 500 stores simultaneously using neural networks?