[R-SIG-Finance] question about subsetting xts, calculating returns

Andreas Voellenklee wotuzu17 at gmail.com
Wed Apr 18 10:58:23 CEST 2012


Thank you Sean and Garrett. Garrett's example worked fine. If anybody
is interested, I incorporated this in a function and wrote some more
to visualize the results.


calculateNPeriodReturns <- function (TS, Filter, n)
{
    returns <- do.call(cbind, lapply(1:n, function(i) {
        lag(ROC(Cl(TS), i), -i)[Filter]
    }))
    colnames(returns) <- 1:n
    return(returns)
}

returnsBoxplot <- function (returns)
{
    par(mfrow = c(1, 1))
    boxplot(as.matrix(returns), range = 0)
}

returnsHistogram <- function (returns)
{
    columns <- dim(returns)[2]/2
    par(mfrow = c(2, columns))
    for (i in 1:dim(returns)[2]) {
        hist(returns[, i], main = paste("t+", i, sep = ""), xlab = "",
            breaks = 20, col = "blue")
    }
}

returnsLinePlot <- function (returns)
{
    molten <- melt(t(as.data.frame(returns)))
    colnames(molten) <- c("period", "date", "return")
    ggplot(molten, aes(period, return)) + geom_line(aes(colour = date))
}

library(quantmod)
# try Nokia for this example
getSymbols("NOK", adjust=TRUE)

# calculate donchian channel for NOK
DC <- DonchianChannel(lag(cbind(Hi(NOK),Lo(NOK))))

# mark days when price closes below the low band of DC
breakdown <- eval(Cl(NOK)<DC[,"low"])
colnames(breakdown) <- c("breakdown")

# calculate returns from 1:10 periods after breakdown events
returns <- calculateNPeriodReturns(NOK, breakdown, 10)

# show a boxplot of returns
returnsBoxplot(returns)

# show a histogram of returns
returnsHistogram(returns)

# show a line diagram
library(ggplot2)
library(reshape)
returnsLinePlot(returns)



More information about the R-SIG-Finance mailing list