Skip to main content

Note 06: Transformations, Differencing & Variance Stabilization

Module 2: Stationarity & Regression

Learning Objectives

  • Apply Box-Cox transformations and Guerrero’s automatic \(\lambda\) selection to stabilize variance, while recognizing that transformations alone do not remove a trend.
  • Use regular first differencing, log returns, and seasonal differencing to achieve mean stationarity.
  • Quantify stability empirically with exact trailing rolling means and unbiased sample rolling standard deviations via slider::slide_dbl().

1. Variance Stabilization: Box-Cox Transformations

Weak stationarity requires both a constant mean and a constant variance. When fluctuations grow proportionally with the series level (heteroscedasticity), we stabilize variance first using a power transformation from the Box-Cox family (defined for strictly positive series \(y_t > 0\)):

\[ w_t = \begin{cases} \dfrac{y_t^\lambda - 1}{\lambda}, & \lambda \neq 0, \\[8pt] \ln y_t, & \lambda = 0. \end{cases} \]

Special cases include \(\lambda = 1\) (no transformation up to a constant shift), \(\lambda = 0.5\) (square-root scale), and \(\lambda = 0\) (natural logarithm, which converts multiplicative percentage changes into additive differences). Guerrero’s method (feasts::guerrero) selects \(\hat{\lambda}\) automatically by minimizing the coefficient of variation of subseries standard deviations across the time span.

A critical misconception must be dispelled early: Box-Cox stabilizes variance, not a trending mean. Because \(w_t\) is a strictly increasing function of \(y_t\), transforming an exponentially growing series such as U.S. GDP compresses curvature into a gentler slope, yet the transformed series still trends upward and remains non-stationary until differenced.

us_gdp <- global_economy |>
  filter(Country == "United States") |>
  drop_na(GDP)

lam_gdp <- us_gdp |>
  features(GDP, features = guerrero) |>
  pull(lambda_guerrero)

us_gdp <- us_gdp |>
  mutate(
    GDP_bc = box_cox(GDP, lam_gdp),
    dGDP_bc = difference(GDP_bc)
  )

tibble(
  Series = "U.S. Annual GDP (1960–2017)",
  `Guerrero lambda` = lam_gdp,
  `Transform interpretation` = "Near cube-root stabilization; trend still requires differencing"
) |> fmt_tbl(digits = 3, caption = "Guerrero Box-Cox parameter for U.S. GDP.")
Guerrero Box-Cox parameter for U.S. GDP.
Series Guerrero lambda Transform interpretation
U.S. Annual GDP (1960–2017) 0.282 Near cube-root stabilization; trend still requires differencing
g1 <- us_gdp |> autoplot(GDP / 1e12, colour = ts_pal["navy"]) +
  labs(title = "Raw U.S. GDP", subtitle = "Exponential growth", x = "Year", y = "Trillion USD")
g2 <- us_gdp |> autoplot(GDP_bc, colour = ts_pal["teal"]) +
  labs(
    title = TeX(sprintf(r"(Box-Cox ($\hat{\lambda} = %.2f$))", lam_gdp), bold = TRUE),
    subtitle = "Linearized, still trending",
    x = "Year",
    y = TeX(r"($w_t$)", bold = TRUE)
  )
g3 <- us_gdp |> drop_na(dGDP_bc) |> autoplot(dGDP_bc, colour = ts_pal["orange"]) +
  geom_hline(yintercept = mean(us_gdp$dGDP_bc, na.rm = TRUE), linetype = "dashed", colour = ts_pal["slate"]) +
  labs(
    title = "First Diff of Box-Cox",
    subtitle = "Stable level and spread",
    x = "Year",
    y = TeX(r"($\nabla w_t$)", bold = TRUE)
  )

(g1 | g2 | g3) +
  plot_layout(guides = "collect") &
  theme(legend.position = "bottom")
Figure 1: U.S. GDP in raw USD (left), after Guerrero Box-Cox transformation (middle, still trending), and after first differencing the Box-Cox series (right, stabilized mean and variance).

2. Regular and Seasonal Differencing

To eliminate non-stationary trends and seasonal drift, we apply differencing operators:

  • First difference: \(\nabla y_t = y_t - y_{t-1}\) removes a linear trend or stochastic random-walk trend. Applied to log prices, \(r_t = \nabla \ln P_t = \ln(P_t / P_{t-1}) \approx (P_t - P_{t-1})/P_{t-1}\) yields continuously compounded log returns.
  • Seasonal difference (period \(s\)): \(\nabla_s y_t = y_t - y_{t-s}\) removes repeating seasonal unit roots (e.g., \(s = 12\) for monthly or \(s = 4\) for quarterly data).
  • Combined differencing: When both trend and multiplicative seasonality are present, transform first, apply seasonal differencing, and then apply first differencing if trend persistence remains: \(\nabla \nabla_s \ln y_t\).

Monthly AirPassengers demonstrates the full three-stage workflow cleanly.

air_df <- as_tsibble(AirPassengers) |>
  mutate(
    log_y = log(value),
    sdiff_log = difference(log_y, lag = 12),
    both_diff = difference(sdiff_log, lag = 1)
  )

