tragen907
tragen907

Reputation: 23

Remove incomplete month from monthly return calculation

I have some code for grabbing stock prices and calculating monthly returns. I would like to drop the last return if the price used to calculate it did not occur at month end. For example, running the code below returns prices through 2014-06-13. And, the monthlyReturn function calculates a return for June even though there hasn't been a full month. Is there an easy way to make sure monthlyReturn is only computing returns on full months or to drop the last month from the return vector if it wasn't calculated on a full month of prices?

    library(quantmod)

    symbols <- c('XLY', 'XLP', 'XLE', 'XLF', 'XLV', 'XLI', 'XLB', 'XLK', 'XLU')
    Stock <- xts()
    Prices <- xts()

    for (i in 1:length(symbols)){
      Stock <- getSymbols(symbols[i],auto.assign = FALSE)
      Prices <- merge(Prices,Stock[,6])
    }

    returns <- do.call(cbind, lapply(Prices, monthlyReturn, leading=FALSE))
    names(returns) <- symbols

I found this bit of code, but it seems to have some limitations. Is there a way to improve this?

    if(tail(index(x.xts),1) != as.Date(as.yearmon(tail(index(x.xts),1)), frac=1)){
    x.m.xts = x.m.xts[-dim(x.m.xts)[1],]
    }
    # That test isn't quite right, but its close.  It won't work on the first
    # day of a new month when the last business day wasn't the last day of 
    # the month.  It will work for the second day.

Upvotes: 1

Views: 287

Answers (1)

GSee
GSee

Reputation: 49810

You can use negative subsetting with xts:::last.xts. This will remove the last month

last(returns, "-1 months")

But you only want to remove the last month if the month hasn't ended yet, so compare the month of the last row, with the month of the current date.

if (format(end(returns), "%Y%m") == format(Sys.Date(), "%Y%m")) 
  returns <- last(returns, "-1 month")

Upvotes: 1

Related Questions