Skip to main content

Note 01: Time Series Foundations & Tidy Structures

Module 1: Foundations & Exploratory Analysis

Learning Objectives

  • Define a stochastic process and distinguish strict stationarity from weak (second-order) stationarity.
  • Understand the anatomy of a tsibble (index, key, and interval) and convert legacy ts objects cleanly.
  • Handle calendar gaps in financial trading-day series without introducing spurious interpolation artifacts.

1. Stochastic Processes and Stationarity

A time series is an ordered sequence of observations \(x_1, x_2, \dots, x_n\) recorded sequentially over time. Mathematically, we treat the observed data as a single realization (sample path) of a stochastic process, an indexed collection of random variables \(\{X_t : t \in \mathcal{T}\}\) defined on a common probability space. For discrete equally spaced observations, \(\mathcal{T} = \{1, 2, \dots\}\) or \(\mathcal{T} = \mathbb{Z}\).

Unlike independent and identically distributed (iid) cross-sectional samples, consecutive values \(X_t\) and \(X_{t+1}\) typically exhibit serial dependence. Because we observe only one realization of \(\{X_t\}\) at each time point \(t\), statistical inference requires a stability assumption that lets us average across time. That assumption is stationarity.

A process \(\{X_t\}\) is strictly stationary if for every finite set of time indices \(t_1, \dots, t_m\) and every integer shift \(h\), the joint distribution is invariant to time translation:

\[ (X_{t_1}, X_{t_2}, \dots, X_{t_m}) \stackrel{d}{=} (X_{t_1 + h}, X_{t_2 + h}, \dots, X_{t_m + h}). \]

Strict stationarity governs all finite-dimensional distributions and is rarely verifiable in practice. Most time series theory therefore relies on weak stationarity (also called covariance or second-order stationarity). A process \(\{X_t\}\) is weakly stationary if all three of the following conditions hold:

  1. Finite second moments: \(\mathbb{E}[X_t^2] < \infty\) for all \(t\).
  2. Constant mean and variance: \(\mathbb{E}[X_t] = \mu\) and \(\operatorname{Var}(X_t) = \sigma^2 < \infty\) for all \(t\).
  3. Shift-invariant autocovariance: \(\operatorname{Cov}(X_t, X_{t+k}) = \gamma_k\) depends only on the lag \(k\), not on the time index \(t\).

Strict stationarity implies weak stationarity whenever \(\mathbb{E}[X_t^2] < \infty\). The converse does not hold in general, with one critical exception: a Gaussian process is fully determined by its mean and autocovariance functions, so weak and strict stationarity coincide for Gaussian series.

2. Tidy Time Series Structures (tsibble)

In the fpp3 ecosystem, time series are stored as tsibbles (tbl_ts), extensions of tibbles that enforce temporal structure through three explicit attributes:

  • Index: the column recording time (such as yearquarter, yearmonth, Date, or integer year/trading day).
  • Key: zero or more columns identifying distinct observational units (e.g., Country or Symbol). Every (key, index) pair must be unique.
  • Interval: the regular spacing between consecutive observations (e.g., [1Y], [1Q], [1M], [1D], or [!] when irregular).

Many classic datasets in R and astsa arrive as legacy ts objects. The function as_tsibble() converts them directly into tidy tsibbles suitable for ggplot2, feasts, and fable. Consider the global land-ocean temperature anomaly record (astsa::gtemp_both, annual deviations from the 1951 to 1980 baseline in degrees Celsius):

gtemp_ts <- as_tsibble(gtemp_both) |>
  rename(Year = index, Anomaly = value)

tibble(
  Attribute = c("Index", "Key", "Interval", "Start Year", "End Year", "Observations"),
  Value = c(
    index_var(gtemp_ts),
    ifelse(length(key_vars(gtemp_ts)) == 0, "(none)", paste(key_vars(gtemp_ts), collapse = ", ")),
    format(interval(gtemp_ts)),
    as.character(min(gtemp_ts$Year)),
    as.character(max(gtemp_ts$Year)),
    as.character(nrow(gtemp_ts))
  )
) |> fmt_tbl(caption = "Structural metadata of the global temperature anomaly tsibble.")
Structural metadata of the global temperature anomaly tsibble.
Attribute Value
Index Year
Key (none)
Interval 1Y
Start Year 1850
End Year 2023
Observations 174

Plotting the series reveals an immediate violation of weak stationarity: the mean level drifts upward markedly after the mid-twentieth century.

gtemp_ts |>
  autoplot(Anomaly, colour = ts_pal["crimson"], linewidth = 0.7) +
  geom_hline(yintercept = 0, linetype = "dashed", colour = ts_pal["slate"]) +
  labs(
    title = "Global Land-Ocean Temperature Anomalies",
    subtitle = "Annual deviations relative to the 1951-1980 baseline (astsa::gtemp_both)",
    x = "Year",
    y = "Temperature Anomaly (°C)"
  )
Figure 1: Annual global land-ocean temperature anomalies (1850 to 2023) showing a clear upward trend that violates constant-mean stationarity.

3. Trading-Day Indexes and Calendar Gaps

Regular calendar series (monthly, quarterly, annual) rarely have structural gaps. Daily financial series are fundamentally different: equity markets close on weekends and public holidays. If we index daily closing prices by calendar Date, the resulting [1D] tsibble contains implicit missing days.

goog_raw <- readr::read_csv("data/google.csv", show_col_types = FALSE)

goog_cal <- goog_raw |>
  as_tsibble(index = Date)

gap_summary <- goog_cal |>
  count_gaps()

