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)


# Load your function from the .R file
source("plot_fred_simple.R")
# Example calls
plot_fred_simple(df, series1 = "pcX", start = "2000 Q1", end = "2010 Q4")

plot_fred_simple(df, series1 = "X", series2 = "pcX",
                 start = "2000 Q1", end = "2010 Q4")
