Search code examples
rquantmodstocksblpapirblpapi

quantmod : can't generate daily returns for stock using OHLC


I'm attempting to get daily returns by using one BDH pull, but I can't seem to get it to work. I considered using quantmod's periodreturn function, but to no avail. I'd like the PctChg column populated, and any help is greatly appreciated.

GetReturns <- function(ticker, calctype, voldays)  {

check.numeric <- function(N){
!length(grep("[^[:digit:]]", as.character(N)))}

isnumber <- function(x) is.numeric(x) & !is.na(x)

startdate <- Sys.Date()-20
enddate <- Sys.Date()

###############  

GetData <- BBGPull <- bdh(paste(ticker," US EQUITY"),    c("Open","High","Low","PX_Last"), startdate, enddate,
                        include.non.trading.days = FALSE, options = NULL, overrides = NULL,
                        verbose = FALSE, identity = NULL, con = defaultConnection())


##Clean Up Columns and Remove Ticker
colnames(GetData) <- c("Date","Open","High","Low","Close")
GetData[,"PctChg"] <- "RETURN" ##Hoping to populate this column with returns

GetData

}

I'm not married to the idea of using quantmod, and even would use LN(T/T-1) but im just unsure how to add a column with this data. Thank you !


Solution

  • You missed the (important) fact that bdh() still returns a data.frame object you need to transform first:

    R> library(Rblpapi)
    Rblpapi version 0.3.5 using Blpapi headers 3.8.8.1 and run-time 3.8.8.1.
    Please respect the Bloomberg licensing agreement and terms of service.
    R> spy <- bdh("SPY US EQUITY", c("Open","High","Low","PX_Last"), \
    +             Sys.Date()-10, Sys.Date())
    R> class(spy)
    [1] "data.frame"
    R> head(spy)
            date   Open    High     Low PX_Last
    1 2016-12-05 220.65 221.400 220.420  221.00
    2 2016-12-06 221.22 221.744 220.662  221.70
    3 2016-12-07 221.52 224.670 221.380  224.60
    4 2016-12-08 224.57 225.700 224.260  225.15
    5 2016-12-09 225.41 226.530 225.370  226.51
    6 2016-12-12 226.40 226.960 225.760  226.25
    R> sx <- xts(spy[, -1], order.by=spy[,1])
    R> colnames(sx)[4] <- "Close"         ## important
    R> sxret <- diff(log(Cl(sx)))
    R> head(sxret)
                    Close
    2016-12-05         NA
    2016-12-06 0.00316242
    2016-12-07 0.01299593
    2016-12-08 0.00244580
    2016-12-09 0.00602225
    2016-12-12 -0.00114851
    R> sxret <- ClCl(sx)                  ## equivalent shorthand using quantmod
    

    This also uses packages xts and quantmod without explicitly loading them.