---
title: "Bayesian Changepoint Detection on Price Histograms"
subtitle: "Detecting structural changes in pricing regimes"
author: "Pavel Logačev"
date: 2025-06-30
categories: [bayesian, changepoint-detection, pricing]
image: images/thumbnail.png
description: "A product's list price and discounts change rarely, but its daily average price moves constantly with the customer mix. This post detects pricing-regime changes from daily price histograms instead of averages — with a greedy Bayesian algorithm in Rcpp, a simulation study against PELT and E-Divisive, and a case study on real retail transactions."
format:
html:
toc: true
code-fold: true
code-tools: true
df-print: paged
execute:
warning: false
message: false
engine: knitr
editor: visual
---
## Summary
This article demonstrates a Bayesian changepoint detection model applied to synthetic sales data, where product prices change over time. The goal is to detect structural changes in pricing regime based on price histograms over time when the pricing of a product undergoes a meaningful change — such as list price changes, promotions, or changes in the availability of discounts.
We assume that the distribution of prices for a product on any given day depends on the underlying price regime, which changes infrequently. While the price regime (list price and available discounts) remains stable for extended periods, the daily average price can fluctuate substantially due to varying proportions of discounted sales. Therefore, using the average price within a stable regime as a predictor is likely more informative than using volatile daily average prices.
The model determines pricing regimes based on daily price histograms (i.e., distributions of sold units across different price points). The implementation, written in Rcpp, uses discrete parameters, and the changepoint configuration is selected via greedy MAP estimation. It is designed to serve as a modular component within larger hierarchical models for retail analytics.
## Theoretical Model Assumptions
### Scope
The model considered here is designed to detect changepoints in pricing time series data, based on a set of assumptions outlined below. In brief, we assume that the relative frequency of specific prices for a product on a given day depends on the underlying price regime, which is associated with a specific distribution of prices, and changes rather infrequently. Structural changes in pricing regimes are detected based on daily price histograms. Changepoints occur when the pricing of a product undergoes a meaningful change — such as list price changes, promotions, or changes in the availability of discounts.
This section outlines the general model assumptions and logic; the implementation presented below works with a subset of these assumptions.
### Theoretical Generative Model
We model the daily distribution of purchase prices for a product as dependent on the current latent price regime. Within each regime, there is assumed to be one list price, and one or multiple discounts, at which a product can be purchased. Discounts may differ in their availability: for instance, 2% of customers may be eligible for a 10% discount, while only 1% may be eligible for a 20% discount. Price regimes change occasionally. This can be due to changes to the list price, promotions, changes in the magnitude or availability of discounts, or a combination of factors.
We assume that each day belongs to a specific pricing regime. At the end of day $t$, the regime either changes (with probability $\rho_t$) or remains the same (with probability $1 - \rho_t$). Each regime is characterized by a distribution over prices. We assume that it follows a multinomial distribution, such that the distribution of prices in pricing regime $k$ follows $\text{Multinomial}(\tau_k)$.
We encode a segmentation of a price time series of length $T$ using a changepoint indicator vector $z$ of length $T-1$, where $z_t=1$ indicates a changepoint between time $t$ and $t+1$, and $z_t=0$ indicates the absence of a changepoint. As a result, each indicator vector defines a set of $K$ segments, where $t_1^{(k)}$ and $t_2^{(k)}$ are the start and end points of segment $k$: $$
[t_1^{(1)},\, t_2^{(1)}], [t_1^{(2)},\, t_2^{(2)}],\quad \dots,\quad [t_1^{(K)},\, t_2^{(K)}]
$$ When the pricing regime changes, it needs to change *significantly*. Thus, we specify a prior $\theta$ over the difference between two adjacent price regime distributions, where the actual difference may be specified in any number of ways, including a difference between means, the Wasserstein distance, etc.
The complete posterior distribution for the changepoint detection model combines the likelihood of the observed data with the prior distributions over the changepoint configuration and the regime differences. The posterior is given by:
$$
p(z, \theta, \tau \mid y_{1:T})
\propto
p(y_{1:T} \mid z, \theta, \tau)
\cdot
p(z, \theta, \tau)\text{, where }
$$
$$
p(z, \theta, \tau) =
p(z)
\cdot
p(\theta)
\cdot
p(\tau)\text{, and where }
$$
- $p(y_{1:T} \mid z, \theta, \tau)$ is the likelihood of the observed data given the changepoint configuration $z$, the changepoint prior $\theta$, and the regime parameters $\tau$.
- $p(z)$ is the prior probability of the changepoint configuration, modeled as a Bernoulli process with changepoint probability $\rho$.
- $p(\theta)$ is the prior distribution over the magnitude of the price regime change, specified based on domain knowledge.
- $p(\tau)$ is the prior distribution over the regime parameters $\tau$, which incorporates the belief about the differences between successive regimes.
It follows from the structure of the model that the likelihood of $y_{1:T}$ is as below.
$$
p(y_{1:T} \mid z, \theta, \tau) = \prod_{k=1}^{K} \prod_{t=t_1^{(k)}}^{t_2^{(k)}} \text{Multinomial}(y_t \mid \tau_k)
$$
The prior probability $p(z)$ of a changepoint configuration $z$ can be modeled using a Bernoulli process with a changepoint probability $\rho$. Assuming each $z_t$ is an independent Bernoulli random variable, the prior can be expressed as below, where $\rho$ is the probability of a changepoint occurring between any two consecutive time points.
<!-- p(z) = \prod_{t=1}^{T-1} \rho^{z_t} (1-\rho)^{1-z_t} -->
$$
z \sim Bernoulli(\rho)
$$
We further incorporate a prior for the differences between successive $\tau_k$ to capture the belief that changes in pricing regimes are typically abrupt rather than gradual, and that two adjacent pricing regimes need to be substantially different in order to justify positing a regime switch. In other words, it penalizes small differences between any two adjacent pricing regimes. One example specification is as below, where $\delta$ is any kind of distance function calculating *absolute* differences between two distributions.
$$
\delta(\tau_k, \tau_{k+1}) \sim Normal( \theta_{\mu}, \theta_{\sigma} )
$$
## Greedy Changepoint Selection
```{r}
#| label: setup
#| echo: false
library(Rcpp)
source("./source/data_generation.r")
source("./source/greedy_cp_selection.r")
Rcpp::sourceCpp("./source/greedy_cp_selection.cpp")
```
This section demonstrates a Bayesian changepoint detection algorithm for histogram-valued time series. It is based on a greedy search tailored for transactional price data with varying pricing regimes.
- Each day's price distribution is modeled via discretized histograms.
- The changepoint configuration is selected via greedy MAP estimation.
- In the future, parameters may be obtained by means of sampling instead of greedy search. (For instance, using RcppSMC or a custom sampler, e.g., MH).
### Modeling Approach
We model the price distribution of a product as a histogram over discrete price points, because in B2C scenarios, only a few specific prices are available at any given time. Some customer groups may be offered a discount, while most purchase at the list price. Modeling daily means or medians may lose the multimodal structure that matters most for detecting pricing regimes. Histogram-valued representations preserve the full distributional shape, making it possible to detect subtle regime shifts such as list price changes or changes in the availability of discounts.
Each day is represented by a histogram over discrete price points. The time series is transformed into a histogram-valued sequence, represented as a matrix of counts. We assume that pricing follows distinct *pricing regimes*, each associated with a different price distribution. Changes in pricing regime occur when the pricing of a product undergoes a meaningful change — such as list price changes, promotions, or changes in the availability of discounts. Changepoints are defined as time indices where the underlying price distribution regime changes, leading to a change in relative frequency of price points.
#### Data Format
The synthetic data used in this section simulates 800 days of pricing activity, segmented into 10 regimes characterized by different list prices, discounts, and discount availability.
```{r}
#| label: synthetic-data
#| code-summary: "Simulate transactions under 10 pricing regimes"
set.seed(123)
segments <- data.frame(
start_day = c(1, 90, 250, 300, 400, 500, 550, 600, 700, 750),
list_price = c(5, 6, 6, 6, 6, 5.5, 5.5, 5.5, 7, 7),
discount_price = c(4, 4, 5, 5, 5, 4.5, 4.5, 4.5, 2, 2),
discount_percentage = c(.25, .1, .1, .25, .5, .01, .03, .15,.3, .4)
)
n_days <- 800
lambda_qty <- 20
df <- generate_transaction_prices(segments, n_days, lambda_qty, seed = 123)
hist <- compute_price_histogram(df)
actual_changepoints <- segments$start_day[-1]-0.5
knitr::kable(segments, caption = "Price Regimes Overview")
```
The plot below shows the synthetic data set, with the actual changepoints marked with dashed vertical lines. This is the dataset we'll use to test the segmentation algorithm.
```{r}
#| label: synthetic-plot
#| code-summary: "Plot the synthetic data"
#| fig-height: 3
#| fig-width: 10
p_price <- hist$df %>% rename(quantity = qty) %>% filter(quantity > 0) %>%
ggplot(aes(day, price)) + geom_point(aes(size=quantity, alpha = quantity)) +
geom_vline( data = data.frame(x = actual_changepoints, changepoint = "actual"),
aes(xintercept = x, color = changepoint), linetype = "dashed") + theme_bw() +
theme(legend.position = "top")
print(p_price)
```
#### Model Structure
##### Segmentation
We define a segmentation of a histogram-valued time series $h$ of length $T$ as a vector $z \in \{0, 1\}^{T-1}$, where $z_t=1$ indicates a changepoint between indices $t$ and $t+1$, and $0$ indicates its absence. From the index vector $z$, we can derive a segmentation in the form of $\mathcal{S}(z)$, i.e., a set of all segment intervals $[t_1, t_2]$.
The model is intended to select a segmentation $z$ that best balances *(i)* goodness-of-fit (how well the empirical histograms are explained within segments) with *(ii)* model simplicity (how many changepoints are included). The balance is governed by the regularizing parameter $\lambda$, which is selected by optimizing the posterior likelihood over it.
The posterior over a changepoint configuration $z$ is assumed to be:
$$
p(z \mid \mathbf{n}, \lambda) \propto p(\mathbf{n} \mid z) \cdot p(z) \cdot p(\lambda)
$$
#### Likelihood
The data likelihood is computed as the product of likelihoods of the segments defined by the segmentation $\mathcal{S}(z)$, where $\mathbf{n}_{[t_1, t_2]}$ stands for the histogram over the interval $[t_1, t_2]$.
$$
p(\mathbf{n} \mid z) = \prod_{(t_1, t_2) \in \mathcal{S}(z)} p(\mathbf{n}_{[t_1, t_2]})\text{,}
$$
```{=html}
<!--
$$
\mathbf{n_{[t_1, t_2]}} = \sum_{t = t_1}^{t_2} \mathbf{h}_t
$$
-->
```
The likelihood of a segment $\mathbf{n}_{[t_1, t_2]}$ is evaluated at $\hat{p}_i$, the (regularized) maximum likelihood estimate of the relative frequencies of the different price points within the segment. In other words, instead of integrating over the multinomial parameters, we plug in their **maximum likelihood estimate**. Although technically this is not fully Bayesian, the approach can be viewed as an empirical Bayes approximation.
$$
p(\mathbf{n}_{[t_1, t_2]}) = \prod_{i=1}^{K} (\hat{p}_i)^{n_i}
$$
In computing $\hat{p}_i$, we smooth each bin count with a small constant $\epsilon$ to prevent division by zero.
$$
\hat{p}_i = \frac{n_i + \epsilon}{\sum_j (n_j + \epsilon)}
$$
#### Prior
We place a Bernoulli prior on each potential changepoint, to penalize excessive complexity: small $\lambda$ values encourage fewer changepoints, favoring parsimony. In consequence, the model selects the segmentation $z$ that best balances goodness-of-fit with model simplicity, with the balance governed by $\lambda$.
$$
z_t \sim \text{Bernoulli}(\lambda)
$$
### Estimation
To estimate the changepoint configuration $z$, we use a greedy forward search:
1. Start with no changepoints.
2. Iteratively add the changepoint that most increases the penalized posterior.
3. Stop when no further improvement is possible.
This process is repeated for different values of $\lambda$, and the $\lambda$ value that maximizes the resulting posterior is selected using one-dimensional optimization (`optimize()` in R).
### Implementation
The implementation consists of three components:
- A data generator that simulates daily transaction-level price data under piecewise constant pricing regimes (`generate_transaction_prices()`).
- A transformation step that maps transactional data into a histogram matrix (`compute_price_histogram()`).
- A C++ backend that performs fast log-likelihood evaluation and greedy changepoint selection via Rcpp.
### Changepoint Detection Results
In the present example, the algorithm detects the same number of changepoints, and the estimated locations are mostly close to the simulated ones. A formal evaluation against standard baselines follows in the next section. It stands to reason that the accuracy of changepoint identification will depend on the similarity between adjacent segments, as well as segment length.
```{r}
#| label: detect-demo
#| code-summary: "Detect changepoints on the synthetic data"
opt_res <- locate_optimal_changepoints( hist$histogram, max_lambda = 0.3 )
detected_changepoints <- which(opt_res$changepoints) + 0.5
knitr::kable(t(actual_changepoints), caption = "Original Changepoints")
knitr::kable(t(detected_changepoints), caption = "Detected Changepoints")
```
The plot below illustrates the results vis-à-vis the simulation assumptions.
```{r}
#| label: thumbnail-image
#| code-summary: "Plot detected vs. actual changepoints"
#| fig-height: 3
#| fig-width: 10
p_price +
geom_vline( data = data.frame(x = detected_changepoints, changepoint = "detected"),
aes(xintercept = x, color = changepoint), linetype = "dashed") +
scale_color_manual(name = "changepoint", values = c("detected" = "blue", "actual" = "red"),
guide = guide_legend(override.aes = list( linetype = "solid", size = 1))
)
```
### Evaluation
The demonstration above is a single simulation run, evaluated by eye. To quantify performance — and to test the claim that daily average prices are a lossy summary of pricing regimes — we compare the algorithm to a standard baseline: PELT (Killick, Fearnhead & Eckley, 2012), as implemented in the `changepoint` package, applied to the quantity-weighted daily mean price. This corresponds to what a practitioner would typically do with a price time series: collapse each day to its average and run an off-the-shelf changepoint detector on the result. We use both the `cpt.mean` variant (detecting changes in the mean) and the `cpt.meanvar` variant (changes in mean and variance), with the default MBIC penalty.
Because PELT only sees the daily means, we also include a stronger, distribution-aware baseline: E-Divisive (Matteson & James, 2014), as implemented in the `ecp` package, applied to the vectors of daily price *shares*. E-Divisive is a nonparametric method based on the energy statistic, and detects changes in the full multivariate distribution rather than in a summary of it. We use `min.size = 20` and `R = 49` permutations to keep the runtime manageable; on the demonstration dataset, the detected changepoints are identical to those obtained at the default `R = 199`.
```{r}
#| label: eval-helpers
#| code-summary: "Evaluation helpers: detectors, matching, and metrics"
library(changepoint)
library(ecp)
library(parallel)
# Quantity-weighted average price per day, for days with at least one sale.
daily_mean_price <- function(df) {
df %>% summarize( qty = sum(qty), mean_price = sum(price * qty) / sum(qty), .by = day ) %>%
filter(qty > 0) %>% arrange(day) %>% select(day, mean_price)
}
# Days with at least one sale, i.e., the days corresponding to the rows of the histogram matrix.
days_with_sales <- function(df) {
df %>% summarize( qty = sum(qty), .by = day ) %>% filter(qty > 0) %>% arrange(day) %>% pull(day)
}
# Translate boundaries between consecutive rows of the histogram matrix into positions on the day axis.
boundary_position <- function(rows, days) {
rows <- rows[rows >= 1 & rows < length(days)]
(days[rows] + days[rows + 1]) / 2
}
detect_changepoints_histogram <- function(df, max_lambda = 0.3) {
hist <- compute_price_histogram(df)
res <- locate_optimal_changepoints(hist$histogram, max_lambda = max_lambda)
boundary_position(which(res$changepoints), days_with_sales(df))
}
detect_changepoints_means <- function(df, type = c("mean", "meanvar")) {
type <- match.arg(type)
mean_df <- daily_mean_price(df)
fit <- if (type == "mean") { cpt.mean(mean_df$mean_price, method = "PELT")
} else { cpt.meanvar(mean_df$mean_price, method = "PELT") }
boundary_position(cpts(fit), mean_df$day)
}
detect_changepoints_shares <- function(df, min_size = 20, n_perm = 49) {
shares <- df %>% mutate(total = sum(qty), .by = day) %>% filter(total > 0) %>%
mutate(share = qty / total) %>% select(day, price, share) %>%
pivot_wider(names_from = price, values_from = share, values_fill = 0) %>% arrange(day)
fit <- e.divisive(as.matrix(shares[, -1]), sig.lvl = 0.05, R = n_perm, min.size = min_size)
est <- setdiff(fit$estimates, c(1, nrow(shares) + 1))
boundary_position(est - 1, shares$day)
}
# One-to-one matching of detected to actual changepoints (closest pairs first, within tolerance).
changepoint_metrics <- function(detected, actual, tol = 3) {
n_det <- length(detected); n_act <- length(actual)
tp <- 0; errors <- numeric(0)
if (n_det > 0) {
pairs <- expand.grid(i = seq_len(n_det), j = seq_len(n_act)) %>%
mutate(dist = abs(detected[i] - actual[j])) %>%
filter(dist <= tol) %>% arrange(dist)
used_i <- logical(n_det); used_j <- logical(n_act)
for (r in seq_len(nrow(pairs))) {
if (!used_i[pairs$i[r]] && !used_j[pairs$j[r]]) {
used_i[pairs$i[r]] <- used_j[pairs$j[r]] <- TRUE
errors <- c(errors, pairs$dist[r])
}
}
tp <- sum(used_j)
}
precision <- ifelse(n_det > 0, tp / n_det, NA_real_)
recall <- tp / n_act
data.frame( precision = precision, recall = recall,
f1 = ifelse(tp == 0, 0, 2 * precision * recall / (precision + recall)),
loc_error = ifelse(tp > 0, mean(errors), NA_real_),
n_detected = n_det )
}
```
We simulate 50 datasets at each of three sales-volume levels $\lambda_{\text{qty}} \in \{10, 20, 50\}$ (the expected number of transactions per day), keeping the regime structure fixed at the segmentation shown above, so that simulation runs differ only in sampling noise. A detected changepoint counts as correct if it falls within ±3 days of an actual one, with one-to-one matching (closest pairs first). We report precision, recall, F1, and the mean absolute localization error of the matched changepoints.
```{r}
#| label: eval-loop
#| code-summary: "Run the simulation study (4 methods x 3 volumes x 50 datasets)"
n_sims <- 50
volume_levels <- c(10, 20, 50)
sim_grid <- expand_grid(lambda_qty = volume_levels, sim = seq_len(n_sims))
# Forked parallelism; set mc.cores = 1 on Windows.
results <- mcmapply(function(lambda_qty, sim) {
df_sim <- generate_transaction_prices(segments, n_days, lambda_qty, seed = sim)
bind_rows(
changepoint_metrics(detect_changepoints_histogram(df_sim), actual_changepoints) %>%
mutate(method = "Histograms (greedy search)"),
changepoint_metrics(detect_changepoints_shares(df_sim), actual_changepoints) %>%
mutate(method = "Price shares (E-Divisive)"),
changepoint_metrics(detect_changepoints_means(df_sim, "mean"), actual_changepoints) %>%
mutate(method = "Daily means (PELT, mean)"),
changepoint_metrics(detect_changepoints_means(df_sim, "meanvar"), actual_changepoints) %>%
mutate(method = "Daily means (PELT, mean & variance)")
) %>% mutate(lambda_qty = lambda_qty)
}, sim_grid$lambda_qty, sim_grid$sim, SIMPLIFY = FALSE, mc.cores = 6) %>%
bind_rows()
results_summary <- results %>%
summarize(
precision = mean(precision, na.rm = TRUE), recall = mean(recall),
f1_sd = sd(f1), f1 = mean(f1),
loc_error = mean(loc_error, na.rm = TRUE), n_detected = mean(n_detected),
.by = c(lambda_qty, method)
) %>%
mutate( method = factor(method, levels = c("Histograms (greedy search)", "Price shares (E-Divisive)",
"Daily means (PELT, mean)",
"Daily means (PELT, mean & variance)")) ) %>%
arrange(lambda_qty, method) %>%
transmute(
`sales/day` = lambda_qty, method,
precision = sprintf("%.2f", precision), recall = sprintf("%.2f", recall),
`F1 (sd)` = sprintf("%.2f (%.2f)", f1, f1_sd),
`loc. error (days)` = sprintf("%.1f", loc_error),
`detected (of 9)` = sprintf("%.1f", n_detected)
)
knitr::kable(results_summary, caption = "Detection performance by method and sales volume: means over 50 simulated datasets per volume level (matching tolerance: ±3 days)")
```
The pattern is consistent across sales volumes. PELT on daily means is perfectly precise — every changepoint it reports is real, and localized exactly — but its recall is stuck at 4 of 9 changepoints regardless of volume: it finds the changes that shift the daily mean, and it is blind to the ones that mainly alter the composition of prices, such as a discount becoming more or less available. Additional data does not help, because the information it would need is not in the mean. (Both PELT variants produce identical results on these data.)
The two distribution-aware methods, in contrast, recover most changepoints at every volume level, and improve as sales volume grows. Between them, the comparison is a trade-off at essentially tied F1 scores: the histogram-based algorithm has the higher recall throughout (0.80 vs. 0.74 at 10 sales per day, 0.96 vs. 0.89 at 50), while E-Divisive is the more conservative one, with higher precision and fewer false positives. Both localize matched changepoints to well within half a day on average, and both concentrate their remaining misses on the subtlest regime changes, such as the change in discount availability from 1% to 3% on day 550. The greedy algorithm is also considerably faster per series (about 0.3 s vs. 1.7 s here, with E-Divisive's permutation count already reduced), which matters when segmenting a large product assortment. Beyond the metrics, the model-based formulation yields segment-level price distributions that can serve directly as components of larger models, which is the intended use.
The plot below overlays the changepoints detected by the competing approaches on the demonstration dataset from above. PELT finds the four prominent shifts in the daily mean and nothing else; the two distribution-aware methods additionally recover most of the composition-only changes.
```{r}
#| label: eval-plot
#| code-summary: "Overlay detections from all methods"
#| fig-height: 3.2
#| fig-width: 10
pelt_changepoints <- detect_changepoints_means(df, "mean")
edivisive_changepoints <- detect_changepoints_shares(df)
p_price +
geom_vline( data = data.frame(x = detected_changepoints, changepoint = "detected (histograms)"),
aes(xintercept = x, color = changepoint), linetype = "dashed") +
geom_vline( data = data.frame(x = edivisive_changepoints, changepoint = "detected (price shares)"),
aes(xintercept = x, color = changepoint), linetype = "dotdash") +
geom_vline( data = data.frame(x = pelt_changepoints, changepoint = "detected (daily means)"),
aes(xintercept = x, color = changepoint), linetype = "dotted") +
scale_color_manual(name = "changepoint",
values = c("detected (histograms)" = "blue", "detected (price shares)" = "purple",
"detected (daily means)" = "darkgreen", "actual" = "red"),
guide = guide_legend(override.aes = list( linetype = "solid", size = 1))
)
```
### Case Study: Online Retail Data
As a reality check, we apply the algorithm to two products from the [Online Retail II dataset](https://archive.ics.uci.edu/dataset/502/online+retail+ii) (UCI Machine Learning Repository) — two years of transactions from a UK-based online giftware retailer with a mix of wholesale and retail customers. We picked two of the highest-volume SKUs with visible price variation: *World War 2 Gliders Asstd Designs* (84077) and *Jumbo Bag Red White Spotty* (85099B). There is no ground truth here, so the evaluation is qualitative: do the detected boundaries coincide with visible changes in the price menu?
The code below documents how the transaction data was reduced to the day × price × orders table shipped with this post (cancellations, non-positive prices, and non-product stock codes removed):
```{r}
#| label: retail-provenance
#| eval: false
#| code-summary: "Derivation of the shipped data extract (not evaluated)"
raw <- bind_rows(readxl::read_excel("online_retail_II.xlsx", sheet = 1),
readxl::read_excel("online_retail_II.xlsx", sheet = 2))
retail <- raw %>%
filter(!str_starts(Invoice, "C"), Quantity > 0, Price > 0,
str_detect(StockCode, "^[0-9]{5}[A-Z]?$")) %>%
mutate(date = as.Date(InvoiceDate)) %>%
summarize(orders = n_distinct(Invoice), .by = c(StockCode, date, Price)) %>%
rename(price = Price)
```
Real transaction data requires two adjustments relative to the synthetic setting. First, we count *orders* per price point rather than units: units within a wholesale order are not independent draws from a price distribution, and a single 3,000-unit invoice would otherwise dominate the day it falls on. Second, we aggregate to weekly histograms: at roughly 2 and 7 orders per day, these SKUs are too sparse for daily histograms, but at 10–38 orders per week they are comparable to the sales volumes in the simulation study. We also drop price points accounting for less than 1% of orders, which are one-off manual adjustments.
```{r}
#| label: retail-prep
#| code-summary: "Load the extract and build weekly order histograms"
retail <- read_csv("./data/online_retail_ii_skus.csv", show_col_types = FALSE)
prepare_weekly <- function(retail, sku_id) {
sku_df <- retail %>% filter(sku == sku_id) %>% arrange(date)
major_prices <- sku_df %>% summarize(orders = sum(orders), .by = price) %>%
mutate(share = orders / sum(orders)) %>% filter(share >= 0.01) %>% pull(price)
sku_df <- sku_df %>% filter(price %in% major_prices)
date0 <- min(sku_df$date)
weekly <- sku_df %>% mutate(day = as.integer(date - date0) %/% 7 + 1) %>%
summarize(qty = sum(orders), .by = c(day, price))
list(weekly = weekly, date0 = date0)
}
```
One more adjustment concerns $\lambda$. On the synthetic data, the sampling noise is exactly multinomial, and optimizing the posterior over $\lambda$ works well. On real data, the weekly order composition fluctuates more than multinomial sampling alone can explain — the customer mix drifts with seasonality and week-to-week randomness — and the maximum-likelihood segment model absorbs this overdispersion by buying additional segments: with $\lambda$ optimized, the algorithm places a changepoint every second week. We therefore treat $\lambda$ as what the theoretical model says it is — a prior on the changepoint rate, specified from domain knowledge — and fix it at $\lambda = 0.01$, i.e., roughly one regime change per two years a priori. (The principled fix is to replace the multinomial likelihood with a Dirichlet-multinomial, which models within-regime overdispersion explicitly; that is beyond the scope of this post.)
```{r}
#| label: case-study-84077
#| code-summary: "Case-study detectors and plot (SKU 84077)"
#| fig-height: 3.4
#| fig-width: 10
detect_changepoints_histogram_fixed <- function(weekly, log_lambda = log(0.01)) {
hist <- compute_price_histogram(weekly)
res <- locate_changepoints(create_histogram_cumulative(hist$histogram), log_lambda)
boundary_position(which(res$changepoints), days_with_sales(weekly))
}
case_study_plot <- function(retail, sku_id, sku_label) {
prep <- prepare_weekly(retail, sku_id)
weekly <- prep$weekly; date0 <- prep$date0
cp_hist <- detect_changepoints_histogram_fixed(weekly)
cp_mean <- detect_changepoints_means(weekly, "mean")
set.seed(1)
cp_shares <- detect_changepoints_shares(weekly, min_size = 8, n_perm = 199)
as_dates <- function(pos, label) data.frame(x = date0 + (pos - 1) * 7, m = rep(label, length(pos)))
vlines <- bind_rows( as_dates(cp_hist, "histograms (greedy)"),
as_dates(cp_shares, "price shares (E-Divisive)"),
as_dates(cp_mean, "weekly means (PELT)") )
weekly %>% mutate(week_start = date0 + (day - 1) * 7) %>%
ggplot(aes(week_start, price)) + geom_point(aes(size = qty, alpha = qty)) +
geom_vline(data = vlines, aes(xintercept = x, color = m, linetype = m)) +
scale_color_manual(name = NULL, values = c("histograms (greedy)" = "blue",
"price shares (E-Divisive)" = "purple",
"weekly means (PELT)" = "darkgreen")) +
scale_linetype_manual(name = NULL, values = c("histograms (greedy)" = "dashed",
"price shares (E-Divisive)" = "dotdash",
"weekly means (PELT)" = "dotted")) +
labs(x = NULL, y = "price", title = sku_label) + theme_bw() + theme(legend.position = "top")
}
case_study_plot(retail, "84077", "SKU 84077: World War 2 Gliders Asstd Designs")
```
For SKU 84077, the detected boundaries line up with the visible history of the price menu: the mid-June 2010 boundary marks the first sparse sales at the £0.43 tier; the boundaries in late August and mid-September 2010 bracket the gradual rollover of the dominant price from £0.21 to £0.29; the boundaries in late October 2010 and early January 2011 mark the £0.43 tier becoming a regular part of the menu and disappearing again; and the June 2011 boundary marks the introduction of the £0.63 tier. E-Divisive confirms the two largest events. PELT on the weekly mean price detects **nothing at all** — a 38% list-price increase is invisible in the average, because the wholesale/retail mix noise is larger than the shift.
```{r}
#| label: case-study-85099b
#| code-summary: "Case-study plot (SKU 85099B)"
#| fig-height: 3.4
#| fig-width: 10
case_study_plot(retail, "85099B", "SKU 85099B: Jumbo Bag Red White Spotty")
```
For SKU 85099B, the picture is similar. The algorithm brackets the transition of the dominant wholesale price from £1.95 to £2.08 in late March/early April 2011, flags a cluster of composition changes in the December 2010 – January 2011 holiday period, and finds a further mix shift in mid-July 2011; E-Divisive agrees on all three regions. The boundary clusters around the transitions are an honest artifact of the abrupt-change assumption: when a price change rolls out over a few weeks of mixed pricing, the model brackets the transition period instead of placing a single boundary. PELT again fails informatively: it places changepoints in August 2010, where no menu change is visible (the weekly mean moved because the customer mix did), and misses the actual April 2011 price increase.
### Limitations
- The algorithm is designed to detect even small changes in average price if they are sufficiently frequent.
- In the present version, it cannot deal with days with no sales, and may possibly identify them as a new pricing regime, thus zero-sales days have to be excluded before running it.
- The algorithm is not designed to deal with overlapping price regimes.
- The multinomial likelihood assumes that the within-regime price composition is stable up to sampling noise. Real transaction data violates this: customer-mix drift makes the histograms overdispersed, so the changepoint rate $\lambda$ cannot be tuned by posterior optimization and has to be fixed from domain knowledge, as in the case study above. A Dirichlet-multinomial segment likelihood would model the overdispersion explicitly.
- The quantitative evaluation is confined to synthetic data generated under the model's own assumptions; the real-data check is qualitative.
## Repository
All source code is available here:\
👉 <https://github.com/plogacev/case_studies/tree/main/pricedist_changepoints>