[R] Problem with tq_mutate_xy() from the tidyquant package

Joshua Ulrich josh.m.ulrich at gmail.com
Sat Oct 28 15:51:29 CEST 2017


On Wed, Oct 18, 2017 at 9:54 AM, Eric Berger <ericjberger at gmail.com> wrote:
> I was able to reproduce the problem with this self-contained example. Maybe
> it could be reproduced with an even smaller one ...
>
Thanks for the reproducible example.

>
> library(tidyquant)  # Loads tidyverse, tidyquant, financial pkgs, xts/zoo
> library(xts)
>
> dtV <- as.Date("2017-01-01") + 1:100
> locL <- list( foo=xts(rnorm(100), order.by=dtV), bar=xts(rnorm(100),
> order.by=dtV) )
> fullXts <- do.call(merge,locL)
> smallXts <- fullXts["2017-02-01::"]
>
> rolling_corrOnePair <- function( aXts, col1, col2, window ) {  #window =
> window size in days
>   tbl  <- timetk::tk_tbl( aXts[,c(col1,col2)], rename_index="date" )
>   colnames(tbl) <- c("date","x","y")
>   naV <- sapply(1:nrow(tbl), function(i) any(is.na(tbl[i,])) )
>   tbl <- tbl[!naV,]# remove any rows with NAs
>    tq_mutate_xy( data=tbl, x = x, y = y, mutate_fun=runCor,
>                 n = window, use="all.obs",  # runCor args
>                 col_rename = "rolling_corr" ) # tq_mutate args
> }
>
> foo <- rolling_corrOnePair( aXts=smallXts, col1="foo", col2="bar",
> window=30 )
>
> ## This produces the error
> # Error in runCov(x, y, n, use = use, sample = sample, cumulative ) :
> #   n = 30 is outside valid range: [1, 1]
>
The error says that n=1 is only valid value for 'n' in the call to
TTR::runCov(), and you have n=30.  TTR::runCor() will throw that error
when there aren't enough observations for a n-period rolling
calculation.

I have no idea why that happens though, because the simple case below works.
corr <- TTR::runCor(fullXts$foo, fullXts$bar, n = 30)  # this is fine

So the problem must be something in your function or in the other
packages you're using.


> Thanks for any help,
>
> Eric
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



-- 
Joshua Ulrich  |  about.me/joshuaulrich
FOSS Trading  |  www.fosstrading.com
R/Finance 2017 | www.rinfinance.com



More information about the R-help mailing list