December 23, 2024

How do you calculate and plot cumulative stock returns in R

Analyzing rates of return on various assets is one of the most significant responsibilities in financial markets. We need past information for the asset to complete this analysis. There are several data suppliers, some of them are free while the majority are not. In this chapter, we will use data from Yahoo Finance.

ticker <- 'AMT'
start_from <- "2016-01-01"
end_to <- Sys.Date()

# download stock data from yahoo finance
stk_data <- tq_get(x=ticker, get="stock.prices", from=start_from, to=end_to)

# tidyquant mutate function options
tq_mutate_fun_options()

# calculate daily returns
stk_data_daily_returns <- stk_data %>% 
  tq_transmute(select = adjusted,
               mutate_fun = periodReturn,
               period = "daily")

# plot daily returns
p1 <- stk_data_daily_returns %>% 
  ggplot(aes(x=date,y=returns))+
  geom_line()+
  geom_hline(yintercept = 0) +
  ggtitle("Daily Returns")+
  labs(x="Date",y="Returns")+
  scale_x_date(date_breaks = 'years',date_labels = '%Y-%b') +
  scale_y_continuous(breaks = seq(-0.5,0.5,0.05),labels = scales::percent)+ 
  theme_tq()

# calculate cumulative returns
stk_data_cum_returns <- stk_data %>% 
  tq_transmute(select = adjusted,
               mutate_fun = periodReturn,
               period = "daily") %>%
  mutate(cumret = cumprod(1 + daily.returns),
         cumulative_returns = cumret - 1) %>% 
  select(-cumret)

# plot cumulative returns
stk_data_cum_returns %>%
  ggplot(aes(x = date, y = cumulative_returns)) +
  geom_line() +
  theme_tq() +
  labs(x = "Date", y = "Cumulative Returns") +
  ggtitle("Cumulative returns")


# put them into functions
download_stock_data <- function(ticker,start_from,end_to) {
  stk_data <- tq_get(x=ticker, get="stock.prices", from=start_from, to=end_to)
  return(stk_data)
}

cum_returns_plot <- function(df,period="daily",cum_plot=T) {
  cum_returns_df <- df %>% 
    tq_transmute(select = adjusted,
                 mutate_fun = periodReturn,
                 period = period,
                 col_rename = "returns") %>%
    mutate(cumret = cumprod(1 + returns),
           cumulative_returns = cumret - 1) %>% 
    select(-cumret)
  
  if(cum_plot==TRUE) {
    p <- cum_returns_df %>%
      ggplot(aes(x = date, y = cumulative_returns)) +
      geom_line() +
      theme_tq() +
      labs(x = "Date", y = "Cumulative Returns") +
      ggtitle("Cumulative returns") +
      scale_x_date(date_breaks = 'years',date_labels = '%Y-%b')
  } else {
    p <- cum_returns_df %>% 
      ggplot(aes(x=date,y=returns))+
      geom_line()+
      geom_hline(yintercept = 0) +
      ggtitle(paste0(ticker," ",period," returns"))+
      labs(x="Date",y="Returns")+
      scale_x_date(date_breaks = 'years',date_labels = '%Y-%b') +
      scale_y_continuous(breaks = seq(-0.5,0.5,0.05),labels = scales::percent)+ 
      theme_tq()
  }
  return(p)
}

# let's test the functions
ticker <- 'SPG'
start_from <- "2016-01-01"
end_to <- Sys.Date()
df <- download_stock_data(ticker,start_from,end_to)
cum_returns_plot(df,period="monthly",cum_plot = T)