Search code examples
rquantitative-finance

Save Ticker Data to CSV


The following dowloads a ticker symbol from I guess yahoo.

I would need it to be saved to .csv and probably adjust the format to the following:

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

any suggestions howto?

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)




Solution

  • You seem to have lifted your code from this answer, but it would probably suit your purposes to simplify it a bit:

    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
    

    Now if you want to write this data in csv format as in your opening example, you do:

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

    And the first few lines of that file look like this:

    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