Home Articles

在R中每天计算回报

Asked
Viewed 1018 times
2

Need to calculate returns for each company’s share for the given year on daily basis.

Date         AMZN         GOOG      WFM          MSFT
4/1/2016    636.98999   741.840027  33.27       54.799999
5/1/2016    633.789978  742.580017  33.650002   55.049999
6/1/2016    632.650024  743.619995  33.43       54.049999
7/1/2016    607.940002  726.390015  32.5        52.169998
8/1/2016    607.049988  714.469971  31.98       52.330002

数据从csv文件中读取并存储在数据帧mydf中 . 要计算每日回报,我们需要执行以下计算 - (价格(5/1) - 价格(4/1))/(价格(4/1))

如何对数据框中的所有条目重复进行此操作?我可以通过使用diff(mydf $ AMZN)获得差异

3 Answers

  • 2

    尝试使用 quantmod::Delt

    library(quantmod)
    apply(df[,2:5], 2, Delt)
    
                 AMZN          GOOG          WFM         MSFT
    [1,]           NA            NA           NA           NA
    [2,] -0.005023646  0.0009975062  0.011421761  0.004562044
    [3,] -0.001798631  0.0014004928 -0.006537949 -0.018165305
    [4,] -0.039057964 -0.0231704098 -0.027819324 -0.034782628
    [5,] -0.001463983 -0.0164099778 -0.016000000  0.003066973
    

    添加日期

    cbind(df[,1], apply(df[,2:5], 2, Delt))
    
           Date         AMZN          GOOG          WFM         MSFT
    1: 4/1/2016           NA            NA           NA           NA
    2: 5/1/2016 -0.005023646  0.0009975062  0.011421761  0.004562044
    3: 6/1/2016 -0.001798631  0.0014004928 -0.006537949 -0.018165305
    4: 7/1/2016 -0.039057964 -0.0231704098 -0.027819324 -0.034782628
    5: 8/1/2016 -0.001463983 -0.0164099778 -0.016000000  0.003066973
    
  • 1

    试试这个:

    cbind(mydf[-1,1],apply(mydf[,-1],2,function(x) diff(x)/head(x,-1)))
    

    输出:

    Date         AMZN          GOOG          WFM         MSFT
    1: 5/1/2016 -0.005023646  0.0009975062  0.011421761  0.004562044
    2: 6/1/2016 -0.001798631  0.0014004928 -0.006537949 -0.018165305
    3: 7/1/2016 -0.039057964 -0.0231704098 -0.027819324 -0.034782628
    4: 8/1/2016 -0.001463983 -0.0164099778 -0.016000000  0.003066973
    
  • 1

    收集和操纵股票价格的好R套餐是 quantmod . 尝试:

    library(quantmod)
    symbols <- c("AMZN", "GOOG", "WFM", "MSFT")
    getSymbols(symbols, src = 'google')
    closing.prices <- merge.xts(AMZN[,4], GOOG[,4], WFM[,4], MSFT[,4])["2016-01-04/2016-01-08"]
    

    请注意,所有内容都将使用 xts 时间序列完成 . 可以使用 TTR 包中的 ROC 将时间序列 closing.prices 转换为一系列回报:

    library(TTR)
    price.returns = ROC(closing.prices)
    

Related