Search code examples
rfinance

How to calculate stock's daily returns in R using data.frame?


(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-20 3310.126
3  2018-09-19 3312.482
4  2018-09-18 3269.432
5  2018-09-17 3204.922
6  2018-09-14 3242.090
7  2018-09-13 3236.566
8  2018-09-12 3202.025
9  2018-09-11 3224.212
10 2018-09-10 3230.068
11 2018-09-07 3277.644
12 2018-09-06 3262.881
13 2018-09-05 3298.141
14 2018-09-04 3363.898
15 2018-09-03 3321.825

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

         date    close  change
1  2018-09-21 3410.486  3.0319
2  2018-09-20 3310.126 -0.0711
3  2018-09-19 3312.482  1.3168
4  2018-09-18 3269.432  2.0128
5  2018-09-17 3204.922 -1.1464
6  2018-09-14 3242.090  0.1707
7  2018-09-13 3236.566  1.0787
8  2018-09-12 3202.025 -0.6881
9  2018-09-11 3224.212 -0.1813
10 2018-09-10 3230.068 -1.4515
11 2018-09-07 3277.644  0.4525
12 2018-09-06 3262.881 -1.0691
13 2018-09-05 3298.141 -1.9548
14 2018-09-04 3363.898  1.2666
15 2018-09-03 3321.825      NA

Solution

  • A base R option

    df$change <- c(-diff(df$close)/df$close[-1] *  100, NA)
    
    df
    #         date    close      change
    #1  2018-09-21 3410.486  3.03190876
    #2  2018-09-20 3310.126 -0.07112491
    #3  2018-09-19 3312.482  1.31674248
    #4  2018-09-18 3269.432  2.01284150
    #5  2018-09-17 3204.922 -1.14642098
    #6  2018-09-14 3242.090  0.17067472
    #7  2018-09-13 3236.566  1.07872362
    #8  2018-09-12 3202.025 -0.68813713
    #9  2018-09-11 3224.212 -0.18129649
    #10 2018-09-10 3230.068 -1.45153043
    #11 2018-09-07 3277.644  0.45245291
    #12 2018-09-06 3262.881 -1.06908710
    #13 2018-09-05 3298.141 -1.95478579
    #14 2018-09-04 3363.898  1.26656281
    #15 2018-09-03 3321.825          NA
    

    We use diff to get lagged differences of close and then divide it by close ignoring the first row and add a NA at the end.