p1 <- air_df |> autoplot(value, colour = ts_pal["navy"]) +
  labs(title = "1. Raw AirPassengers", x = NULL, y = "Thousands")
p2 <- air_df |> autoplot(log_y, colour = ts_pal["teal"]) +
  labs(
    title = TeX(r"(2. Log Transform: $\ln(y_t)$)", bold = TRUE),
    x = NULL,
    y = TeX(r"($\ln(y_t)$)", bold = TRUE)
  )
p3 <- air_df |> drop_na(sdiff_log) |> autoplot(sdiff_log, colour = ts_pal["orange"]) +
  labs(
    title = TeX(r"(3. Seasonal Diff: $\nabla_{12}\ln(y_t)$)", bold = TRUE),
    x = "Month",
    y = TeX(r"($\nabla_{12}\ln(y_t)$)", bold = TRUE)
  )
p4 <- air_df |> drop_na(both_diff) |> autoplot(both_diff, colour = ts_pal["crimson"]) +
  geom_hline(yintercept = 0, linetype = "dashed", colour = ts_pal["slate"]) +
  labs(
    title = TeX(r"(4. Regular + Seasonal: $\nabla\nabla_{12}\ln(y_t)$)", bold = TRUE),
    x = "Month",
    y = TeX(r"($\nabla\nabla_{12}\ln(y_t)$)", bold = TRUE)
  )

((p1 | p2) / (p3 | p4)) +
  plot_layout(guides = "collect") &
  theme(legend.position = "bottom")
Figure 2: Sequential stabilization of monthly AirPassengers: natural log stabilizes variance, seasonal differencing removes the 12-month cycle, and first differencing removes residual drift.

3. Rolling Mean and Sample Rolling SD Diagnostics

A practical visual check for stationarity tracks the trailing rolling mean and sample rolling standard deviation over a fixed window of width \(w\):

\[ \bar{y}_t^{(w)} = \frac{1}{w} \sum_{j=0}^{w-1} y_{t-j}, \qquad s_t^{(w)} = \sqrt{\frac{1}{w - 1} \sum_{j=0}^{w-1} \left(y_{t-j} - \bar{y}_t^{(w)}\right)^2}. \]

Using slider::slide_dbl(x, sd, .before = w - 1, .complete = TRUE) uses R’s unbiased \(w - 1\) denominator and guarantees an exact window size of \(w\) observations (with .before = w - 1 plus the current index \(t\)).

Applying this diagnostic to Alphabet’s trading-day series (data/google.csv) exposes why finance works with log returns \(\nabla \ln P_t\) rather than raw dollar differences \(\nabla P_t\). As the share price nearly triples between 2019 and 2023, a 2% daily move corresponds to roughly $1 in 2019 versus $3 in 2022–2023, causing the rolling SD of raw price differences to climb steadily with price level.

goog_td <- readr::read_csv("data/google.csv", show_col_types = FALSE) |>
  arrange(Date) |>
  mutate(
    day = row_number(),
    dClose = Close - lag(Close),
    log_ret = log(Close) - lag(log(Close))
  ) |>
  as_tsibble(index = day) |>
  mutate(
    sd_raw = slide_dbl(dClose, sd, .before = 59, .complete = TRUE),
    sd_ret = slide_dbl(log_ret, sd, .before = 59, .complete = TRUE)
  )

goog_td |>
  as_tibble() |>
  mutate(Period = ifelse(year(Date) <= 2020, "2019–2020", "2021–2023")) |>
  group_by(Period) |>
  summarise(
    `Mean Price ($)` = mean(Close),
    `SD of ΔClose ($)` = sd(dClose, na.rm = TRUE),
    `SD of Log Return` = sd(log_ret, na.rm = TRUE)
  ) |>
  fmt_tbl(digits = 4, caption = "Raw price differences scale with price level; log returns normalize scale.")
Raw price differences scale with price level; log returns normalize scale.
Period Mean Price (\()| SD of ΔClose (\)) SD of Log Return
2019–2020 66.76 1.313 0.0202
2021–2023 120.12 2.316 0.0200
r1 <- goog_td |>
  drop_na(sd_raw) |>
  ggplot(aes(x = Date, y = sd_raw)) +
  geom_line(colour = ts_pal["crimson"], linewidth = 0.75) +
  labs(
    title = TeX(r"(60-Day Rolling SD: $\Delta$Close (USD))", bold = TRUE),
    subtitle = "Variance grows with share price",
    x = "Date",
    y = "Rolling SD (USD)"
  )

r2 <- goog_td |>
  drop_na(sd_ret) |>
  ggplot(aes(x = Date, y = sd_ret)) +
  geom_line(colour = ts_pal["navy"], linewidth = 0.75) +
  labs(
    title = TeX(r"(60-Day Rolling SD: $\nabla \ln(P_t)$)", bold = TRUE),
    subtitle = "Level-free scale (volatility bursts remain)",
    x = "Date",
    y = "Rolling SD (Log Return)"
  )

