在 R 中使用 quantmode getSymbols() 时如何排除缺失的条目?

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

所以我只是尝试使用 yfR 和 quantmod 从 YH 中额外添加 100 只不同的股票,然后计算这些股票的每日回报(最终我将使用这些数据来计算每只股票的平均每日回报以及在 GA 中使用的协方差) ).

这是我尝试执行此操作的代码:

library(yfR)
library(quantmod)

df_ftse <- yf_index_composition("FTSE")

assets <- sample(df_ftse$ticker, 100)

dailyReturns = lapply(assets, function(sym) {
  dailyReturn(na.omit(getSymbols(sym, from="2021-01-01", to="2022-01-01", auto.assign=FALSE)))
})

但偶尔如果股票有问题,我会从 quantmod 收到此错误:

Error in getSymbols.yahoo(Symbols = "ABF", env = <environment>, verbose = FALSE,  : 
  Unable to import “ABF”.
attempt to set an attribute on NULL

我知道有时 getSymbols 出于某种原因无法获取股票的数据。 有没有办法自动排除“损坏”或错误的库存?我认为 na.omit 可能会有所帮助,但我认为我可能使用错误。

找不到任何其他解决方案,因此认为值得四处询问。谢谢!

r genetic-algorithm stock quantmod portfolio
1个回答
0
投票
library(tidyquant)
library(tidyverse)

tickers <- yfR::yf_index_composition("FTSE") %>%
  pull(ticker)

df <- tq_get(tickers, from = "2021-01-01", to = "2022-01-01") %>%
  group_by(symbol) %>%
  tq_transmute(select = adjusted,
               mutate_fun = periodReturn,
               period = "daily") 

# A tibble: 9,607 × 3
# Groups:   symbol [39]
   symbol date       daily.returns
   <chr>  <date>             <dbl>
 1 III    2021-01-04       0      
 2 III    2021-01-05       0.00305
 3 III    2021-01-06       0.0638 
 4 III    2021-01-07       0.00286
 5 III    2021-01-08      -0.00285
 6 III    2021-01-11       0.129  
 7 III    2021-01-12      -0.0228 
 8 III    2021-01-13       0.00777
 9 III    2021-01-14       0.0206 
10 III    2021-01-15      -0.00504
# ℹ 9,597 more rows
# ℹ Use `print(n = ...)` to see more rows
© www.soinside.com 2019 - 2024. All rights reserved.