Python Pandas计算日志在行之间返回

时间:2015-06-30 10:30:19

标签: python pandas

我有一个包含按日期索引的价格的数据框。有没有办法计算从一天到下一天的日志回报?

因此,如果我的原始数据框如下所示:

            BBG.XSTO.FABG.S BBG.XETR.BIO3.S BBG.XPAR.BOL.S  BBG.XMCE.AIR.S  
date                
03/02/2014  8.785104        81.151          3.938           51.4627
04/02/2014  8.805004        81.151          4.142           51.4627
05/02/2014  8.866988        82.007          4.197           50.5261
06/02/2014  9.038363        82.135          4.162           51.4134
07/02/2014  8.978838        83.512          4.126           51.7585

Could someone let me know how I apply the formula

log(today_price / yesterday_price)

so I get something that looks like:

            BBG.XSTO.FABG.S BBG.XETR.BIO3.S BBG.XPAR.BOL.S  BBG.XMCE.AIR.S  
date                
03/02/2014  na               na             na              na
04/02/2014  0.002262636      0              0.050505783     0
05/02/2014  0.007014971      0.010492993    0.013191221    -0.018367239
06/02/2014  0.019142907      0.001559626    -0.008374256    0.017408804
07/02/2014  -0.006607599     0.016626099    -0.008687313    0.006689831


Thanks

2 个答案:

答案 0 :(得分:9)

使用shiftnp.log

In [158]:
np.log(df/df.shift())

Out[158]:
            BBG.XSTO.FABG.S  BBG.XETR.BIO3.S  BBG.XPAR.BOL.S  BBG.XMCE.AIR.S
date                                                                        
2014-03-02              NaN              NaN             NaN             NaN
2014-04-02         0.002263         0.000000        0.050506        0.000000
2014-05-02         0.007015         0.010493        0.013191       -0.018367
2014-06-02         0.019143         0.001560       -0.008374        0.017409
2014-07-02        -0.006608         0.016626       -0.008687        0.006690

答案 1 :(得分:1)

我认为使用内置操作diff可以更好地获得相同的结果

np.log(df).diff()

我更喜欢它,因为它读得更好,你正在做的更清楚

np.log(df)日志,.diff()返回