Chi Ngo
Chi Ngo

Reputation: 21

Quantmod periodReturn when running R code in the book Data Mining witth R

I try to run the following piece of code in the book Data Mining with R

yearlyReturn(trade.res@trading$Equity)

Error in NextMethod("[<-") : incorrect number of subscripts on matrix The error actually occurs when executing the PeriodReturn that is called by yearlyReturn. The instruction that caused the problem is:

ret[1,] <- firstval

## periodReturn()
xx <- try.xts(x)
    if (inherits(x, "ts")) {
        x <- na.omit(try.xts(x))
        xtsAttributes(x) <- CLASS(x) <- NULL
        xx <- x
        TS <- TRUE
    }
    else TS <- FALSE
    if (has.Op(xx) & has.Cl(xx)) {
        getFirst <- function(X) Op(X)
        getLast <- function(X) Cl(X)
    }
    else getFirst <- getLast <- function(X) X[, 1]
    on.opts <- list(daily = "days", weekly = "weeks", monthly = "months", 
        quarterly = "quarters", yearly = "years", annually = "years")
    ep <- endpoints(xx, on = on.opts[[period]])
    ret <- Delt_(Cl(to_period(xx, period = on.opts[[period]], 
        ...)), type = type)
    if (leading) {
        firstval <- as.numeric(Delt_(getFirst(xx[1]), getLast(xx[ep[2]]), 
            type = type))
        ret[1, ] <- firstval
    }
    colnames(ret) <- paste(period, "returns", sep = ".")
    if (TS) 
        xx <- 1
    tmp.ret <- reclass(ret, xx[ep[-1]])
    if (is.null(subset)) 
        subset <- "/"
    reclass(as.xts(tmp.ret)[subset])
}

Upvotes: 1

Views: 672

Answers (1)

user3670901
user3670901

Reputation:

I got the same error info when running the example code in book "Data Mining with R".

After look into the yearlyReturn source code, i find that if i cast the trade.res@trading$Equity into as.xts(trade.res@trading$Equity), then the error message disappear.

such as:

    yearlyReturn(as.xts(trade.res@trading$Equity))



BTW, there is another error after this error solved with the example code.

The error relative code are:

    table.CalendarReturns(rets)
    table.DownsideRisk(rets)

I look into the source code of table.CalendarReturns and table.DownsideRisk, and find a solution, it works for me, maybe you will need it.

Change above code to:

    R <- as.xts(rets)
    colnames(R) <- 'Equity'
    table.DownsideRisk(R)
    table.CalendarReturns(R)

Upvotes: 1

Related Questions