I have a file like this.
head(Historical_Stock_Prices_R)
Date1 MSFT AAPL GOOGL
1 25-01-05 21.02985 4.873362 88.56
2 26-01-05 21.02177 4.886890 94.62
3 27-01-05 21.10259 4.913269 94.04
want to calculate log return using this formula ln(current price/previous price) and my expected output is like this
Date1 MSFT AAPL GOOGL
26-01-05 -0.04% 0.28% 6.62%
27-01-05 0.38% 0.54% -0.61%
tried to solve by this codes from previous stack overflow answer but fail
logs=data.frame( cbind.data.frame(newdates[-1],
diff(as.matrix(log(Historical_Stock_Prices_R[,-1])))))
Try this:
df = read.table(text="
Date1 MSFT AAPL GOOGL
1 25-01-05 21.02985 4.873362 88.56
2 26-01-05 21.02177 4.886890 94.62
3 27-01-05 21.10259 4.913269 94.04",header=T)
cbind.data.frame(date=df$Date1[-1],apply(df[,2:4],2,function(x) log(x[-1]/x[-length(x)])*100))
# date MSFT AAPL GOOGL
# 2 26-01-05 -0.03842896 0.2772061 6.6188582
# 3 27-01-05 0.38372143 0.5383395 -0.6148647