Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - Passing Results of Combn Function to a Two Parameter Function

Tags:

r

I have a vector of stock/etf symbols, which varies in size depending on my interests.

Ex:

symbols_v <- c('UPRO','TLT','SPXU','TBT','DRN','URE','SOXL')

I would like to use the rule of combinations, two at a time to iterate over the vector, to generate pairs.

Ex:

p <- combn(symbols_v, 2)

Each pair from p should then get passed into a (user defined) two parameter function "f(x,y)" that will download stock data and perform correlations and other functions.

My questions are: 1) What would be the best data structure to use for p for step 2 below? 2) Given the data structure p, what's the easiest way to parse it to feed the pairs to the function f?

Summary: how do I take the results of the combn() function and pass each pair to a function f(x,y)?

I am trying to minimize looping, since that is considered "slow" in R.

I am probably missing something fundamental, but I can't seem to quite wrap my head around it.

Please feel free to insult my intelligence while providing an answer :)

like image 221
Doug Smith Avatar asked Dec 08 '22 21:12

Doug Smith


1 Answers

You can just use the FUN argument of combn:

library(quantmod)  # for getSymbols
symbols_v <- c('UPRO','TLT','SPXU')  # shorter example
# simple function to download data and calculate correlation between close prices
f <- function(x) {
  x1 <- getSymbols(x[1], auto.assign=FALSE)
  x2 <- getSymbols(x[2], auto.assign=FALSE)
  y <- merge(Cl(x1),Cl(x2))
  cor(y[,1],y[,2],use="complete.obs")
}
# run 'f' on each pair 
p <- combn(symbols_v, 2, FUN=f, simplify=FALSE)

[[1]]
            TLT.Close
UPRO.Close -0.6394617

[[2]]
           SPXU.Close
UPRO.Close  0.0947242

[[3]]
           SPXU.Close
TLT.Close -0.06216682
like image 136
Joshua Ulrich Avatar answered Apr 30 '23 22:04

Joshua Ulrich