Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize ts_brownian_motion() #395

Closed
spsanderson opened this issue Jan 7, 2023 · 0 comments
Closed

Optimize ts_brownian_motion() #395

spsanderson opened this issue Jan 7, 2023 · 0 comments
Assignees
Labels
enhancement New feature or request

Comments

@spsanderson
Copy link
Owner

spsanderson commented Jan 7, 2023

Updated Function:

bm <- function(.time = 100, .num_sims = 10, .delta_time = 1./365, 
               .initial_value = 0, .return_tibble = TRUE){
  
  # Tidyeval ----
  num_sims <- as.numeric(.num_sims)
  t <- as.numeric(.time)
  initial_value <- as.numeric(.initial_value)
  delta_time <- as.numeric(.delta_time)
  return_tibble <- as.logical(.return_tibble)
  
  # Matrix of random draws - one for each simulation
  rand_matrix <- matrix(rnorm(t * num_sims, mean = 0, sd = sqrt(delta_time)),
                        ncol = num_sims, nrow = t)
  colnames(rand_matrix) <- paste0("sim_number ", 1:num_sims)
  
  # Get the Brownian Motion and convert to price paths
  ret <- apply(rbind(rep(initial_value, num_sims), rand_matrix), 2, cumsum)
  
  # Return
  if (return_tibble){
    ret <- ret %>%
      dplyr::as_tibble() %>%
      dplyr::mutate(t = 1:(t+1)) %>%
      dplyr::select(t, dplyr::everything()) %>%
      tidyr::pivot_longer(-t)
  }
  
  return(ret)
}

Examples:

> benchmark(
+   current = {
+     ts_brownian_motion(.num_sims = 500, .time = 100, .delta_time = 1)
+   },
+   new = {
+     bm(.num_sims = 500, .time = 100, .delta_time = 1)
+   },
+   replications = 25,
+   columns = c("test","replications","elapsed","relative","user.self","sys.self"  )
+ ) %>%
+   arrange(relative)
     test replications elapsed relative user.self sys.self
1     new           25    0.49    1.000      0.48     0.00
2 current           25   24.33   49.653     23.83     0.48
@spsanderson spsanderson self-assigned this Jan 7, 2023
@spsanderson spsanderson added the enhancement New feature or request label Jan 7, 2023
@spsanderson spsanderson added this to the healthyR.ts 0.2.7 milestone Jan 7, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Development

No branches or pull requests

1 participant