# 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"
)
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
- Rolling correlation helps identify how two assets (e.g., AAPL and
NFLX) co-move over time.
- This is useful for portfolio diversification decisions, especially
during volatile market periods.