Get startedGet started for free

Nested foreach loops for price trends

The stock market is well-known for its unpredictable behavior. You work for an investment firm and your boss wants to see the trends in stock prices across a window of one week.

You have acquired the data of daily stock prices for ten tech companies since 2015. The Data Scientist on your team has provided code to fit regression models. You plan on parallelizing this code using foreach(), %:%, and%dopar%.

The total number of columns to iterate over is saved in your workspace as ncols, and number of rows as nrows. parallel, doParalel, and foreach packages have been loaded for you. The cluster, cl, has been set up. You need to write the nested foreach() loops.

This exercise is part of the course

Parallel Programming in R

View Course

Exercise instructions

  • Register the cluster to use with foreach loops.
  • Specify a foreach loop to iterate over columns one to ncols, collect the results with "cbind", and use the nesting operator.
  • Specify another foreach loop to iterate over rows one to nrows, collect results with "c", and use the do-parallel operator.
  • Stop the cluster when all computations are done.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Register the cluster to use with %dopar%
___
# Use foreach loop to iterate over columns one to ncol
moving_trend <- foreach(___, ___) %:%
# Iterate over rows one to nrows within each column
  foreach(___, ___) %dopar% {
    prices <- data[row:(row + 6), col]
    if (any(is.na(prices))) NA
    else {days <- 1:7
          model <- lm(prices ~ days)
          model$coefficients[2]}
  }
# Stop cluster  
___
print(paste("Total number of models fit:", sum(!is.na(moving_trend))))
Edit and Run Code