Question

If I have a zoo object with multiple series, as so (call it zoo1):

          'SPY'    'XLE'   'XLF'   'XLY'
1/1/2000   .002    .015    .005    .021 
2/1/2000   .051    .007    .070    .011
3/1/2000   .007    .102    .143    .095

and another (zoo2) that represents the max value by row of the above (but excludes column 'SPY'):

1/1/2000    'XLY'
2/1/2000    'XLF'
3/1/2000    'XLF'

How do I get a zoo object that is the pairing of the 'SPY' value from zoo1, as well as the value from zoo1, column indexed by the column referenced in zoo2, but lagged (-1) month. A general description of the task would be that I want to pair the monthly number for SPY with the number for the same month of the symbol that performed best in the prior month. By visual example:

           'SPY'   Current_Perf_Of_Prior_Month_Best_Performer
2/1/2000   .051    .011
3/1/2000   .007    .143

I've tried indexing, read many articles on joins, and even downloaded and attempted to use package sqldf, along with a custom function. Time to punt. Seems like it should be relatively straightforward. Any takers?

Was it helpful?

Solution

This doesn't directly answer your question, because your question is a round-about way to achieve the same result. You don't need the zoo2 object.

# reproducible data
Lines <- 
"'Date'     'SPY'    'XLE'   'XLF'   'XLY'
1/1/2000   .002    .015    .005    .021 
2/1/2000   .051    .007    .070    .011
3/1/2000   .007    .102    .143    .095"
zoo1 <- read.zoo(text=Lines, header=TRUE, format="%m/%d/%Y")

# Get return at (t) for best performer at (t-1)
x <- rollapplyr(zoo1, 2, function(x) x[2,which.max(x[1,])], by.column=FALSE)
# merge with original data
merge(zoo1, x)
#              SPY   XLE   XLF   XLY curBestLag
# 2000-01-01 0.002 0.015 0.005 0.021         NA
# 2000-02-01 0.051 0.007 0.070 0.011      0.011
# 2000-03-01 0.007 0.102 0.143 0.095      0.143
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top