Home > OS >  Calculating daily returns
Calculating daily returns

Time:06-13

I am currently trying to calculate daily returns for "WMK", "DIS", "PEP", and I cannot get the right code to do so. As well as this I need to plot the returns as well. Could someone please help me, I will attach code below.

prices= tq_get("WMK", "DIS", "PEP", from = "2000-01-01", to = "2022-06-01")
  
R.WMK= Return.calculate(xts(prices), method="discrete")
R.DIS= Return.calculate(xts(prices), method="discrete")
R.PEP= Return.calculate(xts(prices), method="discrete")

ggplot(R.WMK, type = "1")
ggplot(R.DIS, type = "1")
ggplot(R.PEP, type ="1")

CodePudding user response:

You could do something like this to get the % daily return on adjusted prices:

library(tidyverse)
library(tidyquant)
library(scales)

price_df <- tq_get(c("WMK", "DIS", "PEP"), 
                 from = "2000-01-01", to = "2022-06-01")

return_df <- price_df |> 
  group_by(symbol) |> 
  mutate(daily_return = adjusted / lag(adjusted) - 1)

return_df |> 
  ggplot(aes(symbol, daily_return))  
  geom_boxplot()  
  scale_y_continuous(labels = label_percent())

Created on 2022-06-13 by the Simple return

Cumulative return

tq_get(c("WMK", "DIS", "PEP"), from = "2000-01-01", 
       to = "2022-06-01") %>% 
  group_by(symbol) %>%  
  tq_mutate(select = adjusted, 
            mutate_fun = periodReturn, 
            period = "daily", 
            col_rename = "return") %>%  
  mutate(cr = cumprod(1   return)) %>% 
  ggplot()   
  aes(x = date, y = cr, col = symbol)  
  geom_line()   
  facet_wrap(~ symbol)

Cumulative return

  • Related