| Type: | Package |
| Title: | Gamma-Gamma Spend Models with Covariates |
| Version: | 0.1.0 |
| 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/. |
| License: | Apache License (≥ 2) |
| Encoding: | UTF-8 |
| Language: | en-US |
| LazyData: | true |
| Imports: | stats, graphics |
| Suggests: | knitr, rmarkdown, testthat (≥ 3.0.0) |
| VignetteBuilder: | knitr |
| Depends: | R (≥ 3.5) |
| Config/roxygen2/version: | 8.1.1 |
| Config/testthat/edition: | 3 |
| URL: | https://kaloklee.github.io/GammaGammaCov/, https://github.com/kaloklee/GammaGammaCov |
| BugReports: | https://github.com/kaloklee/GammaGammaCov/issues |
| NeedsCompilation: | no |
| Packaged: | 2026-11-12 15:35:25 UTC; kartmanlmde |
| Author: | Ka Lok Lee [aut, cre] |
| Maintainer: | Ka Lok Lee <kaloklee@gmail.com> |
| Repository: | CRAN |
| Date/Publication: | 2026-12-04 17:30:21 UTC |
Negative Log-Likelihood for Equation (6)
Description
Negative Log-Likelihood for Equation (6)
Usage
GGcov_LL(par, data_df)
Arguments
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
|
Value
Scalar negative log-likelihood.
Fit the Equation (6) Model by Maximum Likelihood
Description
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.
Usage
GGcov_MLE(fo, data, subject, level = 0.95)
Arguments
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. |
Value
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 |
Examples
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)
Expected Spend per Transaction
Description
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
Usage
GGcov_expected_spend(fit, newdata, history = NULL)
Arguments
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 |
Details
E(Z_k \mid \cdot) = \frac{p \, (\gamma + B(x))}{p x + q - 1}
e^{w_k \beta'}, \qquad B(x) = \sum_{i=1}^{x} z_i e^{-w_i \beta'},
which requires p x + q > 1 (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
e^{-w\beta'};no past transactions (x = 0, or a customer absent from
history): B(x) = 0, giving the prior expectationp \gamma e^{w_k\beta'} / (q - 1), which requires q > 1;a model without covariates:
e^{w_k\beta'} = 1.
Value
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 (p x + q \le 1).
References
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/
Examples
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)
Internal Optimization for the Equation (6) Model
Description
BFGS on the log scale for p, q and gamma, so an unconstrained method is appropriate.
Usage
GGcov_optim(model_data)
Arguments
model_data |
Data frame prepared by |
Value
The unmodified list returned by optim (internal
scale: log p, log q, log gamma, standardized coefficients), including the
Hessian of the negative log-likelihood.
Plot Observed versus Fitted Average Spend
Description
Compares the observed distribution of each customer's average spend per
transaction, \bar{z}, with the distribution implied by a fitted
gamma-gamma model, as in Figure 3 of Fader and Hardie (2013).
Usage
GGcov_plot_avg_spend(
fit,
data,
max_customers = 5000,
n = 400,
xlab = "Average spend per transaction",
ylab = "Density",
main = "Observed versus fitted average spend"
)
Arguments
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. |
Details
For a customer with x transactions, the fitted density of
\bar{z} is the average over customers of
f(\bar{z}) = \frac{1}{c} \,
\frac{\Gamma(k + q)}{\Gamma(k)\Gamma(q)} \,
\frac{\gamma^q (\bar{z}/c)^{k-1}}{(\gamma + \bar{z}/c)^{k+q}},
where a_1 = \sum_j e^{w_j\beta'}, a_2 = \sum_j e^{2 w_j\beta'},
k = p a_1^2 / a_2 and c = a_2 / (x a_1).
If the customer's covariate effect is the same on every transaction (no covariates, or static covariates), then
k = p xand 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
\nu_0), the Satterthwaite-Welch approximation, which gives the expression above. The plot says so when this approximation is used.
Value
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).
References
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.
Examples
fit <- GGcov_MLE(
Price ~ discount + gender + channel,
data = spend_data_sample,
subject = "Id"
)
GGcov_plot_avg_spend(fit, spend_data_sample)
Plot the Mixing Distribution of a Fitted Gamma-Gamma Model
Description
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.
Usage
GGcov_plot_mixing(
fit,
coverage = 0.999,
n = 400,
xlab = expression(nu[0]),
ylab = "Density",
main = "Mixing distribution",
...
)
Arguments
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 |
Details
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.
Value
Invisibly returns a list with the mean (q / gamma) and
median of the mixing distribution.
Examples
fit <- GGcov_MLE(
Price ~ discount + gender + channel,
data = spend_data_sample,
subject = "Id"
)
GGcov_plot_mixing(fit)
Print a Fitted Equation (6) Model
Description
Print a Fitted Equation (6) Model
Usage
## S3 method for class 'GGcov'
print(x, digits = 4, ...)
Arguments
x |
A fitted model of class |
digits |
Number of significant digits to print. Default 4. |
... |
Unused. |
Value
x, invisibly.
Examples
fit <- GGcov_MLE(Price ~ 1, data = spend_data_sample, subject = "Id")
print(fit, digits = 3)
Simulated Customer Spend Data
Description
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.
Usage
spend_data
spend_data_sample
Format
A data frame with one row per transaction and 5 variables:
- Id
Customer identifier.
- Price
Amount spent in the transaction (strictly positive).
- discount
Time-varying numeric covariate: the discount applied to the transaction, between 0 and 1.
- gender
Time-invariant factor with 2 levels (
"female","male"), repeated on each of the customer's rows. The first level is the reference.- channel
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.
Details
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).
Source
Simulated; see data-raw/spend_data.R.
References
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
Examples
head(spend_data)