0
$\begingroup$

I downloaded adjusted closing price using quantmod for a set of securities. I want to calculate daily/weekly/monthly return for all securities. Usual dailyReturn, weeklyReturn etc not working. What do I need to do? Here is my code.

tickers <- c('FB','MMM')
data_env <- new.env()
getSymbols(Symbols = tickers, env = data_env)
tempPort <- do.call(merge, eapply(data_env, Ad))

head(tempPort )
           MMM.Adjusted FB.Adjusted
2007-01-03     57.00983          NA
2007-01-04     56.78401          NA
2007-01-05     56.39790          NA
2007-01-08     56.52174          NA
2007-01-09     56.58731          NA
2007-01-10     56.71116          NA

head(weeklyReturn(tempPort,  type = 'log', leading=TRUE))
           weekly.returns
2012-05-18   -0.010791856
2012-05-25    0.015093078
2012-06-01   -0.023027534
2012-06-08    0.037315263
2012-06-15    0.016605617
2012-06-22   -0.007000966

It returned garbage. How to handle this?

$\endgroup$

2 Answers 2

0
$\begingroup$

weeklyReturnis for univariate series.

Try this

tail(do.call("merge",apply(tempPort,2,weeklyReturn,type = 'log', leading=TRUE)))

#             weekly.returns weekly.returns.1
# 2019-04-18    0.006692682      -0.00458900
# 2019-04-26   -0.132748543       0.07148027
# 2019-05-03   -0.034230826       0.02057131
# 2019-05-10   -0.051856081      -0.03715810
# 2019-05-17   -0.039257136      -0.01627267
# 2019-05-24   -0.009381505      -0.02314769
$\endgroup$
0
$\begingroup$

Maybe create a weekly series before calculating returns.

library(xts)
library(quantmod)

tickers <- c('FB','MMM')
data_env <- new.env()
getSymbols(Symbols = tickers, env = data_env)

tempPort_weekly <- do.call(merge, eapply(data_env, function(x) {
  x <- Ad(x)
  w <- Cl(to.weekly(x))
  colnames(w) <- colnames(x)
  w
}))

tail(diff(log(tempPort_weekly)))
#>            MMM.Adjusted  FB.Adjusted
#> 2021-09-10 -0.051945999  0.006437513
#> 2021-09-17 -0.016719862 -0.037587995
#> 2021-09-24 -0.002482621 -0.032775228
#> 2021-10-01 -0.024377816 -0.028595080
#> 2021-10-08  0.001527043 -0.038515509
#> 2021-10-15  0.027809784 -0.016157643

Created on 2021-10-18 by the reprex package (v0.2.1)

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.