Python Pandas calculates log returned between lines

I have a dataframe containing indexes by date. Is there a way to calculate the log return from one day to the next?

So, if my original framework looks like this:

            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

      

+3


source to share


2 answers


Use shift

and np.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

      

+8


source


I think using the built-in diff operation is better to get the same results

np.log(df).diff()



I like it a little more because it reads better, it is clear what you are doing

np.log(df)

log, .diff()

return

+1


source







All Articles