data/data-script/FactorModel.R

update_factor_ret <- function() {

  ff <- download_french('F-F_Research_Data_5_Factors_2x3_daily_CSV.zip', 2)
  ff_5 <- ff[, 1:6]
  rf <- ff[, c(1, 7)]
  ff_mo <- download_french('F-F_Momentum_Factor_daily_CSV.zip', 12)
  us_yield <- us_yield_pca()
  raw <- download_fred('BAMLC0A0CM')
  raw[, 2] <- price_fill_na(raw[, 2])
  us_credit <- price_to_ret(raw)
  raw <- download_fred('DTWEXB')
  raw[, 2] <- price_fill_na(raw[, 2])
  us_dollar <- price_to_ret(raw)
  all_ret <- combine_time_series(ff_5, ff_mo, us_yield, us_credit, us_dollar,
                                 freq = 'w')
  all_ret[is.na(all_ret)] <- 0
  return(all_ret)
}

us_yield_pca <- function() {

  yield_tick <- c('DGS3MO', 'DGS6MO', 'DGS1', 'DGS2', 'DGS3', 'DGS5', 'DGS7',
                  'DGS10', 'DGS20')
  yield_list <- lapply(yield_tick, download_fred)
  yield <- combine_time_series(yield_list, freq = 'w',
                                  data_type = 'price', input_list = TRUE)
  yield_delta <- price_to_ret(yield)
  yield_delta[, 2:ncol(yield_delta)] <- apply(yield_delta[, 2:ncol(yield_delta)],
                                              MARGIN = 2,
                                              FUN = function(x) {
                                                x[x > 0.5] <- NA
                                                x[x < -0.5] <- NA
                                                return(x)
                                              })
  yield_delta <- return_fill_na(yield_delta)
  p <- princomp(yield_delta[, 2:ncol(yield_delta)], cor = TRUE)
  data.frame(date = yield_delta$date, p$scores)
}

fact_ret <- update_factor_ret()
save(fact_ret, file = './data/FactorModel.RData')
alejandro-sotolongo/InvestmentSuite documentation built on Jan. 19, 2020, 5:20 p.m.