I have my two chunks of code below. In the first chunk I am trying to get my data ready to display in a gt table. My goal is to display a table with Month abbreviations in ascending order (Jan, Feb, March, etc.) in column 1. Currently, it appears each time I run the second chunk of code to create a table, it sort the month data alphabetically. I have looked into the lubridate package, messed around with the 'month.abb' and 'month.name function and still am outputting the months in alphabetical order. See packages used below and chunks below.
library(tidyverse)
library(quantmod)
library(tidyquant)
library(xts)
library(rvest)
library(stringr)
library(forcats)
library(lubridate)
library(tidyr)
library(plotly)
library(purrr)
library(PerformanceAnalytics)
library(gt)
library(paletteer)
library(readr)
library(janitor)
library(scales)
library(lubridate)
start <- as.Date("2020-01-01")
end <- as.Date("2020-11-30")
StockMonthlyReturns <- c("XLC", "XLC", "XLP", "XLE","XLF", "XLV", "XLI","XLB", "XLRE", "XLK", "XLU") %>%
tq_get(get = "stock.prices",
from = start,
to = end) %>%
group_by(symbol) %>%
tq_transmute(select = adjusted,
mutate_fun = periodReturn,
period = "monthly",
col_rename = "StockMonthlyReturns")
stockdata <- StockMonthlyReturns %>% group_by(symbol, Month = floor_date(date, "month")) %>% summarise(Amount = sum(StockMonthlyReturns))
monthnum <- month(stockdata$Month)
stockdata <- cbind(stockdata, monthnum)
stockdata <- stockdata %>% rename(Month_Num = ...4)
stockdata$Month_Num <- month.abb[stockdata$Month_Num]
stockdata <- stockdata %>%
select(-Month)
stockdata <- stockdata %>% rename(Month = "Month_Num")
#stockdata$Month <- months(as.Date(stockdata$Month))
stockdata <- adorn_rounding(stockdata, digits= 4) # Rounding Returns
stockdata$Amount <- percent(stockdata$Amount, accuracy = 0.01) # Changing Decimals to Percent
stockdata %>%
tidyr::spread(key="symbol", value = Amount) %>%
gt(rowname_col = "Month") %>%
tab_header(title = "Monthly Return of SPDR ETF's")
You can try :
library(tidyverse)
library(gt)
stockdata %>%
mutate(Month = factor(Month, month.abb)) %>%
tidyr::spread(key=symbol, value = Amount) %>%
#tidyr::pivot_wider(names_from = symbol, values_from= Amount) %>%
gt(rowname_col = "Month") %>%
tab_header(title = "Monthly Return of SPDR ETF's")
Also note that spread
has been retired in favor of pivot_wider
.