[R-SIG-Finance] Counting consecutive equally signed items in a time series

Gabor Grothendieck ggrothendieck at gmail.com
Fri Dec 18 12:35:41 CET 2009


You can get the run lengths using rle:

> library(zoo)
> set.seed(1)
> z <- zoo(rnorm(25))
> rle(sign(coredata(z)))
Run Length Encoding
  lengths: int [1:14] 1 1 1 2 1 3 1 2 2 1 ...
  values : num [1:14] -1 1 -1 1 -1 1 -1 1 -1 1 ...


On Fri, Dec 18, 2009 at 6:30 AM, Mark Breman <breman.mark at gmail.com> wrote:
> Hello,
>
> I have a univariate financial time series with daily returns (xts or zoo)
> and I would like to count the number of consecutive equally signed returns
> in the series, i.e. the number of consecutive up- and down-days (this
> probably has some fancy mathematical name which I can't seem to find).
>
> Example:
>
>> usod
>               Adjusted
> 2009-11-02           NA
> 2009-11-03  0.016001969
> 2009-11-04  0.009026592
> 2009-11-05 -0.004656863
> 2009-11-06 -0.027707809
> 2009-11-09  0.019753086
> 2009-11-10 -0.002227171
> 2009-11-11  0.003452528
> 2009-11-12 -0.032594856
> 2009-11-13 -0.003834356
> 2009-11-16  0.029039464
> 2009-11-17  0.004693676
> 2009-11-18  0.004671748
> 2009-11-19 -0.025466465
> 2009-11-20 -0.006088280
> 2009-11-23 -0.001015744
> 2009-11-24 -0.020736133
>
> I would like to get the following vector for this series:
>
> 2, -2, 1, -1, 1, -2, 3, -4
>
> meaning: 2 updays, 2 downdays, 1 upday, 1 downday etc.
>
> Is there a function in R which does that?
>
> Kind regards,
>
> -Mark-
>
>        [[alternative HTML version deleted]]
>
> _______________________________________________
> R-SIG-Finance at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-sig-finance
> -- Subscriber-posting only.
> -- If you want to post, subscribe first.
>



More information about the R-SIG-Finance mailing list