# Load packages
library(tidyverse)
library(tidyquant)
library(timetk)
library(corrr)

1. Import Prices

symbols <- c("AAPL", "MSFT", "GOOG", "AMZN", "TSLA", "NFLX")

prices <- tq_get(
  x = symbols,
  get = "stock.prices",
  from = "2012-01-01",
  to   = "2022-12-31"
)

2. Convert to Monthly Returns (Wide Format)

returns_tbl <- prices %>%
  group_by(symbol) %>%
  tq_transmute(
    select     = adjusted,
    mutate_fun = periodReturn,
    period     = "monthly",
    type       = "log"
  ) %>%
  slice(-1)

returns_wide_tbl <- returns_tbl %>%
  pivot_wider(names_from = symbol, values_from = monthly.returns)

3. Compute Rolling Correlation

rolling_correlation_tbl <- returns_wide_tbl %>%
  tk_xts() %>%
  rollapply(
    width      = 24,
    FUN        = function(x) cor(x)["AAPL", "NFLX"],
    by.column  = FALSE,
    align      = "right"
  ) %>%
  tk_tbl(preserve_index = TRUE, rename_index = "date") %>%
  rename(rolling_correlation = value) %>%
  drop_na()

4. Plot Rolling Correlation

rolling_correlation_tbl %>%
  ggplot(aes(x = date, y = rolling_correlation)) +
  geom_line(color = "cornflowerblue") +
  labs(title = "24-Month Rolling Correlation: AAPL vs. NFLX",
       x = "Date", y = "Correlation") +
  theme_minimal()

5. Correlation Heatmap (Optional — OMITTED based on instructions)

6. Conclusion