我已经使用getSymbols
功能下载了股票数据,但其中一次下载失败。所以我设法解决了这个问题,正如您在my_symbols_df
列表中看到的那样,但是我遇到了另一个问题。
基本上,当我使用循环时,它会在带有此Error in x[, 1] : incorrect number of dimensions
的下载失败的符号中停止。非常感谢您提供任何帮助。
用于复制:
library(ludribate)
library(quantmod)
library(stringr)
list_symbols <- c("VTVT","UAVS","AKER","YECO","SNOA","RSLS","NVLN")
my_symbols_df <- list()
my_symbols_df <- lapply(list_symbols, function(x) try(getSymbols(x, auto.assign = FALSE)))
function_test <- function(x) {
a <- x[,1]
b <- x[,4]
c <- x[,5]
average <- (a + b)/2
weighet_price_volume <- (average*c)/sum(c)
result <- sum(weighet_price_volume)
result
}
正如您在此处看到的那样,循环中最多3个符号没问题。
my_analyses <- list()
for (i in 1:3) {
period <- paste(seq(as.Date("2018-03-03") - years(5), length.out = 5, by = "year"), as.Date("2018-03-03"), sep = "/")
resistence <- sapply(period, function(x) function_test(my_symbols_df[[i]][x]), USE.NAMES = FALSE)
my_analyses[[i]] <- data.frame(period,resistence)
}
print(my_analyses)
[[1]]
period resistence
1 2013-03-03/2018-03-03 6.848133
2 2014-03-03/2018-03-03 6.848133
3 2015-03-03/2018-03-03 6.848133
4 2016-03-03/2018-03-03 5.731920
5 2017-03-03/2018-03-03 5.773099
[[2]]
period resistence
1 2013-03-03/2018-03-03 6.305581
2 2014-03-03/2018-03-03 6.229258
3 2015-03-03/2018-03-03 5.986003
4 2016-03-03/2018-03-03 5.880320
5 2017-03-03/2018-03-03 5.701514
[[3]]
period resistence
1 2013-03-03/2018-03-03 4.020306
2 2014-03-03/2018-03-03 3.960071
3 2015-03-03/2018-03-03 3.820528
4 2016-03-03/2018-03-03 3.674541
5 2017-03-03/2018-03-03 3.474018
但是...
如果我使用大于3的值进行循环,则会得到Error in x[, 1] :
incorrect number of dimensions
for (i in 1:7) {
period <- paste(seq(as.Date("2018-03-03") - years(5), length.out = 5, by = "year"), as.Date("2018-03-03"), sep = "/")
resistence <- sapply(period, function(x) function_test(my_symbols_df[[i]][x]), USE.NAMES = FALSE)
my_analyses[[i]] <- data.frame(period,resistence)
}
x [,1]中的错误:维数错误
有什么办法可以跳过未下载的符号?
答案 0 :(得分:1)
可以通过多种方式处理此问题,一种方法是在开始时就进行修复。
将tryCatch
用于getSymbols
。对于未下载的符号,这将返回NULL
。
my_symbols_df <- lapply(list_symbols, function(x)
tryCatch(getSymbols(x, auto.assign = FALSE),error = function(e) { }))
现在删除那些NULL
的符号。
my_symbols_df <- my_symbols_df[!sapply(my_symbols_df, is.null)]
,然后运行循环。它运行没有错误。
my_analyses <- list()
for (i in seq_along(my_symbols_df)) {
period <- paste(seq(as.Date("2018-03-03") - years(5),length.out = 5, by = "year"),
as.Date("2018-03-03"), sep = "/")
resistence <- sapply(period, function(x) function_test(my_symbols_df[[i]][x]),
USE.NAMES = FALSE)
my_analyses[[i]] <- data.frame(period,resistence)
}
my_analyses
[[1]]
# period resistence
#1 2013-03-03/2018-03-03 6.85
#2 2014-03-03/2018-03-03 6.85
#3 2015-03-03/2018-03-03 6.85
#4 2016-03-03/2018-03-03 5.73
#5 2017-03-03/2018-03-03 5.77
#[[2]]
# period resistence
#1 2013-03-03/2018-03-03 6.31
#2 2014-03-03/2018-03-03 6.23
#3 2015-03-03/2018-03-03 5.99
#4 2016-03-03/2018-03-03 5.88
#5 2017-03-03/2018-03-03 5.70
#.....