Question

I have a list of zoo objects. The core data is the adjusted close of several stock symbols, monthly data. Each list object is a separate time series for each ticker. I'd like to calculate the monthly change for each month, in each object. If it helps, here's what gets me up to my desired calculation:

path = 'C:/SectorRotationSymbList072013.csv'
symbs = read.csv(path, header = FALSE, stringsAsFactors = FALSE)
symbs = symbs[, 1]
importData = vector('list', length(symbs))

#Get monthly pricing data.
for (sIdx in 1:length(symbs)){
    #Import the data for each symbol into the list.
    importData[[sIdx]] = get.hist.quote(instrument= symbs[sIdx],
        start="2000-01-01", end="2013-07-15", quote="AdjClose",
        provider="yahoo", origin="1970-01-01",
        compression="m", retclass="zoo")
}

names(importData) = symbs

I can get the month over month change for each object using sapply as follows:

monthlyGainsLosses = sapply(importData, diff)

I want relative change, though (%). I've tried every variation I can think of on the simple calculation, including:

monthlyGainsLosses = sapply(importData, diff / importData)
monthlyGainsLosses = sapply(importData, diff / coreData(importData))

None of which work. For the latter (which seems most logical to me) I get the error:

non- numeric argument to binary operator. Can anyone help?

Was it helpful?

Solution

sapply expects a function as second argument and diff / coreDate(importData) is not a function in R but an expression.

You can supply lambda to correct it.

monthlyGainsLosses = sapply(importData, function(x) diff(x) / (x))

Or if you want to avoid lambda, then do it in two steps.

perc <- function(x) diff(x) / x
monthlyGainsLosses = sapply(importData, perc)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top