# Importing necessary libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
import seaborn as sns
from unicodedata import numeric
from sklearn.metrics import r2_score, mean_absolute_percentage_error
from statsmodels.stats.outliers_influence import variance_inflation_factor
Loading and Splitting the Data¶
I begin by loading the three datasets from Excel and separating into training and testing periods using a cutoff date of 31 August 2022. This makes sure that the model is trained exclusively on training data, with the subsequent reporting period reserved as the test set. The initial observations are displayed to show the structure and contents of each dataset.
# Load the data from Excel
file_path = "data_task.xlsx"
# Display sheet names
excel_file = pd.ExcelFile(file_path)
print("Available sheets:", excel_file.sheet_names)
# Load the datasets
order_numbers_full = pd.read_excel(file_path, sheet_name="order_numbers")
transaction_data_full = pd.read_excel(file_path, sheet_name="transaction_data")
reported_data_full = pd.read_excel(file_path, sheet_name="reported_data")
# Define the training cutoff
cutoff_date = pd.Timestamp("2022-08-31")
# Create training datasets based on the cutoff date
order_numbers = order_numbers_full[order_numbers_full["date"] <= cutoff_date].copy()
transaction_data = transaction_data_full[transaction_data_full["date"] <= cutoff_date].copy()
reported_data = reported_data_full[reported_data_full["end_date"] <= cutoff_date].copy()
reported_data_test = reported_data_full[reported_data_full["start_date"] > cutoff_date].copy()
# Display the first few rows of each dataset
print("\nOrder numbers:")
display(order_numbers.head())
print("\nTransaction data:")
display(transaction_data.head())
print("\nReported data:")
display(reported_data.head())
Available sheets: ['order_numbers', 'transaction_data', 'reported_data'] Order numbers:
| date | order_number | |
|---|---|---|
| 0 | 2018-01-07 | 33841906 |
| 1 | 2018-01-22 | 34008921 |
| 2 | 2018-01-25 | 34397468 |
| 3 | 2018-02-06 | 34434432 |
| 4 | 2018-02-08 | 34579365 |
Transaction data:
| date | total_spend_index | gross_orders_index | weekly_active_users_index | |
|---|---|---|---|---|
| 0 | 2018-01-01 | 0.052537 | 0.158983 | 1.563652 |
| 1 | 2018-01-02 | 0.839176 | 1.430843 | 1.628314 |
| 2 | 2018-01-03 | 0.182855 | 0.476948 | 1.633740 |
| 3 | 2018-01-04 | 2.364675 | 1.907790 | 1.657706 |
| 4 | 2018-01-05 | 0.687484 | 1.271860 | 1.679863 |
Reported data:
| period | start_date | end_date | revenue_index | |
|---|---|---|---|---|
| 0 | 2018 Q1 | 2018-01-01 | 2018-02-28 | 100.000000 |
| 1 | 2018 Q2 | 2018-03-01 | 2018-06-30 | 253.521127 |
| 2 | 2018 Q3 | 2018-07-01 | 2018-08-31 | 139.788732 |
| 3 | 2018 Q4 | 2018-09-01 | 2018-12-31 | 306.161972 |
| 4 | 2019 Q1 | 2019-01-01 | 2019-02-28 | 117.693662 |
Initial Data Inspection¶
Here I display dataset dimensions, column names, data types, missing values, and duplicate observations. This provides an initial assessment of data quality and helps identify potential issues that may need to be addressed before feature engineering and modelling. Data is then sorted chronologically to insure there are no out-of-order dates.
# Analyze the datasets by printing: shapes, column names, data types, missing values, and duplicate rows
datasets = {
"order_numbers": order_numbers,
"transaction_data": transaction_data,
"reported_data": reported_data
}
for name, df in datasets.items():
print(f"\n{'=' * 50}")
print(f"Dataset: {name}")
print("\nShape (rows, columns):")
print(df.shape)
print("\nColumn names:")
print(df.columns.tolist())
print("\nData types:")
print(df.dtypes)
print("\nMissing values:")
print(df.isnull().sum())
print("\nDuplicate rows:")
print(df.duplicated().sum())
# Make sure data is sorted chronologically
order_numbers = (
order_numbers
.sort_values("date")
.reset_index(drop=True)
)
transaction_data = (
transaction_data
.sort_values("date")
.reset_index(drop=True)
)
reported_data = (
reported_data
.sort_values("start_date")
.reset_index(drop=True)
)
================================================== Dataset: order_numbers Shape (rows, columns): (772, 2) Column names: ['date', 'order_number'] Data types: date datetime64[ns] order_number int64 dtype: object Missing values: date 0 order_number 0 dtype: int64 Duplicate rows: 0 ================================================== Dataset: transaction_data Shape (rows, columns): (1704, 4) Column names: ['date', 'total_spend_index', 'gross_orders_index', 'weekly_active_users_index'] Data types: date datetime64[ns] total_spend_index float64 gross_orders_index float64 weekly_active_users_index float64 dtype: object Missing values: date 0 total_spend_index 0 gross_orders_index 0 weekly_active_users_index 0 dtype: int64 Duplicate rows: 0 ================================================== Dataset: reported_data Shape (rows, columns): (19, 4) Column names: ['period', 'start_date', 'end_date', 'revenue_index'] Data types: period object start_date datetime64[ns] end_date datetime64[ns] revenue_index float64 dtype: object Missing values: period 0 start_date 0 end_date 0 revenue_index 0 dtype: int64 Duplicate rows: 0
Order Number Analysis and Feature Engineering¶
I examine the order-number dataset for observations where order numbers fail to increase. We see a significant number of such observations that must be dealt with. An inital plot of the data demonstrates a strong non-linear trend, so a logarithmic transformation is applied and a linear model is then fitted to estimate the order number trend. The fitted values are transformed back to their original scale and combined with weekly active user data to estimate orders per active user. This provides a measure of underlying ordering activity that accounts for changes in the customer base.
# Identify non-increasing order numbers
order_numbers["order_number_diff"] = order_numbers["order_number"].diff()
order_numbers["invalid_order_sequence"] = order_numbers["order_number_diff"] <= 0
# Display suspicious observations
suspicious_orders = order_numbers[order_numbers["invalid_order_sequence"]]
print("Number of suspicious order-number observations:", len(suspicious_orders))
display(suspicious_orders)
# Apply log transformation to prepare for linear regression modeling
order_numbers["log_order_number"] = np.log1p(order_numbers["order_number"])
# Plot order numbers and log-transformed order numbers over time
fig, ax = plt.subplots(figsize=(14, 6))
ax.plot(order_numbers["date"], order_numbers["order_number"], marker=".", linestyle="-")
ax.set_title("Order Numbers Over Time")
ax.set_xlabel("Date")
ax.set_ylabel("Order Number")
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
fig, ax = plt.subplots(figsize=(14, 6))
ax.plot(order_numbers["date"], order_numbers["log_order_number"], marker=".", linestyle="-")
ax.set_title("Log-Transformed Order Numbers Over Time")
ax.set_xlabel("Date")
ax.set_ylabel("Log(Order Number + 1)")
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
# Express time as days since the first observation
X = ((order_numbers["date"] - order_numbers["date"].min()).dt.days.to_numpy().reshape(-1, 1))
# Fit linear regression model to log-transformed order numbers and save fitted values
model = LinearRegression()
model.fit(X, order_numbers["log_order_number"])
order_numbers["fitted_log_order_number"] = model.predict(X)
# Plot fitted log order numbers over time
fig, ax = plt.subplots(figsize=(14, 6))
ax.plot(order_numbers["date"], order_numbers["fitted_log_order_number"], marker=".", linestyle="-")
ax.set_title("Fitted Log Order Number Trend")
ax.set_xlabel("Date")
ax.set_ylabel("Fitted Log(Order Number + 1)")
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
# Reverse log transformation
order_numbers["fitted_order_number"] = np.expm1(order_numbers["fitted_log_order_number"])
# Match order numbers with active users by date
order_numbers = order_numbers.merge(transaction_data[["date", "weekly_active_users_index"]], on="date", how="left")
# Calculate fitted orders per active user
order_numbers["log_orders_per_active_user"] = (order_numbers["fitted_order_number"] / order_numbers["weekly_active_users_index"])
# Plot fitted orders per active user over time
fig, ax = plt.subplots(figsize=(14, 6))
ax.plot(order_numbers["date"], order_numbers["log_orders_per_active_user"], marker=".", linestyle="-")
ax.set_title("Fitted Orders per Active User Over Time")
ax.set_xlabel("Date")
ax.set_ylabel("Orders per Active User")
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
Number of suspicious order-number observations: 213
| date | order_number | order_number_diff | invalid_order_sequence | |
|---|---|---|---|---|
| 11 | 2018-03-22 | 35482998 | -1310484.0 | True |
| 15 | 2018-04-03 | 35559751 | -3033672.0 | True |
| 23 | 2018-05-08 | 36368212 | -16150.0 | True |
| 26 | 2018-05-13 | 36408976 | -192112.0 | True |
| 28 | 2018-05-19 | 36569135 | -174356.0 | True |
| ... | ... | ... | ... | ... |
| 733 | 2022-04-17 | 79208916 | -920388.0 | True |
| 735 | 2022-04-21 | 80010988 | -458500.0 | True |
| 736 | 2022-04-22 | 78270297 | -1740691.0 | True |
| 739 | 2022-04-24 | 11337408 | -69249743.0 | True |
| 756 | 2022-06-28 | 82632637 | -355201.0 | True |
213 rows × 4 columns
Transaction Data Analysis and Normalisation¶
I examine the transaction dataset for missing and duplicate dates, then several normalised metrics are then constructed, including spending and orders per active user, as well as spending per order. Normalising by active users helps distinguish changes in business performance from changes in the overall customer base. Logarithmic transformations are then applied to selected metrics to normalize variance. The resulting variables are plotted to examine their behaviour over time.
# Check for missing and duplicate dates
expected_dates = pd.date_range(
transaction_data["date"].min(),
transaction_data["date"].max(),
freq="D"
)
missing_dates = expected_dates.difference(transaction_data["date"].dropna().unique())
duplicate_dates = transaction_data[transaction_data["date"].duplicated(keep=False)]
print(f"Missing dates: {len(missing_dates)}")
print(f"Rows with duplicate dates: {len(duplicate_dates)}")
# Calculate spending and orders per active user
spend = transaction_data["total_spend_index"]
orders = transaction_data["gross_orders_index"]
users = transaction_data["weekly_active_users_index"]
transaction_data["spend_per_active_user_index"] = spend / users
transaction_data["orders_per_active_user_index"] = orders / users
transaction_data["spend_per_order_index"] = spend / orders
# Apply log transformations to selected variables
log_columns = [
"spend_per_active_user_index",
"orders_per_active_user_index"
]
transaction_data[[f"log_{col}" for col in log_columns]] = np.log1p(transaction_data[log_columns])
# Select variables to plot
transaction_columns = [
"total_spend_index",
"gross_orders_index",
"weekly_active_users_index",
"spend_per_active_user_index",
"orders_per_active_user_index",
"spend_per_order_index",
"log_spend_per_active_user_index",
"log_orders_per_active_user_index"
]
# Plot each variable over time
fig, axes = plt.subplots(len(transaction_columns), 1, figsize=(14, 16))
for ax, col in zip(axes, transaction_columns):
ax.plot(transaction_data["date"], transaction_data[col])
ax.set_title(col)
ax.set_xlabel("Date")
ax.set_ylabel("Index")
plt.tight_layout()
plt.show()
Missing dates: 0 Rows with duplicate dates: 0
Reported Revenue Exploration¶
Reported quarterly revenue is plotted over time to give context about the historical performance of ABC-Retail.
# Plot reported revenue
plt.figure(figsize=(12, 6))
plt.plot(reported_data["end_date"], reported_data["revenue_index"],marker="o", linestyle="-")
plt.xlabel("Reporting Period End Date")
plt.ylabel("Revenue Index")
plt.title("ABC-Retail Reported Quarterly Revenue")
plt.grid(True, alpha=0.3)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
Quarterly Aggregation and Feature Engineering¶
Daily transaction and order-number observations are aggregated to match the reporting periods used in the revenue dataset. Average transaction metrics are calculated for each period, while revenue is normalised by the number of days in the reporting period to account the for differences in period length. Lagged versions of the resulting variables are then constructed so that the model uses only past information in order to make true forecasts. The first four observations are excluded to remove an initial period of high variability. Finally, the dataset is restricted to only the variables selected for modelling.
# Transaction variables to aggregate
keep_columns = [
"log_spend_per_active_user_index",
"log_orders_per_active_user_index",
"spend_per_order_index",
"weekly_active_users_index"
]
# Aggregate daily data into quarterly reporting periods
def aggregate_period(period):
start = period["start_date"]
end = period["end_date"]
# Filter transaction and order data for the period
daily = transaction_data[transaction_data["date"].between(start, end)]
orders = order_numbers[order_numbers["date"].between(start, end)]
# Calculate period-level variables
return {
"period": period["period"],
"start_date": start,
"end_date": end,
"period_days": (end - start).days + 1,
"revenue_per_day_index": (period["revenue_index"] / ((end - start).days + 1)),
# Calculate mean transaction metrics
**{f"{col}_mean": daily[col].mean() for col in keep_columns},
# Calculate change in fitted log orders per active user
"log_order_numbers_per_active_user_index_mean": (
(orders["log_orders_per_active_user"].iloc[-1]
- orders["log_orders_per_active_user"].iloc[0])
/ (end - start).days
if not orders.empty else np.nan
)
}
# Apply aggregation to all reporting periods
quarterly_data = pd.DataFrame([aggregate_period(period) for _, period in reported_data.iterrows()])
# Define variables for which to calculate lagged values
lag_columns = [
"revenue_per_day_index",
"log_spend_per_active_user_index_mean",
"log_orders_per_active_user_index_mean",
"spend_per_order_index_mean",
"weekly_active_users_index_mean",
"log_order_numbers_per_active_user_index_mean"
]
# Create one-period lags of selected variables
quarterly_data[[f"{col}_lag1" for col in lag_columns]] = (quarterly_data[lag_columns].shift(1))
# Remove the first four observations to get rid of noise
quarterly_data = quarterly_data.iloc[4:].reset_index(drop=True)
#Keeping only the relevant columns for forecasting
columns = [
"period",
"start_date",
"end_date",
"period_days",
"revenue_per_day_index",
"revenue_per_day_index_lag1",
"log_spend_per_active_user_index_mean_lag1",
"log_orders_per_active_user_index_mean_lag1",
"spend_per_order_index_mean_lag1",
"weekly_active_users_index_mean_lag1",
"log_order_numbers_per_active_user_index_mean_lag1"
]
quarterly_data = quarterly_data[columns]
# Display aggregated dataset
display(quarterly_data)
| period | start_date | end_date | period_days | revenue_per_day_index | revenue_per_day_index_lag1 | log_spend_per_active_user_index_mean_lag1 | log_orders_per_active_user_index_mean_lag1 | spend_per_order_index_mean_lag1 | weekly_active_users_index_mean_lag1 | log_order_numbers_per_active_user_index_mean_lag1 | |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 2019 Q1 | 2019-01-01 | 2019-02-28 | 59 | 1.994808 | 2.509524 | 0.521897 | 0.542169 | 0.983021 | 18.732037 | -5548.881083 |
| 1 | 2019 Q2 | 2019-03-01 | 2019-06-30 | 122 | 2.410673 | 1.994808 | 0.424892 | 0.464220 | 0.918930 | 23.945946 | -4605.100062 |
| 2 | 2019 Q3 | 2019-07-01 | 2019-08-31 | 62 | 2.524421 | 2.410673 | 0.501468 | 0.505041 | 1.012522 | 30.874044 | -3227.726468 |
| 3 | 2019 Q4 | 2019-09-01 | 2019-12-31 | 122 | 2.950387 | 2.524421 | 0.498811 | 0.512969 | 0.991109 | 39.630936 | -1824.885090 |
| 4 | 2020 Q1 | 2020-01-01 | 2020-02-29 | 60 | 2.467723 | 2.950387 | 0.536380 | 0.541652 | 0.999375 | 52.064994 | -1769.192129 |
| 5 | 2020 Q2 | 2020-03-01 | 2020-06-30 | 122 | 2.375317 | 2.467723 | 0.436335 | 0.499597 | 0.852306 | 69.068976 | -2752.875922 |
| 6 | 2020 Q3 | 2020-07-01 | 2020-08-31 | 62 | 3.827806 | 2.375317 | 0.528327 | 0.592248 | 0.855006 | 94.826958 | -1405.401616 |
| 7 | 2020 Q4 | 2020-09-01 | 2020-12-31 | 122 | 3.998066 | 3.827806 | 0.588742 | 0.639253 | 0.898283 | 125.789196 | -809.868670 |
| 8 | 2021 Q1 | 2021-01-01 | 2021-02-28 | 59 | 3.674803 | 3.998066 | 0.640940 | 0.690563 | 0.905386 | 147.784366 | -185.717809 |
| 9 | 2021 Q2 | 2021-03-01 | 2021-06-30 | 122 | 3.798199 | 3.674803 | 0.597299 | 0.676427 | 0.847538 | 158.865911 | -131.032055 |
| 10 | 2021 Q3 | 2021-07-01 | 2021-08-31 | 62 | 3.817867 | 3.798199 | 0.694960 | 0.723006 | 0.950824 | 177.164324 | -194.048343 |
| 11 | 2021 Q4 | 2021-09-01 | 2021-12-31 | 122 | 4.528221 | 3.817867 | 0.673324 | 0.722844 | 0.908642 | 188.466264 | 14.245167 |
| 12 | 2022 Q1 | 2022-01-01 | 2022-02-28 | 59 | 3.686570 | 4.528221 | 0.717735 | 0.740452 | 0.964565 | 201.788035 | -89.287462 |
| 13 | 2022 Q2 | 2022-03-01 | 2022-05-31 | 92 | 4.447105 | 3.686570 | 0.633843 | 0.668732 | 0.943016 | 222.086359 | -258.035930 |
| 14 | 2022 Q3 | 2022-06-01 | 2022-08-31 | 92 | 3.566118 | 4.447105 | 0.719219 | 0.696887 | 1.064628 | 231.458325 | 53.666600 |
Correlation Analysis¶
I calculated a Pearson correlation matrix for the quarterly variables and visualised using a heatmap. This helps identify relationships between potential predictors and the revenue target, as well as possible multicollinearity between explanatory variables. We can see that there is some significant multicoliearity care must be taken as to which predictors are used.With this in mind I chose the highest correlations with revenue_per_day (log_orders_per_active_user_index_mean_lag1 and weekly_active_users_index_mean_lag1) as potential model predictors.
# Select numerical variables for correlation analysis
distributed_lags = quarterly_data.iloc[:, 4:]
# Calculate Pearson correlation coefficients
correlation_matrix = distributed_lags.corr(method="pearson")
# Visualize the correlation matrix using a heatmap
plt.figure(figsize=(12, 9))
sns.heatmap(
correlation_matrix,
annot=True,
cmap="coolwarm",
vmin=-1,
vmax=1,
center=0,
fmt=".2f",
square=True
)
plt.title("Correlation Matrix of Quarterly Variables")
plt.tight_layout()
plt.show()
display(quarterly_data.head())
| period | start_date | end_date | period_days | revenue_per_day_index | revenue_per_day_index_lag1 | log_spend_per_active_user_index_mean_lag1 | log_orders_per_active_user_index_mean_lag1 | spend_per_order_index_mean_lag1 | weekly_active_users_index_mean_lag1 | log_order_numbers_per_active_user_index_mean_lag1 | |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 2019 Q1 | 2019-01-01 | 2019-02-28 | 59 | 1.994808 | 2.509524 | 0.521897 | 0.542169 | 0.983021 | 18.732037 | -5548.881083 |
| 1 | 2019 Q2 | 2019-03-01 | 2019-06-30 | 122 | 2.410673 | 1.994808 | 0.424892 | 0.464220 | 0.918930 | 23.945946 | -4605.100062 |
| 2 | 2019 Q3 | 2019-07-01 | 2019-08-31 | 62 | 2.524421 | 2.410673 | 0.501468 | 0.505041 | 1.012522 | 30.874044 | -3227.726468 |
| 3 | 2019 Q4 | 2019-09-01 | 2019-12-31 | 122 | 2.950387 | 2.524421 | 0.498811 | 0.512969 | 0.991109 | 39.630936 | -1824.885090 |
| 4 | 2020 Q1 | 2020-01-01 | 2020-02-29 | 60 | 2.467723 | 2.950387 | 0.536380 | 0.541652 | 0.999375 | 52.064994 | -1769.192129 |
Trend and Seasonal Regression Model¶
I developed a linear regression model using time and quarterly seasonal indicators. Time is represented as the number of days since the first training observation, while quarterly dummy variables account for seasonal effects, using Q1 as the reference category. The model is evaluated using in-sample R², and its fitted values are used to examine the estimated revenue trend. The same time and seasonal structure is then applied to the unseen reporting period to generate an out-of-sample revenue prediction.
# Convert dates to datetime
quarterly_data["start_date"] = pd.to_datetime(quarterly_data["start_date"])
# Define time as days since first training observation
first_date = quarterly_data["start_date"].min()
quarterly_data["time"] = (
quarterly_data["start_date"] - first_date
).dt.days
# Extract quarter
quarterly_data["quarter"] = (
quarterly_data["period"]
.astype(str)
.str.extract(r"Q([1-4])")[0]
.astype(int)
)
# Create seasonal dummy variables explicitly
seasonal_dummies = pd.DataFrame({
"Q_2": (quarterly_data["quarter"] == 2).astype(int),
"Q_3": (quarterly_data["quarter"] == 3).astype(int),
"Q_4": (quarterly_data["quarter"] == 4).astype(int)
}, index=quarterly_data.index)
# Define X and y
X = pd.concat([
quarterly_data[["time"]],
seasonal_dummies
], axis=1)
y = quarterly_data["revenue_per_day_index"]
# Fit model
trend_model = LinearRegression()
trend_model.fit(X, y)
# Calculate fitted values and R²
y_pred = trend_model.predict(X)
r2 = r2_score(y, y_pred)
# Display coefficients
coefficients = pd.DataFrame({
"Feature": X.columns,
"Coefficient": trend_model.coef_
})
print(f"Intercept: {trend_model.intercept_:.4f}")
print(f"R²: {r2:.4f}")
display(coefficients)
# Add fitted values to dataframe
quarterly_data["revenue_trend"] = y_pred
# Test dataset
# Convert dates to datetime
reported_data_test["start_date"] = pd.to_datetime(
reported_data_test["start_date"]
)
reported_data_test["end_date"] = pd.to_datetime(
reported_data_test["end_date"]
)
# Extract quarter
reported_data_test["quarter"] = (
reported_data_test["period"]
.astype(str)
.str.extract(r"Q([1-4])")[0]
.astype(int)
)
# Create seasonal dummy variables explicitly
test_seasonal_dummies = pd.DataFrame({
"Q_2": (reported_data_test["quarter"] == 2).astype(int),
"Q_3": (reported_data_test["quarter"] == 3).astype(int),
"Q_4": (reported_data_test["quarter"] == 4).astype(int)
}, index=reported_data_test.index)
# Calculate time relative to training dataset
reported_data_test["time"] = (
reported_data_test["start_date"] - first_date
).dt.days
# Construct test X
test_X = pd.concat([
reported_data_test[["time"]],
test_seasonal_dummies
], axis=1)
# Match training column order
test_X = test_X[X.columns]
# Generate predictions
y_test_pred = trend_model.predict(test_X)
# Calculate number of days in each test period
reported_data_test["period_days"] = (
reported_data_test["end_date"] -
reported_data_test["start_date"]
).dt.days + 1
# Calculate predicted revenue
predicted_revenue = (
y_test_pred * reported_data_test["period_days"].to_numpy()
)
actual_revenue_total = reported_data_test["revenue_index"].iloc[0]
results = pd.DataFrame({
"Metric": ["Predicted total revenue", "Actual total revenue"],
"Value": [predicted_revenue, actual_revenue_total]
})
display(results)
Intercept: 2.0580 R²: 0.7997
| Feature | Coefficient | |
|---|---|---|
| 0 | time | 0.001639 |
| 1 | Q_2 | 0.204757 |
| 2 | Q_3 | 0.193361 |
| 3 | Q_4 | 0.770170 |
| Metric | Value | |
|---|---|---|
| 0 | Predicted total revenue | [612.723255867109] |
| 1 | Actual total revenue | 512.079789 |
Multiple Linear Regression Without Seasonal Effects¶
I fitted a multiple linear regression model using lagged average spending per active user and average weekly active users as predictors of revenue per day. In-sample R² is calculated to assess the model’s explanatory performance. VIF is also calculated to assess potential multicollinearity between the predictors, and although we have some multicolinearity, it doesn't necesarliy appear to be prohibitive (VIF < 10). Finally, the model is applied to the unseen reporting period, and predicted total revenue is compared with the actual reported value.
# Define target and predictors
target = "revenue_per_day_index"
features = [
"log_spend_per_active_user_index_mean_lag1",
"weekly_active_users_index_mean_lag1"
]
# Prepare training data
train_data = quarterly_data[features + [target]].dropna()
X_train = train_data[features]
y_train = train_data[target]
# Fit model
model = LinearRegression()
model.fit(X_train, y_train)
# Calculate and display in-sample R²
y_pred = model.predict(X_train)
r2 = r2_score(y_train, y_pred)
print(f"In-sample R²: {r2:.4f}")
# Display coefficients
coefficients = pd.DataFrame({
"Feature": features,
"Coefficient": model.coef_
})
display(coefficients)
# Calculate and display VIF
vif = pd.DataFrame({
"Variable": X_train.columns,
"VIF": [
variance_inflation_factor(X_train.values, i)
for i in range(X_train.shape[1])
]
})
display(vif)
# Prepare test predictors
X_test = quarterly_data.loc[
[quarterly_data.index[-1]], features
].reset_index(drop=True)
# Generate prediction
predicted_revenue_per_day = model.predict(X_test)[0]
# Calculate test period duration
test_start = pd.to_datetime(reported_data_test["start_date"].iloc[0])
test_end = pd.to_datetime(reported_data_test["end_date"].iloc[0])
test_period_days = (test_end - test_start).days + 1
# Calculate predicted and actual total revenue
predicted_revenue = predicted_revenue_per_day * test_period_days
# Display revenue comparison
results = pd.DataFrame({
"Metric": ["Predicted total revenue", "Actual total revenue"],
"Value": [predicted_revenue, actual_revenue_total]
})
display(results)
In-sample R²: 0.7174
| Feature | Coefficient | |
|---|---|---|
| 0 | log_spend_per_active_user_index_mean_lag1 | -1.254632 |
| 1 | weekly_active_users_index_mean_lag1 | 0.010417 |
| Variable | VIF | |
|---|---|---|
| 0 | log_spend_per_active_user_index_mean_lag1 | 6.119404 |
| 1 | weekly_active_users_index_mean_lag1 | 6.119404 |
| Metric | Value | |
|---|---|---|
| 0 | Predicted total revenue | 529.183511 |
| 1 | Actual total revenue | 512.079789 |
Multiple Linear Regression With Seasonal Effects¶
I then extended the baseline multiple regression model by incorporating quarterly seasonal dummy variables alongside the two lagged performance predictors. This allows the model to account for seasonal differences in revenue while retaining information about spending and customer activity. Q1 is used as the reference quarter, with Q2, Q3, and Q4 represented by separate binary indicators. In-sample R² and regression coefficients are examined to assess the model’s explanatory performance and the contribution of each predictor. The fitted model is then used to predict revenue for the unseen quarter, allowing its performance to be compared with the non-seasonal regression model.
# Define target and predictors
target = "revenue_per_day_index"
features = [
"log_spend_per_active_user_index_mean_lag1",
"weekly_active_users_index_mean_lag1"
]
# Create seasonal dummy variables
seasonal_dummies = pd.DataFrame({
"Q_2": (quarterly_data["quarter"] == 2).astype(int),
"Q_3": (quarterly_data["quarter"] == 3).astype(int),
"Q_4": (quarterly_data["quarter"] == 4).astype(int)
}, index=quarterly_data.index)
# Combine predictors and seasonal variables
X_train = pd.concat([
quarterly_data[features],
seasonal_dummies
], axis=1)
y_train = quarterly_data[target]
# Remove missing observations
train_data = pd.concat([
X_train,
y_train.rename(target)
], axis=1).dropna()
X_train = train_data.drop(columns=target)
y_train = train_data[target]
# Fit seasonal regression model
model = LinearRegression()
model.fit(X_train, y_train)
# Calculate and display in-sample R²
y_pred = model.predict(X_train)
r2 = r2_score(y_train, y_pred)
print(f"In-sample R²: {r2:.4f}")
# Display regression coefficients
coefficients = pd.DataFrame({
"Feature": X_train.columns,
"Coefficient": model.coef_
})
display(coefficients)
# Extract test quarter
test_quarter = int(
reported_data_test["period"]
.astype(str)
.str.extract(r"Q([1-4])")[0]
.iloc[0]
)
# Create seasonal dummy variables for test data
test_seasonal = pd.DataFrame([{
"Q_2": int(test_quarter == 2),
"Q_3": int(test_quarter == 3),
"Q_4": int(test_quarter == 4)
}])
# Extract latest available lagged predictors
test_predictors = quarterly_data.loc[
[quarterly_data.index[-1]], features
].reset_index(drop=True)
# Combine test predictors and seasonal variables
test_X = pd.concat([
test_predictors,
test_seasonal
], axis=1)
# Match training columns and order
test_X = test_X[X_train.columns]
# Generate prediction
predicted_revenue_per_day = model.predict(test_X)[0]
# Calculate test period duration
start_date = pd.to_datetime(reported_data_test["start_date"].iloc[0])
end_date = pd.to_datetime(reported_data_test["end_date"].iloc[0])
test_period_days = (end_date - start_date).days + 1
# Calculate predicted and actual total revenue
predicted_revenue = predicted_revenue_per_day * test_period_days
actual_revenue_total = reported_data_test["revenue_index"].iloc[0]
# Display revenue comparison
results = pd.DataFrame({
"Metric": [
"Predicted total revenue",
"Actual total revenue"
],
"Value": [
predicted_revenue,
actual_revenue_total
]
})
display(results)
In-sample R²: 0.8318
| Feature | Coefficient | |
|---|---|---|
| 0 | log_spend_per_active_user_index_mean_lag1 | -3.401116 |
| 1 | weekly_active_users_index_mean_lag1 | 0.012800 |
| 2 | Q_2 | -0.145657 |
| 3 | Q_3 | 0.136388 |
| 4 | Q_4 | 0.646075 |
| Metric | Value | |
|---|---|---|
| 0 | Predicted total revenue | 589.079849 |
| 1 | Actual total revenue | 512.079789 |
Model Comparison and Evaluation¶
The trend and seasonal model achieved an in-sample R² of 0.7997, indicating a reasonably strong fit based on time and quarterly effects alone. This model, however predicted a total revenue of 612.72 which is fairly far off the actual value of 512.08 (approximately 19.7% overprediction). The non-seasonal multiple regression model performed slightly worse in-sample, with an R² of 0.7174, but predicted a total revenue of 529.18, which is much closer to the actual value (approximately 3.3% overprediction). Adding seasonal variables improved the multiple regression model’s in-sample R² to 0.8318, the highest of the three models. However, its predicted revenue of 589.08 was substantially worse than without seasonal variables (approximately 15.0% overprediction). This suggests that although using seasonality improves the model’s ability to explain the training data, it does not necessarily improve its out-of-sample predictive accuracy. This is consistent with the fact that we have a training set of only 19 observations, making it very easy to overfit to the training data. Overall, the non-seasonal multiple regression model produced the most accurate prediction for the unseen quarter and only used two parameters, so I would likely recommend this for further forecasting.