import pandas as pd
import numpy as np
from prophet import Prophet
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
import warnings
warnings.filterwarnings('ignore')
# =============================================================================
# USAGE-BASED REVENUE FORECASTING MODEL WITH SEASONALITY
# =============================================================================
# This model uses Facebook's Prophet to forecast usage (e.g., API calls, active users)
# incorporating trend, seasonality (yearly, weekly, daily), and holidays if provided.
# Revenue is then calculated as: forecasted_usage * price_per_unit.
#
# Key Assumptions:
# - Revenue is directly proportional to usage (usage * constant price_per_unit).
# - Historical data: Daily granularity with 'date' and 'usage' columns.
# - Extendable: Add changepoints for known events, custom seasonality, holidays.
#
# Inputs:
# - historical_df: pd.DataFrame with 'date' (datetime) and 'usage' (float/int).
# - price_per_unit: float (e.g., revenue per API call or per user).
# - forecast_days: int (number of days to forecast ahead).
# - holidays_df: optional pd.DataFrame for holidays ('holiday' str, 'ds' date, 'lower_window', 'upper_window').
#
# Outputs:
# - forecast_df: pd.DataFrame with 'ds', 'yhat' (usage forecast), 'yhat_lower', 'yhat_upper', 'revenue', 'revenue_lower', 'revenue_upper'.
# - Plots: Historical + forecast usage/revenue.
#
# Installation: pip install prophet pandas matplotlib numpy
# =============================================================================
class UsageRevenueForecaster:
def __init__(self, price_per_unit=0.01, changepoint_prior_scale=0.05, seasonality_prior_scale=10.0):
"""
Initialize the forecaster.
:param price_per_unit: Revenue per unit of usage (default: $0.01).
:param changepoint_prior_scale: Prophet param for trend flexibility (higher = more flexible).
:param seasonality_prior_scale: Prophet param for seasonality strength.
"""
self.price_per_unit = price_per_unit
self.model = Prophet(
changepoint_prior_scale=changepoint_prior_scale,
seasonality_prior_scale=seasonality_prior_scale,
yearly_seasonality=True,
weekly_seasonality=True,
daily_seasonality=False, # Set True for sub-daily data
holidays=None
)
self.forecast_df = None
def fit(self, historical_df, holidays_df=None):
"""
Fit the model to historical usage data.
:param historical_df: pd.DataFrame with 'date' (datetime) and 'usage' columns, sorted by date.
:param holidays_df: Optional pd.DataFrame for holidays.
"""
# Prepare data for Prophet: rename columns to 'ds' and 'y'
df_prophet = historical_df[['date', 'usage']].rename(columns={'date': 'ds', 'usage': 'y'}).copy()
df_prophet['ds'] = pd.to_datetime(df_prophet['ds'])
# Add holidays if provided
if holidays_df is not None:
self.model.holidays = holidays_df
# Fit the model
self.model.fit(df_prophet)
print("Model fitted successfully!")
def predict(self, forecast_days=365):
"""
Generate forecast for next 'forecast_days'.
:param forecast_days: Number of days to forecast.
:return: forecast_df with usage and revenue forecasts.
"""
# Create future dataframe
future = self.model.make_future_dataframe(periods=forecast_days)
# Predict usage
forecast = self.model.predict(future)
# Calculate revenue forecasts
forecast['revenue'] = forecast['yhat'] * self.price_per_unit
forecast['revenue_lower'] = forecast['yhat_lower'] * self.price_per_unit
forecast['revenue_upper'] = forecast['yhat_upper'] * self.price_per_unit
# Keep only relevant columns and future predictions
self.forecast_df = forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper', 'revenue', 'revenue_lower', 'revenue_upper']].copy()
self.forecast_df['ds'] = pd.to_datetime(self.forecast_df['ds'])
# Filter to future only (after last historical date)
last_historical_date = self.forecast_df['ds'].max() - pd.Timedelta(days=forecast_days + 1)
future_forecast = self.forecast_df[self.forecast_df['ds'] > last_historical_date].copy()
print(f"Forecast generated for {len(future_forecast)} future days.")
return self.forecast_df, future_forecast
def plot(self, historical_df):
"""
Plot historical + forecasted usage and revenue.
:param historical_df: Original historical data for plotting.
"""
fig, axes = plt.subplots(2, 1, figsize=(12, 10))
# Usage plot
hist_usage = historical_df.set_index('date')['usage']
axes[0].plot(hist_usage.index, hist_usage.values, 'b-', label='Historical Usage', linewidth=2)
axes[0].plot(self.forecast_df['ds'], self.forecast_df['yhat'], 'r--', label='Forecasted Usage', linewidth=2)
axes[0].fill_between(self.forecast_df['ds'], self.forecast_df['yhat_lower'], self.forecast_df['yhat_upper'],
color='red', alpha=0.2, label='Uncertainty')
axes[0].set_title('Usage Forecast with Seasonality')
axes[0].set_ylabel('Usage')
axes[0].legend()
axes[0].grid(True, alpha=0.3)
# Revenue plot
axes[1].plot(hist_usage.index, hist_usage * self.price_per_unit, 'b-', label='Historical Revenue', linewidth=2)
axes[1].plot(self.forecast_df['ds'], self.forecast_df['revenue'], 'r--', label='Forecasted Revenue', linewidth=2)
axes[1].fill_between(self.forecast_df['ds'], self.forecast_df['revenue_lower'], self.forecast_df['revenue_upper'],
color='red', alpha=0.2, label='Uncertainty')
axes[1].set_title('Revenue Forecast')
axes[1].set_xlabel('Date')
axes[1].set_ylabel('Revenue ($)')
axes[1].legend()
axes[1].grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
def get_summary_stats(self, future_forecast):
"""
Print summary statistics for future revenue.
:param future_forecast: Future forecast DataFrame.
"""
total_rev = future_forecast['revenue'].sum()
avg_monthly_rev = future_forecast['revenue'].resample('M', on='ds').sum().mean()
print(f"\n=== FORECAST SUMMARY ===")
print(f"Total Forecasted Revenue (next {len(future_forecast)} days): ${total_rev:,.2f}")
print(f"Avg. Monthly Revenue: ${avg_monthly_rev:,.2f}")
print(f"Min Daily Revenue: ${future_forecast['revenue'].min():.2f}")
print(f"Max Daily Revenue: ${future_forecast['revenue'].max():.2f}")
# =============================================================================
# EXAMPLE USAGE WITH SAMPLE DATA
# =============================================================================
# Step 1: Generate sample historical data (2 years, daily usage with trend + seasonality + noise)
np.random.seed(42)
dates = pd.date_range(start='2022-01-01', end='2023-12-31', freq='D')
n_days = len(dates)
# Base trend: linear growth
trend = 1000 + 10 * np.arange(n_days)
# Seasonality: yearly sine wave + weekly cycle
yearly_season = 500 * np.sin(2 * np.pi * np.arange(n_days) / 365.25)
weekly_season = 200 * np.sin(2 * np.pi * np.arange(n_days) / 7)
seasonal = yearly_season + weekly_season
# Noise and some growth spurts
noise = np.random.normal(0, 100, n_days)
usage = trend + seasonal + noise
usage = np.maximum(usage, 0) # No negative usage
historical_df = pd.DataFrame({'date': dates, 'usage': usage})
print("Sample historical data shape:", historical_df.shape)
print(historical_df.head())
# Optional: Sample holidays (e.g., Black Friday spikes)
holidays = pd.DataFrame({
'holiday': 'black_friday',
'ds': pd.to_datetime(['2022-11-25', '2023-11-24']),
'lower_window': 0,
'upper_window': 1,
})
# Step 2: Initialize, fit, predict, and plot
forecaster = UsageRevenueForecaster(price_per_unit=0.01) # $0.01 per unit usage
forecaster.fit(historical_df, holidays_df=holidays) # Pass holidays if needed
full_forecast, future_forecast = forecaster.predict(forecast_days=365)
# Step 3: Visualize
forecaster.plot(historical_df)
# Step 4: Summary stats
forecaster.get_summary_stats(future_forecast)
# Step 5: View future forecast table (first 10 rows)
print("\n=== FUTURE FORECAST SAMPLE ===")
print(future_forecast.head(10).round(2))
# =============================================================================
# HOW TO USE WITH YOUR DATA
# =============================================================================
# 1. Load your data: historical_df = pd.read_csv('your_usage.csv')
# 2. Ensure columns: 'date' (YYYY-MM-DD), 'usage' (numeric)
# 3. forecaster = UsageRevenueForecaster(price_per_unit=YOUR_PRICE)
# 4. forecaster.fit(historical_df)
# 5. full_forecast, future_forecast = forecaster.predict(365)
# 6. Export: future_forecast.to_csv('revenue_forecast.csv', index=False)
#
# Customization:
# - Variable pricing: Replace revenue calc with a custom function (e.g., tiered pricing).
# - Add regressors: self.model.add_regressor('marketing_spend')
# - Custom seasonality: self.model.add_seasonality(name='monthly', period=30.5, fourier_order=5)
# - Confidence intervals: Use yhat_lower/upper for risk analysis.
# =============================================================================
Model Explanation
- Prophet: Automatically detects and models seasonality (yearly/weekly), trend (with changepoints), and holidays. Handles missing data and outliers well.
- Usage to Revenue: Simple multiplication; extendable for tiers (e.g.,
def tiered_price(usage): ...).
- Uncertainty: 80% prediction intervals (
yhat_lower/upper) propagated to revenue.
- Scalability: Works on daily/hourly data; retrain periodically with new data.
- Sample Data: Simulates realistic usage (trend up, peaks in holidays/seasons).
Run the code in Jupyter/Colab for plots/tables. Adapt price_per_unit and data for your use case! If you provide real data, I can refine it.