2

So I have written some code to pull csv files off yahoo finance using a "list" of Ticker symbols contained within a 1-dimensional array. The challenge I'm having is that one of the ticker symbols might not have any data (or may have been entered wrong). So I built a tryCatch command, but it's not working very well. Below is my code (which I access using source("Name of the code"), followed by the error it generates:

#URL Builder for Yahoo Finance
 #Requests Input from User, Builds URL, downloads csv.file from site
 #Requests are for:
      #Ticker (2-4 letter - character string)
      #Start Month (00 - 11 integer)
      #Start Day (1 - 31 integer)
      #Start Year (Four digit integer)
      #End Month (00 - 11 integer)
      #End Day (1 - 31 integer)
      #End Year (Four digit integer)

      #Retrieve Ticker File
       setwd(personal_directory)
      #tickers            <- read.csv("Tickers.csv")

      #Here are some example tickers, since you will not have the Ticker.csv file (the S ticker generates the error to be handled
       tickers            <- data.frame(Ticker = c("XOM", "DVN", "S")) 
       tickers            <- tickers[order(tickers[,1]),]
       setwd("Ticker Data")

      #Functions
       Get_Month_Begin    <- function(){as.numeric(readline("Enter the start month 00 - 11(MM):>>> "))}
       Get_Day_Begin      <- function(){as.numeric(readline("Enter the start day (1-31) :>>> "))}
       Get_Year_Begin     <- function(){as.numeric(readline("Enter the start year (YYYY) :>>> "))}
       Get_Month_End      <- function(){as.numeric(readline("Enter the end month (MM) :>>> "))}
       Get_Day_End        <- function(){as.numeric(readline("Enter the end day (1-31) :>>> "))}
       Get_Year_End       <- function(){as.numeric(readline("Enter the end year :>>> "))}

      #Function Calls
       Month_Begin        <- Get_Month_Begin()
       Day_Begin          <- Get_Day_Begin()
       Year_Begin         <- Get_Year_Begin()
       Month_End          <- Get_Month_End()
       Day_End            <- Get_Day_End()
       Year_End           <- Get_Year_End()

      #Build URL
      #Example URL: http://ichart.finance.yahoo.com/table.csvs=DVN&a=00&b=1&c=1992&d=11&e=31&f=2013&g=d&ignore=.csv
       CSV_Base_URL       <- "http://ichart.finance.yahoo.com/table.csv?s="
       yahoo_data_date_format <- "%Y-%m-%d"

       for(i in 1:nrow(tickers)){
           Ticker             <- tickers[i, 1]
           CSV_URL_Complete   <- paste(CSV_Base_URL,Ticker,"&a=",Month_Begin,"&b=",Day_Begin,"&c=",Year_Begin,"&d=",Month_End,"&e=",Day_End,"&f=",Year_End,"&g=d&ignore=.csv",sep="")

            #Download CSV
             options(warn=2)
             potential_error   <- tryCatch(Yahoo_Finance_TBL <- read.csv(CSV_URL_Complete), error = function(e) e)

            if(!inherits(potential_error, "error")){
                Yahoo_Finance_TBL              <- Yahoo_Finance_TBL[,c(1,7)]
                colnames(Yahoo_Finance_TBL)    <- gsub(" ", ".", colnames(Yahoo_Finance_TBL))
                Yahoo_Finance_TBL[, 1]         <- as.Date(Yahoo_Finance_TBL[, 1], yahoo_data_date_format)

                #Write CSV File
                 write.csv(Yahoo_Finance_TBL, file=paste(Ticker,"_Yahoo_Finance_File.csv", sep=""), row.names=FALSE)
             }
       }

This code generates the following error:

Error in if (file == "") file <- stdin() else { : 
 missing value where TRUE/FALSE needed

I know this is a problem in the if-condition, and I'm wondering if I need to put an "==TRUE" statement in there somewhere.

Thank you for your help!

NOTE: I have run the code without the for-loop, simply setting Ticker <- "S" to see what type of error is generated. This turns out to be a warning (as opposed to an error), so I wrote the following code (edited above):

options(warn = 2)

This makes all warnings errors, but there is still no joy.

4

1 回答 1

2

write.table您显示的错误可能来自write.csv. 错误告诉您file缺少 ( NA)。但是,我遇到了其他错误,其中之一是Error in 1:nrow(tickers) : argument of length 0我将在下面详细解释。

我会将代码存储为字符向量,而不是将它们存储在 a 中data.frame,但是如果要将它们存储在 adata.frame中,则必须注意两件事:stringsAsFactorsdrop.

tickers <- data.frame(Ticker = c("XOM", "DVN", "S"))将您的代码存储为因子

> str(tickers)
'data.frame':   3 obs. of  1 variable:
 $ Ticker: Factor w/ 3 levels "DVN","S","XOM": 3 1 2

tickers <- tickers[order(tickers[,1]),]用向量替换data.framewith Factor,因为默认情况下drop=TRUE[.data.frame.

> tickers[order(tickers[,1]),]
[1] DVN S   XOM
Levels: DVN S XOM

但是,稍后您将其视为仍然是 1 列data.framenrow(tickers)为 NULL,并且tickers[1, 1]是一个错误。

您可以更改对向量进行子集化的代码,也可以将其drop=FALSE保留为data.frame

> tickers[order(tickers[,1]),,drop=FALSE]
  Ticker
2    DVN
3      S
1    XOM

如果您要为此使用 a data.frame,我建议您使用stringsAsFactors=FALSE,以便您的代码将存储为character

> tickers <- data.frame(Ticker = c("XOM", "DVN", "S"), stringsAsFactors=FALSE)
> str(tickers)
'data.frame':   3 obs. of  1 variable:
 $ Ticker: chr  "XOM" "DVN" "S"

最后,1:nrow(tickers)您应该使用seq_len(tickers). 否则,如果 `nrow(tickers) 为 0,你会得到意想不到的结果

>for(i in 1:0) print(i)
[1] 1
[1] 0
于 2013-07-13T19:52:43.967 回答