library(tidyverse)
source("../R/scm_functions.R") # pooling_safety_stock()
pfad <- "olist/" # folder containing the unzipped CSV files
orders <- read_csv(paste0(pfad, "olist_orders_dataset.csv"))
items <- read_csv(paste0(pfad, "olist_order_items_dataset.csv"))
cust <- read_csv(paste0(pfad, "olist_customers_dataset.csv"))
prod <- read_csv(paste0(pfad, "olist_products_dataset.csv"))
transl <- read_csv(paste0(pfad, "product_category_name_translation.csv"))
names(transl)[1] <- "product_category_name" # removes a BOM character if present
regionen <- tibble(
customer_state = c("AC","AP","AM","PA","RO","RR","TO",
"AL","BA","CE","MA","PB","PE","PI","RN","SE",
"DF","GO","MT","MS",
"ES","MG","RJ","SP",
"PR","RS","SC"),
region = c(rep("Norte", 7), rep("Nordeste", 9), rep("Centro-Oeste", 4),
rep("Sudeste", 4), rep("Sul", 3))
)
daten <- items |>
inner_join(orders, by = "order_id") |>
filter(!order_status %in% c("canceled", "unavailable")) |>
inner_join(cust, by = "customer_id") |>
left_join(prod, by = "product_id") |>
left_join(transl, by = "product_category_name") |>
left_join(regionen, by = "customer_state") |>
mutate(kategorie = product_category_name_english,
woche = floor_date(as_date(order_purchase_timestamp), "week", week_start = 1)) |>
filter(woche >= as.Date("2017-01-02"), woche <= as.Date("2018-08-20"))
top10 <- daten |> count(kategorie, sort = TRUE) |> slice_head(n = 10) |> pull(kategorie)
wochen <- daten |>
filter(kategorie %in% top10) |>
count(kategorie, region, woche, name = "menge") |>
complete(kategorie, region, woche, fill = list(menge = 0))
# Example: forecast errors (moving average over 8 weeks) for one category
fehler <- wochen |>
filter(kategorie == "health_beauty") |>
group_by(region) |> arrange(woche) |>
mutate(prognose = lag(zoo::rollmeanr(menge, 8, fill = NA)),
fehler = menge - prognose) |>
ungroup() |> drop_na(fehler) |>
select(woche, region, fehler) |>
pivot_wider(names_from = region, values_from = fehler)
Sigma <- cov(as.matrix(fehler[, -1]))
z <- qnorm(0.95); L <- 2
c(SB_regional = sum(z * sqrt(diag(Sigma)) * sqrt(L)),
SB_zentral = z * sqrt(sum(Sigma)) * sqrt(L))