如何使用 yahoofinancer 获取多个符号

问题描述 投票:0回答:1

我想使用 RStudio 中的 yahoofinancer (https://cran.r-project.org/web/packages/yahoofinancer/index.html) 包从 Yahoo 的 API 下载数据。

为此,我需要先设置一个股票代码。 Ticker 本身就是一个类。 我想使用公司符号向量来设置许多股票代码。 类似的东西

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

但需要更多符号。

为了得到这个,我尝试循环处理股票向量。

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

这返回了以下错误:

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

如何解决此错误?

我想要得到类似的东西:

r yahoo-finance
1个回答
0
投票

您可以将股票代码实例存储在单个列表中:

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

创建于 2023-01-20,使用 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.