(r1 | r2) +
  plot_layout(guides = "collect") &
  theme(legend.position = "bottom")
Figure 3: 60-trading-day rolling sample standard deviation of Alphabet raw price differences (left, drifting upward with stock price) versus daily log returns (right, scale-stabilized though exhibiting volatility clusters).

Notice that while log returns remove the long-run level-driven variance drift, temporary volatility spikes (such as early 2020 and 2022) remain visible. Modeling time-varying conditional volatility is the focus of Module 4 (ARCH/GARCH).

Practice Exercises

Exercise 1: Stabilizing Quarterly Australian Gas Production

Filter aus_production from 1970 Q1 onward. Compute Guerrero’s \(\hat{\lambda}\) for Gas, apply box_cox(Gas, lam) followed by seasonal differencing (\(\nabla_4\)) and first differencing (\(\nabla \nabla_4\)), and compare the 12-quarter rolling sample SD (w = 12, .before = 11) of difference(Gas, 4) versus difference(box_cox(Gas, lam), 4).

Solution

Guerrero selects \(\hat{\lambda}\) very close to zero (essentially a log transform). Without Box-Cox stabilization, the 12-quarter rolling SD of seasonally differenced gas grows rapidly as production expands; after Box-Cox transformation, rolling spread stays tight and stable across decades.

gas_df <- aus_production |> filter_index("1970 Q1" ~ .) |> select(Gas)
lam_gas <- gas_df |> features(Gas, guerrero) |> pull(lambda_guerrero)

gas_df |>
  mutate(
    sd_raw12 = slide_dbl(difference(Gas, 4), sd, .before = 11, .complete = TRUE),
    sd_bc12  = slide_dbl(difference(box_cox(Gas, lam_gas), 4), sd, .before = 11, .complete = TRUE),
    Era = ifelse(year(Quarter) < 1990, "1970–1989", "1990–2010")
  ) |>
  as_tibble() |>
  group_by(Era) |>
  summarise(
    `Mean Rolling SD (Raw Δ_4)` = mean(sd_raw12, na.rm = TRUE),
    `Mean Rolling SD (BC Δ_4)`  = mean(sd_bc12, na.rm = TRUE)
  ) |>
  fmt_tbl(digits = 4, caption = paste0("Rolling SD stability before vs. after Box-Cox (lambda = ", round(lam_gas, 3), ")."))
Rolling SD stability before vs. after Box-Cox (lambda = 0.03).
Era Mean Rolling SD (Raw Δ_4) Mean Rolling SD (BC Δ_4)
1970–1989 4.587 0.0685
1990–2010 7.428 0.0520

Exercise 2: Raw Differences vs. Log Differences on U.S. GDP

Using global_economy for the United States, compute a 10-year trailing rolling SD (w = 10, .before = 9) for both raw annual differences \(\nabla \text{GDP}_t\) (in billions USD) and log differences \(\nabla \ln \text{GDP}_t\). Why does differencing raw GDP fail to achieve weak stationarity?

Solution

Because GDP grows exponentially, constant percentage fluctuations translate into far larger dollar jumps in the 2000s than in the 1960s, causing the rolling SD of raw \(\nabla \text{GDP}_t\) to explode over time. Taking logs before differencing measures proportional growth rates with roughly stable spread.

gdp_roll <- us_gdp |>
  mutate(
    d_raw = difference(GDP / 1e9),
    d_log = difference(log(GDP)),
    sd_raw = slide_dbl(d_raw, sd, .before = 9, .complete = TRUE),
    sd_log = slide_dbl(d_log, sd, .before = 9, .complete = TRUE)
  )

gdp_roll |>
  as_tibble() |>
  drop_na(sd_raw, sd_log) |>
  mutate(Decade = ifelse(Year < 1990, "1970–1989", "1990–2017")) |>
  group_by(Decade) |>
  summarise(
    `Avg 10-Yr SD of ΔGDP ($B)` = mean(sd_raw),
    `Avg 10-Yr SD of Δln(GDP)`  = mean(sd_log)
  ) |>
  fmt_tbl(digits = 4, caption = "10-year rolling dispersion of raw vs. log-differenced U.S. GDP.")
10-year rolling dispersion of raw vs. log-differenced U.S. GDP.
Decade Avg 10-Yr SD of ΔGDP ($B) Avg 10-Yr SD of Δln(GDP)
1970–1989 58.16 0.0199
1990–2017 178.24 0.0168

Key Takeaways

  • Box-Cox transformations stabilize variance for strictly positive series; they never eliminate a trending mean on their own.
  • Follow the canonical transformation order: stabilize variance first (log or Guerrero Box-Cox), then apply seasonal differencing \(\nabla_s\), then apply regular differencing \(\nabla\) if trend persists.
  • Always use .before = w - 1 and .complete = TRUE in slider::slide_dbl() so rolling means and unbiased \(w - 1\) rolling standard deviations span exactly \(w\) observations.
  • For daily financial assets, log returns \(\nabla \ln P_t\) on a sequential trading-day index eliminate level-driven scale drift without artificial weekend interpolation.
Back to top