-
Notifications
You must be signed in to change notification settings - Fork 0
/
timeseries.R
64 lines (58 loc) · 1.6 KB
/
timeseries.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
rle2 <- function(x) {
# Modified version of base::rle that includes indexes
if (!is.vector(x) && !is.list(x))
stop("'x' must be an atomic vector")
n <- length(x)
if (n == 0L)
return(structure(list(lengths = integer(), values = x),
class = "rle"))
y <- x[-1L] != x[-n]
i <- c(which(y | is.na(y)), n)
data.frame(lengths = diff(c(0L, i)), values = x[i], index = i)
}
getRuns <- function(x, decreasing=F) {
# Function to calculate runs of equal values for every element in a vector
if (decreasing) {
x <- rev(x)
}
runs <- list()
done <- FALSE
while (!done) {
y <- rle2(x)
y <- subset(y, values!=0)
if (nrow(y)>0) {
runs[[length(runs)+1]] <- y
x[y[,'index']] <- 0
} else {
done <- TRUE
}
}
runs <- do.call(rbind, runs)
if (decreasing) {
runs <- runs[order(runs$index, decreasing=T),]
runs$index <- rev(runs$index)
}
runs <- runs[order(runs$index),]
return(runs)
}
toDate <- function(datestr) {
as.Date(as.character(datestr),'%Y%m%d')
}
get.bday <- function(sdt, edt, region='US') {
# Return business days for given date range
# Expects YYYYMMDD for date strings
library(timeDate)
if (class(sdt) != 'Date') {
sdt <- toDate(sdt)
edt <- toDate(edt)
}
dtes <- seq(sdt, edt, by=1)
years <- as.numeric(unique(strftime(dtes,'%Y')))
dtes <- as.timeDate(dtes)
if (region=='US') {
dtes <- dtes[isBizday(dtes, holidays=holidayNYSE(years), wday=1:5)]
} else if (region=='LN') {
dtes <- dtes[isBizday(dtes, holidays=holidayLONDON(), wday=1:5)]
}
return(strftime(dtes, '%Y%m%d'))
}