| Title: | Gamma-Gamma Spend Models with Covariates |
|---|---|
| Description: | Maximum likelihood estimation of the gamma-gamma model of spend per transaction, with time-varying and time-invariant covariates and unobserved cross-sectional heterogeneity, following Fader and Hardie (2024) <https://brucehardie.com/notes/045/>. |
| Authors: | Ka Lok Lee [aut, cre] |
| Maintainer: | Ka Lok Lee <[email protected]> |
| License: | Apache License (>= 2) |
| Version: | 0.1.0 |
| Built: | 2026-12-04 19:56:07 UTC |
| Source: | https://github.com/cran/GammaGammaCov |
Computes the expected spend on future transactions from a fitted gamma-gamma model, given each customer's observed history. For a customer with x past transactions (spends z_1, ..., z_x and covariates w_1, ..., w_x) and a future transaction with covariates w_k, the expected spend is
GGcov_expected_spend(fit, newdata, history = NULL)GGcov_expected_spend(fit, newdata, history = NULL)
fit |
A fitted model of class |
newdata |
Data frame with one row per future transaction to predict: the subject column and the covariates (original, unstandardized values; factors are coded as in the fit) in effect for that transaction. |
history |
Optional data frame of observed transactions, with the
subject column, the spend column and the covariates, laid out like the
data used for |
which requires (Fader and Hardie, 2024). One formula
covers all cases:
time-varying covariates: each past and future transaction has its own covariate values;
static covariates: repeat each customer's values on every row, and
B(x) reduces to the total spend times ;
no past transactions (x = 0, or a customer absent from
history): B(x) = 0, giving the prior expectation
, which requires q > 1;
a model without covariates: .
A data frame with one row per row of newdata: the subject
identifier, n_trans (number of past transactions used) and
expected_spend. Entries are NA where the formula requires
a condition that fails ().
Fader, P. S., & Hardie, B. G. S. (2024). Incorporating Covariates in the Gamma-Gamma Spend Model (Research Note No. 045). https://brucehardie.com/notes/045/
fit <- GGcov_MLE( Price ~ discount + gender + channel, data = spend_data_sample, subject = "Id" ) last_rows <- spend_data_sample[!duplicated(spend_data_sample$Id, fromLast = TRUE), ] future <- last_rows[1:5, c("Id", "discount", "gender", "channel")] future$discount <- 0.1 GGcov_expected_spend(fit, newdata = future, history = spend_data_sample)fit <- GGcov_MLE( Price ~ discount + gender + channel, data = spend_data_sample, subject = "Id" ) last_rows <- spend_data_sample[!duplicated(spend_data_sample$Id, fromLast = TRUE), ] future <- last_rows[1:5, c("Id", "discount", "gender", "channel")] future$discount <- 0.1 GGcov_expected_spend(fit, newdata = future, history = spend_data_sample)
Negative Log-Likelihood for Equation (6)
GGcov_LL(par, data_df)GGcov_LL(par, data_df)
par |
c(log p, log q, log gamma, beta), optimizer scale. |
data_df |
Data frame: column 1 = id, column 2 = z (outcome, > 0),
columns 3+ = covariates W (none for the null model, in which case
|
Scalar negative log-likelihood.
Fits the model in which, for each subject, the outcomes z_1, ..., z_x are gamma distributed with shape p and rate nu0 * exp(-w_i beta'), and nu0 has a gamma(q, gamma) distribution that is integrated out (equation 6). Covariates are centered and scaled internally for numerical stability, and the results are converted back to the original covariate scale.
GGcov_MLE(fo, data, subject, level = 0.95)GGcov_MLE(fo, data, subject, level = 0.95)
fo |
Formula |
data |
Data frame in long format, one row per subject per period. Row order does not matter. Covariates may be time-varying or static: a static covariate is handled by repeating its value on each of the subject's rows. |
subject |
Character string naming the subject ID column in |
level |
Confidence level for the Wald intervals, strictly between 0 and 1. Default 0.95. |
A list of class "GGcov" containing the optim
results with additional elements. All estimates, standard errors and
bounds are on the original covariate scale (only hessian is on the
internal parameterization):
par |
Estimates: p (shape), q (mixture shape: the shape of the gamma mixing distribution of nu0), gamma (mixture rate: its rate), then the covariate coefficients. |
par_stderr |
Standard errors. For p, q and gamma these use the delta
method, e.g. SE(p) is approximately p * SE(log p). |
par_lower, par_upper
|
Wald limits at |
level |
The confidence level used. |
value |
Negative log-likelihood at the optimum. |
convergence |
optim convergence code (0 = success; any other code triggers a warning). |
hessian |
Hessian on the internal parameterization (log p, log q, log gamma, standardized coefficients). |
center, scale
|
Covariate means and standard deviations used internally. |
terms, xlevels
|
Covariate terms and factor levels, for coding new data. |
spend_name, subject_name
|
Names of the outcome and subject columns
used in the fit, so |
fit <- GGcov_MLE( Price ~ discount + gender + channel, data = spend_data_sample, subject = "Id" ) print(fit) # Null model without covariates fit_null <- GGcov_MLE(Price ~ 1, data = spend_data_sample, subject = "Id") print(fit_null)fit <- GGcov_MLE( Price ~ discount + gender + channel, data = spend_data_sample, subject = "Id" ) print(fit) # Null model without covariates fit_null <- GGcov_MLE(Price ~ 1, data = spend_data_sample, subject = "Id") print(fit_null)
Compares the observed distribution of each customer's average spend per
transaction, , with the distribution implied by a fitted
gamma-gamma model, as in Figure 3 of Fader and Hardie (2013).
GGcov_plot_avg_spend( fit, data, max_customers = 5000, n = 400, xlab = "Average spend per transaction", ylab = "Density", main = "Observed versus fitted average spend" )GGcov_plot_avg_spend( fit, data, max_customers = 5000, n = 400, xlab = "Average spend per transaction", ylab = "Density", main = "Observed versus fitted average spend" )
fit |
A fitted model of class |
data |
The transaction data frame used to fit the model (subject, spend and covariate columns). |
max_customers |
Maximum number of customers used to draw the fitted curve. If there are more customers, a random subset is used for the curve (the observed density always uses all customers). |
n |
Number of points used to draw the curves. |
xlab, ylab, main
|
Axis labels and main title. |
For a customer with transactions, the fitted density of
is the average over customers of
where , ,
and .
If the customer's covariate effect is the same on every
transaction (no covariates, or static covariates), then
and the density is exact.
If the covariates change across a customer's transactions, the
total spend is a sum of gamma variables with different rates, which has
no closed form. The total is then approximated by a gamma distribution
with the same mean and variance (given ), the
Satterthwaite-Welch approximation, which gives the expression above. The plot says so when this approximation is used.
Invisibly, a list with the plotted grid, the observed
and fitted densities, the number of customers (n_customers)
and the number whose covariates vary over time (n_time_varying).
Fader, P. S., & Hardie, B. G. S. (2013). The Gamma-Gamma Model of Monetary Value (Research Note No. 025). https://brucehardie.com/notes/025/
Satterthwaite, F. E. (1946). An approximate distribution of estimates of variance components. Biometrics Bulletin, 2(6), 110-114.
Welch, B. L. (1947). The generalization of "Student's" problem when several different population variances are involved. Biometrika, 34(1/2), 28-35.
Moschopoulos, P. G. (1985). The distribution of the sum of independent gamma random variables. Annals of the Institute of Statistical Mathematics, 37, 541-544.
fit <- GGcov_MLE( Price ~ discount + gender + channel, data = spend_data_sample, subject = "Id" ) GGcov_plot_avg_spend(fit, spend_data_sample)fit <- GGcov_MLE( Price ~ discount + gender + channel, data = spend_data_sample, subject = "Id" ) GGcov_plot_avg_spend(fit, spend_data_sample)
Plots the gamma mixing distribution of nu0 implied by a fitted model: shape q (mixture shape) and rate gamma (mixture rate). The mean (dashed) and median (dotted) are marked with vertical lines and shown in a second title.
GGcov_plot_mixing( fit, coverage = 0.999, n = 400, xlab = expression(nu[0]), ylab = "Density", main = "Mixing distribution", ... )GGcov_plot_mixing( fit, coverage = 0.999, n = 400, xlab = expression(nu[0]), ylab = "Density", main = "Mixing distribution", ... )
fit |
A fitted model of class |
coverage |
Central probability mass of the mixing distribution to show on the x-axis. Default 0.999. |
n |
Number of points used to draw the curve. Default 400. |
xlab, ylab, main
|
Axis labels and title. |
... |
Further arguments passed to |
With covariates in the model, nu0 is the rate for a subject whose covariates are all 0 on the original scale (the fitted coefficients are on the original scale), so the plotted distribution describes that baseline.
Invisibly returns a list with the mean (q / gamma) and
median of the mixing distribution.
fit <- GGcov_MLE( Price ~ discount + gender + channel, data = spend_data_sample, subject = "Id" ) GGcov_plot_mixing(fit)fit <- GGcov_MLE( Price ~ discount + gender + channel, data = spend_data_sample, subject = "Id" ) GGcov_plot_mixing(fit)
Print a Fitted Equation (6) Model
## S3 method for class 'GGcov' print(x, digits = 4, ...)## S3 method for class 'GGcov' print(x, digits = 4, ...)
x |
A fitted model of class |
digits |
Number of significant digits to print. Default 4. |
... |
Unused. |
x, invisibly.
fit <- GGcov_MLE(Price ~ 1, data = spend_data_sample, subject = "Id") print(fit, digits = 3)fit <- GGcov_MLE(Price ~ 1, data = spend_data_sample, subject = "Id") print(fit, digits = 3)
Simulated transaction-level data with covariates, generated from the
gamma-gamma model fitted by GGcov_MLE. The data mimic the
structure of retail transaction logs with covariates, such as the apparel
example in the CLVTools vignette (Bachmann et al., 2025). spend_data
holds 1000 customers; spend_data_sample is a random subset of 300
customers for quick examples.
spend_data spend_data_samplespend_data spend_data_sample
A data frame with one row per transaction and 5 variables:
Customer identifier.
Amount spent in the transaction (strictly positive).
Time-varying numeric covariate: the discount applied to the transaction, between 0 and 1.
Time-invariant factor with 2 levels ("female",
"male"), repeated on each of the customer's rows. The first level
is the reference.
Time-invariant factor with 3 levels ("store",
"web", "app"), repeated on each of the customer's rows. The
first level is the reference.
An object of class data.frame with 858 rows and 5 columns.
Each row is one transaction. The true parameters used to generate the data
are p = 2 (within-customer shape), q = 8 (mixture shape), gamma = 200
(mixture rate), and coefficients -0.8 (discount, per unit), -0.3
(gender male versus female), 0.3 (channel web versus store)
and -0.4 (channel app versus store).
Simulated; see data-raw/spend_data.R.
Bachmann, P., Kuebler, N., Meierer, M., Naef, J., Oblander, E., & Schilter, P. (2025). CLVTools: Tools for Customer Lifetime Value Estimation. R package version 0.12.1. https://github.com/bachmannpatrick/clvtools
head(spend_data)head(spend_data)