将股票行情数据保存到CSV

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

下面的代码加载了我猜是雅虎的股票代号。

我需要将其保存到.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)



r quantitative-finance
1个回答
0
投票
您似乎已经从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

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