Return calculations in R

Discrete returns the long way. This assumes the prices are in an xts object. stats::lag is specified since dplyr can mask the stats lag function with its own lag function:

head(diff(prices.xts)[2:n-1]/stats::lag(prices.xts, 1))

The easy way, with the PerformanceAnalytics package:

library(PerformanceAnalytics)
head(Return.calculate(prices.xts, method = “discrete”))

Check they’re the same:

Log returns the long way, this time removing NAs:

na.omit(diff(log(prices.xts))

With PerformanceAnalytics:

prices.ret <-na.omit((Return.calculate(prices.xts, method = “log”)))

Convert to a data.frame, rename date column, remove NAs if any:

data.frame(index(prices.ret), coredata(prices.ret)) %>% dplyr::rename(date = index.prices.ret.) %>% na.omit()

Leave a Reply

Your email address will not be published. Required fields are marked *