3

I'm attempting to carry out some stock portfolio simulations. Using the Package 'quantmod' I have downloaded price data on multiple securities. I would like to accomplish two things.

1) I'd like to create a list/array of the xts objects, where each security ticker symbol would correspond to a time series object in the list.

2) More importantly I'd like to create a time series data frame with the adjusted share price for each security, by day.

I have the following code, which downloads all the price data.

library(quantmod)

tickers <- c("SNC.TO", "PHII", "HBC.TO", "GTE", "MOO",
             "MND.TO", "STKL", "SXC","XIU.TO")

for(i in tickers) {
  getSymbols(i, from = "2010-06-30", to = "2015-06-30") 
}

This is what I have so far to try and create the list of dataframes

pframe <- list()
for(i in tickers) {
  pframe[[i]] <- assign(i)
}
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
Fanderson
  • 90
  • 9

2 Answers2

5

The simplest way to do this is to load all the data into a new environment. Then you can use eapply to extract all the adjusted close columns into a list. Finally, you can use do.call to merge all the adjusted close prices in the list into one xts object.

library(quantmod)
tickers <- c("SNC.TO", "PHII", "HBC.TO", "GTE", "MOO",
             "MND.TO", "STKL", "SXC","XIU.TO")
dataEnv <- new.env()
getSymbols(tickers, from="2010-06-30", to="2015-06-30", env=dataEnv)
plist <- eapply(dataEnv, Ad)
pframe <- do.call(merge, plist)
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
  • There are so many other, related things you can do with R. Here are some ideas to whet your appetite. – ASH Sep 14 '15 at 14:46
  • https://systematicinvestor.wordpress.com/systematic-investor-toolbox/ https://systematicinvestor.wordpress.com/2011/12/06/multi-asset-backtest-rotational-trading-strategies/ https://thierrymoudiki.wordpress.com/2014/08/21/impact-of-correlated-predictions-on-the-variance-of-an-ensemble-model/ https://rbresearch.wordpress.com/ – ASH Sep 14 '15 at 14:48
0

with lapply you can create a llist with xts object of your portfolio

tickers = c("SNC.TO", "PHII", "HBC.TO", "GTE", "MOO",
             "MND.TO", "STKL", "SXC","XIU.TO")
stock_data = lapply(1:length(tickers), function(i) quantmod::getSymbols(Symbols = tickers[i], src = "yahoo", from = base::as.Date("2000-04-09"), to = base::as.Date("2022-12-19"), auto.assign = F))

To create the data frame you can do as the other guy suggested. To create a dataframe, I suggest you cancel or approximate the values of the missing dates of a title.

df = do.call(merge,stock_data)
df = na.omit(df)