CLV (BTYD Model Prep)
Customer-lifetime-value (BTYD) model input preparation.
This module adapts OpenRetailScience transaction data into the per-customer summary
frame consumed by the "buy-till-you-die" models in
pymc-marketing <https://www.pymc-marketing.io/>_ — ParetoNBDModel (churn and
purchase frequency) and GammaGammaModel (per-transaction spend).
The summary follows the standard BTYD convention, where each customer is "born" at their
first purchase and observed until observation_period_end:
frequency— number of repeat purchase occasions (total occasions minus one). An occasion is a distinct calendar day with positive net spend (returns-only days excluded).recency— time from the first purchase to the last purchase.T— the customer's "age": time from the first purchase toobservation_period_end.monetary_value— mean spend across the repeat purchases (excludes the first, per the Gamma-Gamma assumption).NaNfor one-time buyers (excluded byrepeat_buyers).
recency and T are whole calendar days converted to fractional period units ("day",
"week", or "month"; a month is a fixed 365.25/12 days), so 10 days is 1.43 weeks.
The first purchase is always the earliest transaction in the supplied data, exactly as
pymc_marketing.clv.rfm_summary treats it. A customer who was already active before the
data window is therefore treated as born at the window's start — a known limitation of a
truncated observation period, not something this adapter corrects.
CLVStats
Prepares the per-customer BTYD summary for pymc-marketing CLV models.
Aggregates transaction data into the frequency / recency / T /
monetary_value summary that ParetoNBDModel and GammaGammaModel consume.
Results are accessible via the table attribute (ibis Table) or the df property
(materialized pandas DataFrame); :meth:sample narrows the summary to a subset of customers to
fit on. See the module docstring for column definitions.
Construction runs a few small validation queries; the per-customer summary stays lazy until
df is first read, then is cached. A :meth:sample result runs no queries until its own
df is read.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame | Table
|
Transaction data with the |
required |
period
|
str
|
The time unit for |
'week'
|
observation_period_end
|
str | date | None
|
The end of the
observation window, from which each customer's age |
None
|
customer_attributes
|
DataFrame | Table | None
|
A per-customer table (one
row per |
None
|
one_hot_col
|
str | list[str] | None
|
Column(s) of |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If required columns are missing, if |
Source code in openretailscience/experimental/clv.py
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 | |
covariate_cols
property
The covariate columns attached to the summary (customer_attributes and one-hot dummies).
Every column beyond the base BTYD summary, ready to pass as purchase_covariate_cols /
dropout_covariate_cols to ParetoNBDModel.
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: The covariate column names in summary order (empty if none were requested). |
df
cached
property
Returns the materialized BTYD summary as a pandas DataFrame.
The customer_id is a column (not the index) so the frame can be passed straight
to ParetoNBDModel / GammaGammaModel, which expect it as a column.
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: One row per customer, sorted by |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a covariate column is NULL for any customer (a customer missing from
|
pymc_time_unit
property
The pymc-marketing time_unit matching this summary's period ("D"/"W"/"M").
Pass as the time_unit of GammaGammaModel.expected_customer_lifetime_value: its future_t
is in months, but time_unit (the unit of recency and T) defaults to "D", so omitting
it for a weekly or monthly summary silently misreads the horizon by ~7x or ~30x.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
|
repeat_buyers
property
The GammaGamma-ready subset of :attr:df — the repeat buyers (frequency > 0, index reset).
One-time buyers (NaN monetary_value) are excluded; GammaGammaModel cannot fit them. No
spend filter is needed because monetary_value is always positive here. Warns (UserWarning)
if |Pearson r| between frequency and monetary_value exceeds 0.15, breaking
GammaGamma's independence assumption.
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: The |
__init__(data, *, period='week', observation_period_end=None, customer_attributes=None, one_hot_col=None)
Initializes and computes the BTYD summary.
Source code in openretailscience/experimental/clv.py
sample(*, n=None, frac=None, random_state=42)
Draws a random sample of customers, as a new :class:CLVStats over the same summary.
Fit on clv.sample(n=50_000), score on clv.df. Customers are selected by a deterministic
hash of customer_id salted with random_state.
- A draw repeats only on the same engine at the same version: the key is the backend's own hash,
and DuckDB's
HASHchanges between releases. Record the drawn ids, not the seed, to reproduce a fit. Backends with no Ibishashrule (SQLite, MySQL, Trino, Athena) raiseOperationNotDefinedErrorwhen :attr:dfis read. - Draws nest rather than partition: at one
random_state,sample(frac=0.2)is a subset ofsample(frac=0.8)and re-sampling a sample returns it unchanged. A differentrandom_statere-draws independently but still overlaps, so neither gives a disjoint train/holdout split.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int | None
|
Number of customers to draw; every customer if it exceeds the
population. Mutually exclusive with |
None
|
frac
|
float | None
|
Share of customers to draw, in [1e-6, 1]. Decided per
customer, so the count lands near |
None
|
random_state
|
int
|
Salt for the selection hash. Defaults to 42. |
42
|
Returns:
| Name | Type | Description |
|---|---|---|
Self |
Self
|
A |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If both or neither of |