Home > OS >  Stocks Daily Returns with R data.frame
Stocks Daily Returns with R data.frame

Time:09-18

(daily return percentage) / 100 = (today's close - yesterday's close) / yesterday's close

I have a data frame like this,

         date    close
1  2018-09-21 3410.486

2  2018-09-22 3310.126

3  2018-09-23 3312.482

4  2018-09-24 3269.432

5  2018-09-25 3204.922

I'd like to calculate daily returns and make it like this,

        date    close  change

1  2018-09-21 3410.486  3.03%

2  2018-09-22 3310.126 -0.07%

3  2018-09-23 3312.482  1.32%

4  2018-09-24 3269.432  2.01%

5  2018-09-25 3321.825     NA

CodePudding user response:

library(tidyverse) 
library(tidyquant) 

df %>%  
  tq_mutate(select = close, 
            mutate_fun = periodReturn, 
            period = "daily", 
            col_rename = "return")

# A tibble: 5 x 3
  date       close    return
  <date>     <dbl>     <dbl>
1 2018-09-21 3410.  0       
2 2018-09-22 3310. -0.0294  
3 2018-09-23 3312.  0.000712
4 2018-09-24 3269. -0.0130  
5 2018-09-25 3205. -0.0197  

CodePudding user response:

Just using dplyr.

df1 %>% 
  mutate(change = (close - lag(close)) / lag(close))
        date    close        change
1 2018-09-21 3410.486            NA
2 2018-09-22 3310.126 -0.0294268911
3 2018-09-23 3312.482  0.0007117554
4 2018-09-24 3269.432 -0.0129962970
5 2018-09-25 3204.922 -0.0197312561

data:

df1 <- structure(list(date = structure(c(17795, 17796, 17797, 17798, 
17799), class = "Date"), close = c(3410.486, 3310.126, 3312.482, 
3269.432, 3204.922), change = structure(c(0, 0, 0, 0, 0), tsp = c(0, 
4, 1))), row.names = c(NA, -5L), class = "data.frame")
  • Related