rm(list = ls())
library(zoo)
library(dplyr)

# Load UCSV forecasts and save them in new format (easier to read into R)

# Directory
setwd("[enter directory where .csv files for UCSV forecasts have been saved]")

# Vector of origin dates
dts <- (as.yearqtr("1962 Q4") + (0:222)/4) 

# File names for mean and variance forecasts
nm_m <- "mean_y_fore_all_h"
nm_v <- "vari_y_fore_all_h"

# Initialize two lists for mean and variance forecasts
m <- v <- list()
# Loop over horizons. For each horizon, load csv data and put them into list.
for (hh in 1:5){
  m[[hh]] <- read.table(paste0(nm_m, hh, ".csv"), sep = ",", header = FALSE)
  v[[hh]] <- read.table(paste0(nm_v, hh, ".csv"), sep = ",", header = FALSE)
}
  
# Save UCSV forecasts in new list that is organized along forecast origin dates
# Note: 1) Change date convention so that forecasts at h = 1 have the same origin and target date
# 2) "rw" stands for "random walk" (because UCSV is similar to the latter)
all_rw <- list()
for (jj in 1:ncol(m[[1]])){
  all_rw[[jj]] <- list(origin_date = as.yearqtr(dts[jj] + .25),
                       m_draws = sapply(m, function(x) x[,jj]), 
                       v_draws = sapply(v, function(x) x[,jj]))
}

# Save final list one folder level higher
save(all_rw, file = paste0("../ucsv_forecasts_first_release.RData"))