我有一個資料集,其中包含 6k 資產及其市場價格的資料。
我想計算每日收益,因此要應用公式
martketprice[i] - marketprice[i-1]/marketprice[i-1]
問題是我在同一日期時間有多個觀察值,例如對于asset x,我有 3 個觀察值,day t因為它是由 交易的investor 1, 2 and 3。對于資料集中的每個資產,依此類推。所以我的資料集看起來像:
investor asset datetime marketprice
1 x t 10
2 x t 10
3 x t 10
我的想法是使用類似的東西
res <- res %>%
arrange(datetime) %>%
group_by(asset) %>%
mutate(ret = (marketprice - dplyr::lag(marketprice))/dplyr::lag(marketprice, default = NA)) %>%
ungroup()
但它不起作用,因為在上面的示例中,第 2 行意味著使用[i-1]同一天的市場價格,而我希望使用前一天[t-1](不包括在示例資料集中)
此外,R 應檢查[i-1]市場價格不屬于相距超過 4 天的日期,因此如果第 i 行的日期是,則僅當日期或更近10th of july時才應應用計算。[i-1]6th of july
任何想法?
uj5u.com熱心網友回復:
基于以下假設,我理解:
- 當同一資產重復一天時,市場價格是相同的,與投資者無關。
- 你不介意哪個投資者是(所以我們可以洗掉行)
- 當天 (t) 比前一天 (t-1) 早 5 天或之前,NaN 輸出是可以的。
庫和一些資料示例:
library(lubridate)
library(tidyverse)
# Data example
set.seed(132) # reproducibility
example = data.frame(
investor = c(rep(1,3),2,3,rep(2,2),1,
rep(2,4),rep(3,4)),
asset = c(rep('A',8),
rep('B',8)),
datetime = c(today() c(1,2,3,3,3,4,5,6),
today() c(1,seq(6,9),seq(16,18))),
marketprice = c(10,20,30,30,30,sample(c(10,20,30),11,replace = TRUE))
)
示例資料集有 2 個資產。第一個 (A) 顯示代碼如何處理同一天的幾行。第二個 (B) 顯示了當日期跳躍大于 4 天時代碼如何處理。
> example
investor asset datetime marketprice
1 1 A 2022-05-26 10
2 1 A 2022-05-27 20
3 1 A 2022-05-28 30
4 2 A 2022-05-28 30
5 3 A 2022-05-28 30
6 2 A 2022-05-29 30
7 2 A 2022-05-30 30
8 1 A 2022-05-31 30
9 2 B 2022-05-26 20
10 2 B 2022-05-31 10
11 2 B 2022-06-01 20
12 2 B 2022-06-02 10
13 3 B 2022-06-03 10
14 3 B 2022-06-10 30
15 3 B 2022-06-11 20
16 3 B 2022-06-12 10
Dplyr 代碼:
# The formula is [price(t)-price(t-1)]/price(t-1) -> dif(price)/lag(price)
ret = example %>%
group_by(asset,datetime) %>%
slice(1) %>% # remove repeated dates
group_by(asset) %>%
arrange(datetime) %>%
mutate(ret = ifelse(datetime-lag(datetime) > 4,
NA,
(marketprice-lag(marketprice))/lag(marketprice))
) %>% # ifelse check the differences of days
arrange(asset,datetime) # show by assets and dates
輸出:
# A tibble: 14 x 5
# Groups: asset [2]
investor asset datetime marketprice ret
<dbl> <chr> <date> <dbl> <dbl>
1 1 A 2022-05-26 10 NA
2 1 A 2022-05-27 20 1
3 1 A 2022-05-28 30 0.5
4 2 A 2022-05-29 30 0
5 2 A 2022-05-30 30 0
6 1 A 2022-05-31 30 0
7 2 B 2022-05-26 20 NA
8 2 B 2022-05-31 10 NA
9 2 B 2022-06-01 20 1
10 2 B 2022-06-02 10 -0.5
11 3 B 2022-06-03 10 0
12 3 B 2022-06-10 30 NA
13 3 B 2022-06-11 20 -0.333
14 3 B 2022-06-12 10 -0.5
因為一天有 3 個資料條目,所以洗掉了 2 行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/483931.html
上一篇:試圖引入動態變數會導致序數錯誤
下一篇:將物件年-周轉換為日期時間格式
