如何使用数据帧在R中计算股票的每日回报?



(每日回报百分比(/100 = (今日收盘价 - 昨日收盘价(/昨日收盘价

我有一个这样的数据框,

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

我想计算每日回报并使其成为这样,

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

基本 R 选项

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

我们使用diff来获取close的滞后差异,然后通过忽略第一行close将其除以并在末尾添加一个NA

一种选择是使用zoo包中的lag

library(zoo)
close_yesterday <- lag.zoo(df$close, 1, na.pad=TRUE)
df$change <- 100.0 * (df$close - close_yesterday) / close_yesterday

假设所有日期都是连续的几天,则以下内容应该有效:

library(dplyr)
# based on your formula    
df %>% mutate(change = (close - lead(close)) / lead(close))
# based on your outcome 
df %>% mutate(change = (close - lead(close)) / lead(close) * 100)

最新更新