tibble(
  Metric = c("Trading days observed", "Calendar span (days)", "Implicit calendar gaps", "Total non-trading days"),
  Count = c(
    nrow(goog_cal),
    as.integer(max(goog_cal$Date) - min(goog_cal$Date)) + 1L,
    nrow(gap_summary),
    sum(gap_summary$.n)
  )
) |> fmt_tbl(caption = "Calendar gap summary for Alphabet (GOOG) daily prices (2019–2023).")
Calendar gap summary for Alphabet (GOOG) daily prices (2019–2023).
Metric Count
Trading days observed 1258
Calendar span (days) 1823
Implicit calendar gaps 269
Total non-trading days 565

A common mistake is filling weekend gaps with linear interpolation or carry-forward values. Never interpolate closed-market stock prices. Market closures are not missing measurements; inserting synthetic weekend prices creates artificial zero-return days, deflates estimated volatility, and distorts autocorrelation at lags 1 to 7.

Instead, maintain two complementary views of the same data:

  1. Calendar Date view for visualization and domain interpretation.
  2. Sequential trading-day index (day = row_number()) for gap-free temporal operators such as differencing, ACF estimation, and unit-root tests.
goog_td <- goog_raw |>
  arrange(Date) |>
  mutate(day = row_number()) |>
  as_tsibble(index = day)

has_gaps(goog_td) |> fmt_tbl(caption = "Gap verification under the sequential trading-day index.")
Gap verification under the sequential trading-day index.
.gaps
FALSE
goog_cal |>
  ggplot(aes(x = Date, y = Close)) +
  geom_line(colour = ts_pal["navy"], linewidth = 0.65) +
  labs(
    title = "Alphabet Inc. (GOOG) Daily Closing Price",
    subtitle = "Calendar-date display of 1,258 trading days (2019-2023, no interpolation)",
    x = "Date",
    y = "Closing Price (USD)"
  )
Figure 2: Alphabet (GOOG) daily closing prices plotted against calendar dates while keeping the trading-day index free of artificial interpolation.

Practice Exercises

Exercise 1: Inspecting a Quarterly Tsibble

Inspect the built-in aus_production tsibble: identify its index, key, interval, and date span, check whether it has implicit time gaps, and summarize the non-missing sample size, mean, and standard deviation of Beer and Gas.

Solution

aus_production is an unkeyed quarterly tsibble ([1Q]) spanning 1956 Q1 through 2010 Q2 with zero implicit gaps.

tibble(
  Index = index_var(aus_production),
  Interval = format(interval(aus_production)),
  Start = as.character(min(aus_production$Quarter)),
  End = as.character(max(aus_production$Quarter)),
  Has_Gaps = has_gaps(aus_production)$.gaps
) |> fmt_tbl(caption = "Metadata for aus_production.")
Metadata for aus_production.
Index Interval Start End Has_Gaps
Quarter 1Q 1956 Q1 2010 Q2 FALSE
aus_production |>
  as_tibble() |>
  summarise(
    across(
      c(Beer, Gas),
      list(
        n = ~ sum(!is.na(.x)),
        Mean = ~ mean(.x, na.rm = TRUE),
        SD = ~ sd(.x, na.rm = TRUE)
      )
    )
  ) |>
  pivot_longer(everything(), names_to = c("Series", ".value"), names_sep = "_") |>
  fmt_tbl(digits = 1, caption = "Summary statistics for Beer (megalitres) and Gas (petajoules).")
Summary statistics for Beer (megalitres) and Gas (petajoules).
Series n Mean SD
Beer 218 415.4 85.9
Gas 218 99.2 76.0

Exercise 2: Trading-Day Indexing on gafa_stock

Filter gafa_stock to Apple (Symbol == "AAPL") in 2018. Verify that the calendar Date index has gaps, construct a gap-free trading-day tsibble indexed by day = row_number(), and plot Close against Date.

Solution

Filtering to AAPL in 2018 yields a single-key daily series with weekend and holiday gaps on the calendar index (has_gaps() is TRUE), while indexing by day = row_number() produces a regular [1] trading-day tsibble with zero gaps.

aapl_2018 <- gafa_stock |>
  filter(Symbol == "AAPL", year(Date) == 2018)

aapl_td <- aapl_2018 |>
  as_tibble() |>
  arrange(Date) |>
  mutate(day = row_number()) |>
  as_tsibble(index = day)

tibble(
  Representation = c("Calendar Date", "Trading Day"),
  Rows = c(nrow(aapl_2018), nrow(aapl_td)),
  Has_Gaps = c(has_gaps(aapl_2018)$.gaps, has_gaps(aapl_td)$.gaps)
) |> fmt_tbl(caption = "Calendar vs. trading-day gap status for AAPL (2018).")
Calendar vs. trading-day gap status for AAPL (2018).
Representation Rows Has_Gaps
Calendar Date 251 FALSE
Trading Day 251 FALSE
aapl_2018 |>
  ggplot(aes(x = Date, y = Close)) +
  geom_line(colour = ts_pal["teal"], linewidth = 0.75) +
  labs(
    title = "Apple Inc. (AAPL) Closing Prices in 2018",
    subtitle = "Observed trading days plotted on a calendar axis without gap interpolation",
    x = "Date",
    y = "Closing Price (USD)"
  )
Figure 3: Apple (AAPL) daily closing prices across 2018 trading days.

Key Takeaways

  • Weak stationarity requires finite second moments, constant mean, constant variance, and an autocovariance function depending only on lag \(k\).
  • Every tsibble enforces a unique (key, index) structure and explicit time interval; convert legacy ts objects with as_tsibble().
  • Never interpolate financial prices across closed-market days: plot with Date for interpretability and index by sequential trading days (day = row_number()) for temporal analysis.
  • Visual inspection of time plots is always the first diagnostic check against non-stationary mean drift or changing variance.
Back to top