1

When I run function CTI(Close ,n=10), it show Caused by error:! cti_10 must be size 5550 or 1, not 5541. . How to fix it ? Thanks!

library(tidyverse)
library(TTR)
data(ttrc)
ttrc %>% mutate( cti_10 = CTI(Close ,n=10))
anderwyang
  • 1,801
  • 4
  • 18
  • 2
    The error suggests that `CTI` is not returning a value for each of the 5550 rows of your data frame `ttrc`. Without more details, it's difficult to say more. Incidentally, you may want to *save* the results of the function call. You aren't at the moment because you aren't assigning the results of the `mutate` call... – Limey Aug 02 '23 at 07:36
  • Thanks for your reply , is the way to cbind CTI result which align bottom ? (the missing value filled by NA ) – anderwyang Aug 02 '23 at 09:51
  • Hmm. Reading the documenttaion (always a good idea!), "The CTI measures the Spearman correlation between the price and the ideal trend line with slope of slope, over the past n days". So if you have m data points, you can calculate `CTI` for m - n + 1 of them, where n is the value of n you pass to `CTI`. And 5550 - 10 + 1 is 5541. I doubt that's a co-incidence. I'm not familiar with `TTR` and your example is not reproducible, but it looks like you need to prepend(?) 10 - 1 = 9 `NA` values to the start of the vector returned by `CTI` if you want to add a new column to your data frame. – Limey Aug 02 '23 at 10:25
  • Thanks , append NA to the vector can solver it – anderwyang Aug 02 '23 at 10:27
  • 1
    "removed the error" is not the same as "gives the correct answer". I strongly urge you to consider whether you need to _prepend_ rather than _append_ the `NA`s. – Limey Aug 02 '23 at 10:52
  • Thanks for your advice. i will consider prepend or append according the true reason – anderwyang Aug 03 '23 at 00:59

1 Answers1

1

This is because you're passing a numeric vector to CTI(), which can't be converted to an xts object inside CTI(). CTI() calls rollapply(), which doesn't pad the result with leading NA. That's why it has fewer observations than the input. I'll patch TTR so leading NA are added.

In the meantime, you can use this as a work-around. Make sure you have xts version 0.13.1 for as.xts() to automatically find the Date column in ttrc.

library(TTR)
data(ttrc)
ttrc$cti_10 <- CTI(xts::as.xts(ttrc)$Close, n = 10)

EDIT: This is fixed on GitHub now and will be included in the next TTR release. You can install the development version with:

remotes::install_github("joshuaulrich/TTR")
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418