2014-05-14 22 views
2

我想在具有累積收益的數據框中創建一列。數據框有多個股票,並由列「n」表示。我想計算這些股票的每個股票的累計回報,而不需要將數據框分成股票數量。請看這個例子:當文件包含不同的股票時計算cumprod

library("lubridate") 
n=c("IBM","IBM","IBM","IBM","IBM","IBM","IBM","IBM","IBM","IBM", 
    "AAPL","AAPL","AAPL","AAPL","AAPL","AAPL","AAPL","AAPL","AAPL","AAPL", 
    "GOOG","GOOG","GOOG","GOOG","GOOG","GOOG","GOOG","GOOG","GOOG","GOOG" 
    ) 

dt=c("20140407","20140408","20140409","20140410","20140411", 
    "20140414","20140415","20140416","20140417","20140418", 
    "20140407","20140408","20140409","20140410","20140411", 
    "20140414","20140415","20140416","20140417","20140418", 
    "20140407","20140408","20140409","20140410","20140411", 
    "20140414","20140415","20140416","20140417","20140418" 
    ) 
ret=c(0.006,0.049,0.069,0.068,0.062,0.035,0.001,0.048,0.034,0.025, 
    0.068,0.002,0.042,0.036,0.01,0.006,0.074,0.021,0.005,0.028, 
    0.082,0.041,0.036,0.083,0.012,0.031,0.061,0.032,0.061,0.041 
    ) 

df=data.frame(n,dt,ret) 
df$dt<-ymd(as.character(df$dt)) 
df$cum_ret <-cumprod(1+df$ret) 

正如你所看到的,這個數據集有3個股票。我想更改df $ cum_ret,以便它是每隻股票的累積回報率(在「n」欄中註明)

有沒有人有任何想法?非常感謝!

+0

你真的應該[編輯]您發佈幷包含語言標籤,以便熟悉該語言的人員能夠看到它。 「股票」不是一個編程術語。 –

回答

0

您可以使用包dplyr執行此操作。

require(dplyr)  #install the package and load it into library 

#group the data by "n" and calculate the cumulative sums of returns 

df <- df %.% group_by(n) %.% mutate(cum_ret = cumsum(ret))  

編輯:確保的n組按日期排序計算的累計回報率時,您可以包括arrange在操作:

df <- df %.% arrange(n, dt) %.% group_by(n) %.% mutate(cum_ret = cumsum(ret)) 
+0

這是完美的,非常感謝你beginneR !!! –

1
> s <- split(df, df$n) 
> ll <- lapply(s, function(x) cbind(x, cum_ret = cumprod(1+x$ret))) 
> unsplit(ll, df$n) 
#  n  dt ret cum_ret 
# 1 IBM 20140407 0.006 1.006000 
# 2 IBM 20140408 0.049 1.055294 
# 3 IBM 20140409 0.069 1.128109 
# ... 
# 11 AAPL 20140407 0.068 1.068000 
# 12 AAPL 20140408 0.002 1.070136 
# 13 AAPL 20140409 0.042 1.115082 
# ... 
# 21 GOOG 20140407 0.082 1.082000 
# 22 GOOG 20140408 0.041 1.126362 
# 23 GOOG 20140409 0.036 1.166911 
# ... 
+1

'cumsum(r)'用於對數回報。用於算術的'cumprod(1 + r)'返回 – GSee

+0

謝謝!我正在計算使用累積,因此需要一個1 + r *以前的基礎。 –

+0

好的,然後插入代碼。 :)我爲你做了。 –