library(ggplot2)
library(dplyr)

Plot random walk

create_random_walk <- function(number=1000){
    data.frame(x = rnorm(number),
               rown = c(1:1000)) %>%
        mutate(xt = cumsum(x))
}


p <- ggplot() + aes(x = rown, y = xt)

p + geom_line(data = create_random_walk())

p + geom_line(data = create_random_walk())

Plot several random walks on one plot

# More lines on one plots
set.seed(501)
randomwalkdata <- rbind(mutate(create_random_walk(), run = 1),
                         mutate(create_random_walk(), run = 2),
                         mutate(create_random_walk(), run = 3),
                         mutate(create_random_walk(), run = 4))
ggplot(randomwalkdata, aes(x = rown, y = xt, color=as.factor(run))) + 
  geom_line() 

More general autoregressive process

Inspired by Tavish Srivastava’s step by step guide to learn time series modelling. \(x_t\) follows a data generating process based on the normal distribution. The data generating process depends on the previous observation plus an error term: \[x_t = \rho x_{t-1} + e_t\]

When \(\rho=0\), \(x_t\) is a stationary series, drawn from a normal distribution. When \(\rho=1\), \(x_t\) is a random walk. We are interested in what is happening when \(\rho\) varies.

### Visualise several versions of the rho paramater in one data frame
#' This function will be used as such: group_by(rho) %>% do(dgp2()).
#' Therefore dtf should contain only one rho parameter.
#' @param dtf a data frame containing one rho parameter, 
dgp2 <- function(dtf){ 
  rho <- unique(dtf$rho)
  stopifnot(length(rho)==1)
  dtf <- dtf %>%
    mutate(xt = Reduce(function(u, v) rho * u + v, x, accumulate = TRUE))
}

create_random_data <- function(number=1000){
  merge(data.frame(x = rnorm(number),
                   rown = c(1:1000)),
        data.frame(n = 100,
                   rho = c(0,0.5,0.9,0.99,1,1.01))) %>%
    group_by(rho) %>%
    do(dgp2(.)) %>%
    data.frame %>%
    mutate(rho = paste("rho =",rho))
  }


p <- ggplot() + facet_wrap(~rho, scales = "free_y") + 
  aes(x = rown, y = xt)

p + geom_line(data=create_random_data())

p + geom_line(data=create_random_data())

set.seed(501)
randomdata2 <- rbind(mutate(create_random_data(), run = 1),
                     mutate(create_random_data(), run = 2),
                     mutate(create_random_data(), run = 3),
                     mutate(create_random_data(), run = 4))
ggplot(randomdata2, aes(x = rown, y = xt, color=as.factor(run))) + 
  geom_line() + facet_wrap(~rho, scales = "free_y")

# Same plot with fixed scale remove the explosive value
ggplot(filter(randomdata2, rho!="rho = 1.01"),
       aes(x = rown, y = xt, color=as.factor(run))) + 
  geom_line() + facet_wrap(~rho, scales = "fixed")