2

I have a dataframe (df) with the values (V) of different stocks at different dates (t). I would like to get a new df with the profitability for each time period. Profitability is: ln(Vi_t / Vi_t-1) where:

ln is the natural logarithm

Vi_t is the Value of the stock i at the date t

Vi_t-1 the value of the same stock at the date before

This is the output of df[1:3, 1:10]

      date    SMI Bond  ABB ADDECO Credit Holcim Nestle Novartis Roche
1 01/08/88 1507.5 3.63 4.98 159.20  15.62  14.64   4.01     4.59 11.33
2 01/09/88 1467.4 3.69 4.97 161.55  15.69  14.40   4.06     4.87 11.05
3 01/10/88 1538.0 3.27 5.47 173.72  16.02  14.72   4.14     5.05 11.94

Specifically, instead of 1467.4 at [2, "SMI"] I want the profitability which is ln(1467.4/1507.5) and the same for all the rest of the values in the dataframe. As I am new to R I am stuck. I was thinking of using something like mapply, and create the transformation function myself. Any help is highly appreciated.

Simon
  • 79
  • 1
  • 6

1 Answers1

0

This will compute the profitabilities (assuming data is in a data.frame call d):

(d2<- log(embed(as.matrix(d[,-1]), 2) / d[-dim(d)[1], -1]))
#          SMI        Bond          ABB     ADDECO      Credit      Holcim     Nestle   Novartis       Roche
#1 -0.02696052  0.01639381 -0.002010051 0.01465342 0.004471422 -0.01652930 0.01239173 0.05921391 -0.02502365
#2  0.04699074 -0.12083647  0.095858776 0.07263012 0.020814375  0.02197891 0.01951281 0.03629431  0.07746368

Then, you can add in the dates, if you want:

d2$date <- d$date[-1]

Alternatively, you could use an apply based approach:

(d2 <- apply(d[-1], 2, function(x) diff(log(x))))
#             SMI        Bond          ABB     ADDECO      Credit      Holcim     Nestle   Novartis       Roche
#[1,] -0.02696052  0.01639381 -0.002010051 0.01465342 0.004471422 -0.01652930 0.01239173 0.05921391 -0.02502365
#[2,]  0.04699074 -0.12083647  0.095858776 0.07263012 0.020814375  0.02197891 0.01951281 0.03629431  0.07746368
Jota
  • 17,281
  • 7
  • 63
  • 93