Get startedGet started for free

Importing and transforming multiple instruments

1. Importing and transforming multiple instruments

Now that you've learned how to extract columns from a single data object that you've imported, let's learn how to import and transform multiple instruments.

2. Download instruments into a custom environment

Now let's explore a more general approach, using tools in quantmod and base R packages. getSymbols() can load data into a custom environment. First, use the new.env() function to create an environment. Then pass that environment to getSymbols() using the "env" argument. You also need to make sure to set auto.assign = TRUE, so getSymbols() loads the data instead of returning it.

3. Using lapply()

Now you can use lapply() to loop over and apply a function to all the objects in the environment. You can then combine the list of function results into one object using the do.call() function. You might remember using the do.call() function in the Manipulating Time Series Data in R with xts & zoo course. It's a way to programmatically construct and evaluate a function call, which can save a lot of typing. The first argument to do.call() is the function you want to call, and the second argument is a list of arguments you want to pass to the function you want to call.

4. Extract volume and merge into one object

Let's look at an example that extracts the adjusted close column from each symbol and combines them into one object. First, use lapply() to loop over and call the Ad() function on all the objects in "data_env". Now you have a list of xts objects that contain adjusted close prices, and that list is exactly what you need to pass to do.call(). We want to merge all the xts objects into one object, so we set the first argument to "merge", and the second to our list. Imagine all the typing you would save wif you had more than two instruments!

5. Let's practice!

Now, it's your turn to practice importing and transforming multiple instruments in the exercises.