Importing and transforming multiple instruments

Importing and Managing Financial Data in R

Joshua Ulrich

Quantitative Analyst & quantmod Co-Author and Maintainer

Download instruments into a custom environment

# Create new environment
data_env <- new.env()

# Use getSymbols to load data into the environment getSymbols(c("SPY", "QQQ"), env = data_env, auto.assign = TRUE)
"SPY" "QQQ"
# Look at a few rows of the SPY data
head(data_env$SPY, 3)
            SPY.Open SPY.High SPY.Low SPY.Close SPY.Volume SPY.Adjusted
 2007-01-03   142.25   142.86  140.57    141.37   94807600     114.8094
 2007-01-04   141.23   142.05  140.61    141.67   69620600     115.0530
 2007-01-05   141.33   141.40  140.38    140.54   76645300     114.1353
Importing and Managing Financial Data in R

Using lapply()

  • Loops over all objects in environment
  • Combine list of function results into one object using do.call()
    • First argument (what) is the function to be called
    • Second argument (args) is a list of arguments to pass
Importing and Managing Financial Data in R

Extract volume and merge into one object

# Extract volume column from each object
adjusted_list <- lapply(data_env, Ad)

# Merge each list element into one object adjusted <- do.call(merge, adjusted_list)
head(adjusted)
            QQQ.Adjusted SPY.Adjusted
 2007-01-03     39.47694     114.8094
 2007-01-04     40.22558     115.0530
 2007-01-05     40.03385     114.1353
 2007-01-08     40.06124     114.6632
 2007-01-09     40.26210     114.5658
 2007-01-10     40.73684     114.9475
Importing and Managing Financial Data in R

Let's practice!

Importing and Managing Financial Data in R

Preparing Video For Download...