library(readxl)     # read Excel
library(dplyr)      # data manipulation, %>%
library(ggplot2)    # plots
library(zoo)        # (optional) for quarterly dates like "2000 Q1"
library(gridExtra)  # arrange multiple plots vertically

# scales is often used together with ggplot2 to format axis labels (percentages, dollars, custom date
# library(scales) 

graphics.off() ; rm(list = ls(all = TRUE)) ; cat("\014"); getwd()


# 1. Read data --> note that these are QUARTERLY DATA
df <- read_excel("GDPC1.xlsx", sheet = "Quarterly") %>%
  rename(date = observation_date, X = GDPC1) %>%
  mutate(date = as.Date(date))

class(df)

df <- df %>%
  arrange(date) %>%
  mutate(
    DX     = X - lag(X, 1),                     # First Differences
    DX4    = X - lag(X, 4),                     # Change from Year Ago
    pcX    = 100 * (X - lag(X, 1)) / lag(X, 1), # Percent Change
    pcX4   = 100 * (X - lag(X, 4)) / lag(X, 4), # Percent Change from year ago
    carcX4 = 100 * ((X / lag(X, 1))^4 - 1),     # Compounded Annual Rate of Change
    ccrX   = 100 * (log(X) - log(lag(X, 1))),   # Continuously Compounded Rate of Change:
    ccarc  = 400 * (log(X) - log(lag(X, 1))),   # Continuously Compounded Annual Rate of Change
    lnX    = log(X)
  )

# 3. Create qdate
df$qdate <- as.yearqtr(df$date)

# Then you can filter (Select subsample, for example: 2000Q1–2010Q4) using natural quarterly labels:
sub <- df %>% filter(qdate >= as.yearqtr("1980 Q1"),
                     qdate <= as.yearqtr("2010 Q4"))

# 4a. Plot ONE transformation (e.g. percent change)
g <- ggplot(sub, aes(x = date, y = pcX)) +
  geom_line(color = "#9c394a") +
  labs(title = "Percent Change in Real GDP", 
       x = "Date. Quarterly data", y = "Percent  %") +
  theme_gray(base_size = 10)
g

# install.packages("ggthemes")
# library(ggthemes)
# g + theme_economist()
# g + theme_wsj()
# g + theme_tufte()

# theme_bw() → clean black-and-white, good for publications.
# theme_light() → like theme_bw but softer gridlines.
# theme_classic() → axes only, no background grid.
# theme_gray() (default) → gray background with white grid.
# theme_void() → no axes or grid, just the data (nice for minimalist look).
# p + theme_light(base_size = 14)



# 4b. Double plot: original series (top) and transformation (bottom)
g1 <- ggplot(sub, aes(x = date, y = X)) +
  geom_line(color = "#3bb6c5") +
  labs(title = "Real GDP (levels)", x = "", y = "Billions (Chained 2017 $)") +
  theme_minimal()

g2 <- ggplot(sub, aes(x = date, y = pcX)) +
  geom_line(color = "#2c7eb8"") +
  labs(title = "Percent Change in Real GDP", x = "Date", y = "Percent") +
  theme_minimal()

grid.arrange(g1, g2, ncol = 1, heights = c(2,1))

