Unfortunately you can't use strings with a matrix in R. The matrix data structure is homogeneous so the entire data must be the same class. You need to use a data frame for this task, and you're in luck. You might try the tidyquant
package which takes care multiple assets. It doesn't require for-loops so it will save you a significant amount of code. The tq_get()
function is responsible for getting stock prices. Here's a quick example with stock prices. You can do the same thing with FRED symbols (see below).
Getting stock prices:
library(tidyquant)
# Get some stock prices for multiple stocks
c("FB", "GOOG", "AMZN", "NFLX") %>%
tq_get(get = "stock.prices",
from = "2013-01-01",
to = "2016-12-31")
#> # A tibble: 4,032 × 8
#> symbol date open high low close volume adjusted
#> <chr> <date> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 FB 2013-01-02 27.44 28.18 27.42 28.00 69846400 28.00
#> 2 FB 2013-01-03 27.88 28.47 27.59 27.77 63140600 27.77
#> 3 FB 2013-01-04 28.01 28.93 27.83 28.76 72715400 28.76
#> 4 FB 2013-01-07 28.69 29.79 28.65 29.42 83781800 29.42
#> 5 FB 2013-01-08 29.51 29.60 28.86 29.06 45871300 29.06
#> 6 FB 2013-01-09 29.67 30.60 29.49 30.59 104787700 30.59
#> 7 FB 2013-01-10 30.60 31.45 30.28 31.30 95316400 31.30
#> 8 FB 2013-01-11 31.28 31.96 31.10 31.72 89598000 31.72
#> 9 FB 2013-01-14 32.08 32.21 30.62 30.95 98892800 30.95
#> 10 FB 2013-01-15 30.64 31.71 29.88 30.10 173242600 30.10
#> # ... with 4,022 more rows
Getting FRED data:
library(tidyquant)
# Get some economic data for multiple FRED codes
c("CPIAUCSL", "A191RL1Q225SBEA", "IC4WSA") %>%
tq_get(get = "economic.data")
#> # A tibble: 691 × 3
#> symbol date price
#> <chr> <date> <dbl>
#> 1 CPIAUCSL 2007-01-01 203.437
#> 2 CPIAUCSL 2007-02-01 204.226
#> 3 CPIAUCSL 2007-03-01 205.288
#> 4 CPIAUCSL 2007-04-01 205.904
#> 5 CPIAUCSL 2007-05-01 206.755
#> 6 CPIAUCSL 2007-06-01 207.234
#> 7 CPIAUCSL 2007-07-01 207.603
#> 8 CPIAUCSL 2007-08-01 207.667
#> 9 CPIAUCSL 2007-09-01 208.547
#> 10 CPIAUCSL 2007-10-01 209.190
#> # ... with 681 more rows
There's a bunch of options to choose from. I call them "getters", and you have most of the quantmod
data sources that you can choose from. Good luck!