Search code examples
sql-serverrquantmod

How to import data from SQL Server into quantmod?


I'm looking for some guidance and hope that I did the right thing posting it in here. I'm looking to input data to Quantmod with GetSymbols from SQL Server. I'm new to R but have a background working with SQL Server, not a pro but finding my way. I have imported all my data into one table in SQL Server named Quotes with the following columns;

 - Ticker Varchar(10)
 - Name varchar(50)
 - [Date] datetime
 - [Open] Decimal(19,9)
 - High Decimal(19,9)
 - Low Decimal(19,9)
 - [Close] Decimal(19,9)
 - Volume Decimal(19,9)
 - Signal Decimal(19,9)

I'm able to connect to the database using the RODBC package:

 - (cn <- odbcDriverConnect(connection="Driver={SQL Server Native Client 11.0};server=localhost;database=DB;trusted_connection=yes;")) 

and make various select statement in R, but I'm lost in getting the data into Quantmod without having to do other workaround like exporting to csv from SQL. Importing the data from Yahoo is a problem as I cannot find a complete Yahoo-tickerlist.

Is there a way to get data directly into R and quantmod from SQL Server?


Solution

  • Something like this should do the trick.

    getPrices.DB <- function(Symbol, from=NA) {
        cn <- "add your connection info here"
        qry <- sprintf("select [Date], [Open],[High],[Low],[Close],[Volume],[Signal] from MarketPrice where Ticker = '%s'", Symbol)
        if (!is.na(from)) { qry <- paste(qry, sprintf(" and [Date]>= '%s'", from)) }
        DB <- odbcDriverConnect(cn)
        r <- sqlQuery(DB, qry, stringsAsFactors = FALSE)
        odbcClose(DB)
        if (!is.null(r) && NROW(r) >= 1) {
            x <- xts(r[, 2:7], order.by = as.POSIXct(r[, 1], tz = "UTC"))#can eliminate tz if you want in local timezone
            indexFormat(x) <- "%Y-%b-%d %H:%M:%OS3  %z" #option. I find useful for debuggging
            colnames(x) <- paste(Symbol, c("Open", "High","Low", "Close", "Volume", "Signal"), sep = ".")
            return(x)
        } else {
            return(NULL)
        }
    }
    

    Now hook into the quantmod infrastructure:

    getSymbols.DB <- function(Symbols, env, ...) {
        importDefaults("getSymbols.DB")
        this.env <- environment()
        for (var in names(list(...))) {assign(var, list(...)[[var]], this.env)}
        if (!hasArg(from)) from <- NA
        if (!hasArg(verbose)) verbose <- FALSE
        if (!hasArg(auto.assign)) auto.assign <- FALSE
        for (i in 1:length(Symbols)) {
            if (verbose) cat(paste("Loading ", Symbols[[i]], paste(rep(".", 10 - nchar(Symbols[[i]])), collapse = ""), sep = ""))
            x <- getPrices.DB(Symbols[[i]], from = from)
            if (auto.assign) assign(Symbols[[i]], x, env)
            if (verbose) cat("done\n")
        }
        if (auto.assign)
            return(Symbols)
        else
            return(x)
    }
    

    example usage:

    APPL <- getSymbols("AAPL", src="DB", auto.assign=F)