-1

I would like to use the yahoofinancer (https://cran.r-project.org/web/packages/yahoofinancer/index.html) package in RStudio to download data from Yahoo's API.

To do so, I need to set a Ticker first. Ticker itself is a class. I would like to use a vector of company symbols to set many Tickers. Something like

stocks<-c("IBM", "AAPL") 
aapl <- Ticker$new('aapl') 
IBM  <- Ticker$new('ibm')

But for more symbols.

To get this, I tried to process the stocks vector in a loop.

library(yahoofinancer) 
x <- c() 
for (i in stocks){ 
  x[i]<-Ticker$new(i) 
  assign(i, x[i]) 
}

This returned the following error:

> Error in x[i] <- Ticker$new(i) : invalid type/length (environment/0) in vector allocation

How can I resolve this error?

I would like to get something like:

enter image description here

margusl
  • 7,804
  • 2
  • 16
  • 20
JR1
  • 1
  • 2
  • Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. – Community Jan 09 '23 at 03:04

1 Answers1

0

You could store your ticker instances in a single list:

library(yahoofinancer)
stocks <-c("IBM", "AAPL") 
# add names so lapply could return named list
(names(stocks) <- stocks)
#> [1] "IBM"  "AAPL"

# create a list of tickers:
tickers <- lapply(stocks, Ticker$new)

# get_history() for single ticker:
tickers$IBM$get_history(interval = "1wk")
#>                  date   volume   high    low   open  close adj_close
#> 1 2023-01-02 05:00:00 13648000 144.25 140.01 141.10 143.70    143.70
#> 2 2023-01-09 05:00:00 14580100 146.66 142.90 144.08 145.89    145.89
#> 3 2023-01-16 05:00:00 14264100 147.18 139.75 146.42 140.62    140.62
#> 4 2023-01-19 21:00:02  4803311 142.23 139.75 140.00 140.62    140.62

# get_history() for all tickers in the list:
lapply(tickers, \(x) x$get_history(interval = "1wk"))
#> $IBM
#>                  date   volume   high    low   open  close adj_close
#> 1 2023-01-02 05:00:00 13648000 144.25 140.01 141.10 143.70    143.70
#> 2 2023-01-09 05:00:00 14580100 146.66 142.90 144.08 145.89    145.89
#> 3 2023-01-16 05:00:00 14264100 147.18 139.75 146.42 140.62    140.62
#> 4 2023-01-19 21:00:02  4803311 142.23 139.75 140.00 140.62    140.62
#> 
#> $AAPL
#>                  date    volume    high    low   open  close adj_close
#> 1 2023-01-02 05:00:00 369880400 130.900 124.17 130.28 129.62    129.62
#> 2 2023-01-09 05:00:00 333283500 134.920 128.12 130.47 134.76    134.76
#> 3 2023-01-16 05:00:00 191489100 138.610 133.77 134.83 135.27    135.27
#> 4 2023-01-19 21:00:04  58280413 136.245 133.77 134.08 135.27    135.27

Created on 2023-01-20 with reprex v2.0.2

margusl
  • 7,804
  • 2
  • 16
  • 20