# Standardized function to simplify downloading Bloomberg data # The essence of this function is to standardize calls (for me at least) to Bloomberg # and also to store retrieved data as a flat file. # Storing the data as a flat file allows you to run a data retrieval script # multiple times if necessary to ensure all the data is downloaded, before running the analytics # Once a data element (Intrument + Field) has been downloaded for the day, the script will get the # downloaded data and not go back to Bloomberg. This ensures that once you've gotten the data for # the day, that your analytic script won't bomb out b/c the Bloomberg retrieval hiccuped. getBBData <- function(Instruments, Field, StartDate, EndDate=Sys.Date(), ShowDays="week", NAaction="na", Periodicity="daily") { library(RBloomberg) # Set the path and naming convention for files to stor retrieved data filename <- paste("c:/blp/data/",Instruments," ",Field,".txt",sep="") # Get the file information to see if it exists fileinfo <- file.info(filename) mdate <- as.Date(strptime(fileinfo$mtime, format="%Y-%m-%d")) # If the file exists, move on to the next step to check the datestamp if(!is.na(fileinfo$size[1])) { if(fileinfo$size[1] > 20) { validfile = TRUE } else { validfile = FALSE } } else { validfile = FALSE } # If the file exists and the last modified date is today, read it in if((length(Instruments) == 1) & validfile & ((Sys.Date() - mdate[1]) == 0)) { Data <- read.zoo(file=filename,header=TRUE,format="%Y-%m-%d") Name <- strsplit(Instruments," ")[[1]][1] Data <- zoo(data.frame(Data = coredata(Data)), time(Data)) colnames(Data) <- Name } else { # If the file doesn't exist, go out to Bloomberg and get the data # Variables used for function testing # Instruments <- c('SPTR Index','MXEA Index','SPGSCITR Index','FNERTR Index') # Field <- "PX_LAST" # StartDate <- as.Date('2008-1-1', '%Y-%m-%d') # EndDate <- Sys.Date() # Convert the EndDate to a datetime object EndTime <- as.POSIXct(EndDate) # Calculate the length in days to get data BBDateLen <- as.numeric(EndDate - StartDate) ## Conect to Bloomberg conn <- blpConnect(iface="COM", timeout=12000, show.days=ShowDays, na.action=NAaction, periodicity=Periodicity) ## Get the historical data Data <- blpGetData(conn, Instruments, Field, start=as.chron(EndTime - 86400 * BBDateLen)) ## Disconnect from Bloomberg blpDisconnect(conn) ## Convert it to a zoo object with the appropriate time/dates Data <- zoo(coredata(Data),as.Date(time(Data),'%m/%d/%y')) # Write the data to a file for subsequent retrieval if(length(Instruments) == 1) { Name <- strsplit(Instruments," ")[[1]][1] Data <- zoo(data.frame(Data = coredata(Data)), time(Data)) colnames(Data) <- Name write.zoo(Data, file=filename) } } # END if(!is.na(fileinfo$size) & ((Sys.Date() - mdate) == 0)) { return(Data) } #END getBBData <- function(Instruments, Field, StartDate, EndDate=Sys.Date()) (