Rikin
Rikin

Reputation: 275

Calculate returns on a daily basis in R

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

The data is read from a csv file and stored in data frame mydf. To calculate the daily returns, we need to perform the below calculation - (Price of (5/1) - Price of (4/1))/(Price of (4/1))

How do I make it recurring for all the entries in the data frame? I could obtain the difference by using diff(mydf$AMZN)

Upvotes: 2

Views: 7515

Answers (3)

lebelinoz
lebelinoz

Reputation: 5068

A good R package for collecting and manipulating stock prices is quantmod. Try:

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"]

Note that everything will be done using xts time series. The time series closing.prices can be converted to a series of returns using ROC from the TTR package:

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

Upvotes: 1

www
www

Reputation: 4224

Try this:

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

Output:

       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

Upvotes: 1

CPak
CPak

Reputation: 13581

Try this using 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

To add back dates

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

Upvotes: 2

Related Questions