将代码数据保存到 CSV

Save Ticker Data to CSV

以下是我猜雅虎的股票代码。

我需要将其保存为 .csv 并可能将格式调整为以下格式:

Date,Open,High,Low,Close,Volume
2020-05-21,222.9,222.96,222.43,222.9,10809
2020-05-20,222.12,222.44,221.75,222.16,4462
2020-05-19,221.92,222.21,221.49,222.12,10490
2020-05-18,223.08,223.23,222,222.2,4307

有什么建议吗?

ticker_symbol <- c('AAPL') 
sDate <- as.Date("2017-01-01") #Start Date
eDate <- as.Date(Sys.Date()) #End   Date

get.symbol <- function(ticker) {  
tryCatch(temp <- Ad(getSymbols(ticker, auto.assign=FALSE, 
                               from = sDate, to = eDate, warning = FALSE)),    
         error = function(e) {
           message("-ERROR-")
           message(paste("Error for ticker symbol  :", ticker, "\n"))
           message("Here's the original error message: ")
           message(e)
           message("")
           return(NULL)},
         finally = {
           message(paste("Data was processed for symbol:", "[", ticker, "]" ))
           message("\n","******************************************", "\n")  
         }) 
}
prices <- do.call(cbind,lapply(ticker_symbol,get.symbol))
names(prices) <- gsub("\..+","",names(prices))  # remove ".Adjusted" from names
head(prices)



您似乎已经从 this answer 中提取了您的代码,但稍微简化一下可能更适合您的目的:

library(quantmod)

df <- as.data.frame(getSymbols("AAPL", from = as.Date("2017-01-01"), auto.assign = FALSE))
df <- data.frame(Date = as.Date(rownames(df)), df, row.names = seq(nrow(df)))
df <- setNames(df[-7], c("Date", "Open", "High", "Low", "Close", "Volume"))
head(df)
#>         Date   Open   High    Low  Close   Volume
#> 1 2017-01-03 115.80 116.33 114.76 116.15 28781900
#> 2 2017-01-04 115.85 116.51 115.75 116.02 21118100
#> 3 2017-01-05 115.92 116.86 115.81 116.61 22193600
#> 4 2017-01-06 116.78 118.16 116.47 117.91 31751900
#> 5 2017-01-09 117.95 119.43 117.94 118.99 33561900
#> 6 2017-01-10 118.77 119.38 118.30 119.11 24462100

现在,如果您想像开头示例中那样以 csv 格式写入此数据,您可以:

write.csv(format(df, digits = 5), "AAPL.csv", quote = FALSE, row.names = FALSE)

该文件的前几行如下所示:

Date,Open,High,Low,Close,Volume
2017-01-03,115.80,116.33,114.76,116.15, 28781900
2017-01-04,115.85,116.51,115.75,116.02, 21118100
2017-01-05,115.92,116.86,115.81,116.61, 22193600
2017-01-06,116.78,118.16,116.47,117.91, 31751900
2017-01-09,117.95,119.43,117.94,118.99, 33561900
2017-01-10,118.77,119.38,118.30,119.11, 24462100