Reputation: 1004
I am using the package quantmod to get historical share prices.
I want to create a loop to pull back the prices and as part of the loop I want to create a dataframe for each share. I have been unsuccessful so far with the below code, it gets the share prices as expected but this is returned as a xts object whereas I require the information as a dataframe - the as.data.frame part of the code doesn't do anything...
library(quantmod)
shares<-c("BARC.L", "BP.L", "DLG.L")
for(i in 1:length(shares)){
#gets share prices
getSymbols((paste(shares[i])), from = "2018-01-01")
#put the data into a dataframe (doesn't work).
shares[i]<-as.data.frame(shares[i])
}
The end result that I want is 3 dataframes - 1 for each share.
Can anyone suggest modifications to the code to achieve this please?
Upvotes: 0
Views: 318
Reputation: 23598
Personally I would do it like this:
library(quantmod)
shares<-c("BARC.L", "BP.L", "DLG.L")
my_shares <- lapply(shares, function(x) getSymbols(x, from = "2018-01-01", auto.assign = FALSE))
names(my_shares) <- shares
Or if you need the dates as a column instead of rownames:
my_shares <- lapply(shares, function(x) {
out <- getSymbols(x, from = "2018-01-01", auto.assign = FALSE)
out <- data.frame(dates = index(out), coredata(out))
return(out)
})
names(my_shares) <- shares
Or if you need everything in a tidy dataset:
library(tidyquant)
my_shares <- tq_get(shares)
my_shares
# A tibble: 7,130 x 8
symbol date open high low close volume adjusted
<chr> <date> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 BARC.L 2008-01-02 464. 483. 460. 466. 38104837 344.
2 BARC.L 2008-01-03 466. 472. 458. 470. 33215781 347.
3 BARC.L 2008-01-04 466. 476. 447. 449. 42710244 332.
4 BARC.L 2008-01-07 447. 452. 433. 436. 58213512 322.
5 BARC.L 2008-01-08 439. 447. 421. 437. 105370539 322.
6 BARC.L 2008-01-09 432. 434. 420. 424. 71059078 313.
7 BARC.L 2008-01-10 428. 431. 413. 418. 54763347 309.
8 BARC.L 2008-01-11 416. 437. 416. 430. 72467229 317.
9 BARC.L 2008-01-14 430. 448. 427. 444. 56916500 328.
10 BARC.L 2008-01-15 445. 452. 428. 429. 77094907 317.
# ... with 7,120 more rows
Upvotes: 2
Reputation: 416
Firstly, I suggest you use the help() function that comes with R packages if you're not already doing so. I noticed in help(getSymbols) that you need to set env=NULL to actually return the data. With that, I've also made a list object so you can store the data as data.frames like you requested:
library(quantmod)
shares<-c("BARC.L", "BP.L", "DLG.L")
# initialize a list to store your data frames
df_list <- as.list(rep(data.frame(), length(shares)))
for (i in 1:length(shares)) {
#gets share prices
df_list[[i]] <- as.data.frame(getSymbols(shares[i], from = "2018-01-01", env=NULL))
}
# so you can access by name, e.g. df_list$DLG.L
names(df_list) <- shares
Upvotes: 2