R/srwalk.R

Defines functions srwalk

Documented in srwalk

#' @title A generator of sample random walks
#'
#'
#' @description `srwalk()` generates a time-series of sampled
#' scaled random walks
#'
#'
#' @param n An integer. The number of random walks generated by
#' `srwalk()`.
#' @param from A Date. The beginning of the process.
#' @param to A Date. The end of the process. If not provided, `len` is
#' used instead.
#' @param len An integer. The length of the random process.
#' @param prob A double \in [0, 1]. The probability of getting Head
#' (the process goes up).
#' @param by An integer, a character, or a \code{\link[base]{difftime}}
#' object. The interval between each process' steps. See `Details`.
#' @param seed  An integer. To make the random walks processes
#' reproducible.
#' @param n  An integer. The number of samples generated by the function.
#' @param ... Not yet used.
#'
#'
#' @details
#' The possible values for `by` are those taken by the `by` argument of the
#' \code{\link[base]{seq.Date}} function.
#'
#'
#' @examples
#' # Generate a zoo object of 20 sampled symmetric random walks ordered by date
#' # from today and up to the next 360 upcoming days
#' srwalk(n = 20)
#'
#'
#' @return `srwalk()` outputs a zoo object containing `n` random walks.
#' The so generated random walks are independent and identically distributed
#' with the same period coverage.
#'
#'
#' @export

srwalk <- function(n = 1,
                   from = Sys.Date(),
                   to,
                   len = 365,
                   prob = .5,
                   R = 1,
                   by = 'day',
                   seed = 1,
                   ...){

  set.seed(seed)
  if (missing(to)) to <- from + len

  partition <- seq(from = from,
                   to = to,
                   by = by)

  multiplier <- sqrt(as.numeric(diff(partition)))

  # 1: head, -1: tail
  x <- rep(list(c(1, -1)), n)

  X <- lapply(x, sample,
              size = length(multiplier),
              replace = T,
              prob = c(prob, 1-prob))

  sampledRandomWalk <- structure(
    lapply(X, FUN = function(x){c(0, cumsum(x) * multiplier)}),
    names = paste0("P",
                   stringr::str_pad(
                     1:length(X),
                     width = floor(log(length(X), base = 10)) + 1,
                     pad = "0")
                   )
  )

  zoo::zoo(data.frame(sampledRandomWalk), order.by = partition)
}
AnthonyTedde/RandomProcesses documentation built on Dec. 14, 2021, 10:39 a.m.