Created
September 3, 2018 14:06
-
-
Save dirknbr/457bdf32851b53e76538bb574a6973ea to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
change <- function(x, days = 10, method = 'last', intvl = .9) { | |
# distribution of change over days | |
stopifnot(days < length(x)) | |
stopifnot(method %in% c('last', 'max', 'min')) | |
N <- length(x) | |
vec <- c() | |
for (i in 1:(N - days)) { | |
extract <- x[i:(i + days)] | |
lastchange <- extract[days] / extract[1] - 1 | |
maxchange <- max(extract) / extract[1] - 1 | |
minchange <- min(extract) / extract[1] - 1 | |
if (method == 'last') { | |
vec <- c(vec, lastchange) | |
} else if (method == 'max') { | |
vec <- c(vec, maxchange) | |
} else { | |
vec <- c(vec, minchange) | |
} | |
} | |
if (method == 'last') { | |
# centered | |
q1 <- quantile(vec, (1 - intvl) / 2 ) | |
q2 <- quantile(vec, intvl + (1 - intvl) / 2 ) | |
cat('low', q1, 'median', median(vec), 'up', q2, '\n') | |
} else if (method == 'max') { | |
q1 <- quantile(vec, intvl) | |
cat('median', median(vec), 'up', q1, '\n') | |
} else { | |
q1 <- quantile(vec, 1 - intvl) | |
cat('low', q1, 'median', median(vec), '\n') | |
} | |
plot(density(vec)) | |
} | |
x <- rnorm(100, 10, 1) | |
x <- 100 + arima.sim(list(ar = .9, ma = .1), 100) | |
plot(x) | |
change(x, method = 'last') | |
change(x, method = 'max') | |
change(x, method = 'min') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment