Search code examples
rloopsquantmod

loop through new.env() R (quantmod)


I am new to R, loop and quantmod. I am trying to build a database that can be used be used easier for calculations (in a column format).

I was wondering how you would use a "loop" to automate the process below. I am simply binding two datasets together.

As you can see, I have bound two datasets together using rbind, Google and Apple stock prices. If I was to have 100 stocks, this process would take a very long time, thus I was wondering how I could automate this process?

library(quantmod)
tickers<- c("AAPL", "GOOG")
all<- new.env()
getSymbols(tickers,src="google", env = all, from = Sys.Date()-100, to = Sys.Date())

apple_share<- all$AAPL
colnames(apple_share)<- c("Open", "High", "Low", "Close", "Volume")
apple_share$Ticker<- rep(1, nrow(apple_share))

google_share<- all$GOOG
colnames(google_share)<- c("Open", "High", "Low", "Close", "Volume")
google_share$Ticker<- rep(2, nrow(google_share))

combined_data<- rbind(apple_share,google_share)

Many thanks,

Shoups


Solution

  • The package tidyquant was created exactly for tasks like the one you asked for. Assuming that you updated the quantmod package to version 0.4-9, which again allows price downloads from YAHOO, the tq_get function will download the data and with "grouping by symbol” you will get the desired output.

    > library(tidyquant)
    stocks <- c("AAPL", "GOOG", "NFLX") %>%
         tq_get(get  = "stock.prices",
                from = "2010-01-01",
                to   = "2015-12-31") %>%
         group_by(symbol)
    
    > stocks
    Source: local data frame [4,527 x 8]
    Groups: symbol [3]
    
    # A tibble: 4,527 x 8
       symbol       date   open   high    low  close    volume
        <chr>     <date>  <dbl>  <dbl>  <dbl>  <dbl>     <dbl>
     1   AAPL 2010-01-04 213.43 214.50 212.38 214.01 123432400
     2   AAPL 2010-01-05 214.60 215.59 213.25 214.38 150476200
     3   AAPL 2010-01-06 214.38 215.23 210.75 210.97 138040000
     4   AAPL 2010-01-07 211.75 212.00 209.05 210.58 119282800
     5   AAPL 2010-01-08 210.30 212.00 209.06 211.98 111902700
     6   AAPL 2010-01-11 212.80 213.00 208.45 210.11 115557400
     7   AAPL 2010-01-12 209.19 209.77 206.42 207.72 148614900
     8   AAPL 2010-01-13 207.87 210.93 204.10 210.65 151473000
     9   AAPL 2010-01-14 210.11 210.46 209.02 209.43 108223500
    10   AAPL 2010-01-15 210.93 211.60 205.87 205.93 148516900
    # ... with 4,517 more rows, and 1 more variables: adjusted <dbl>