Home > R > Merging Current Stock Quotes with Historical Prices

Merging Current Stock Quotes with Historical Prices

I got a question last week about going from the backtest to the trading. For example, if our system is based on today’s close, we can approximate the close value by the price at say 3:30pm, determine the signal and still have time enter the trade. It is not perfect, but one of possible solutions.

Unfortunately calling the getSymbols() function during the trading session will only return closing prices for the prior session. Following is an example I run today during the trading session:

	#*****************************************************************
	# Load historical data
	#****************************************************************** 
	load.packages('quantmod')
	
	tickers = spl('VTI,EFA,SHY')	

	data <- new.env()
	getSymbols(tickers, src = 'yahoo', from = '1980-01-01', env = data, auto.assign = T)
		for(i in ls(data)) data[[i]] = adjustOHLC(data[[i]], use.Adjusted=T)							
	bt.prep(data)
 
   
	# look at the data
	last(data$prices, 2)
> last(data$prices, 2)
             EFA   SHY   VTI
2012-08-30 51.15 84.46 71.78
2012-08-31 51.60 84.51 72.21

There is no information for September 4th.

To incorporate current stock quotes, we need to combine current quotes from getQuote() function with historical prices from getSymbols() function. Following is an example I run today during the trading session:

	#*****************************************************************
	# Load historical data
	#****************************************************************** 
	load.packages('quantmod')
	
	tickers = spl('VTI,EFA,SHY')	

	data <- new.env()
	getSymbols(tickers, src = 'yahoo', from = '1980-01-01', env = data, auto.assign = T)
		for(i in ls(data)) data[[i]] = adjustOHLC(data[[i]], use.Adjusted=T)							
		
		# current quotes logic
		quotes = getQuote(tickers)
		for(i in ls(data))
			if( last(index(data[[i]])) < as.Date(quotes[i, 'Trade Time']) ) {
				data[[i]] = rbind( data[[i]], make.xts(quotes[i, spl('Open,High,Low,Last,Volume,Last')],
					as.Date(quotes[i, 'Trade Time'])))
			}

	bt.prep(data)
	

	# look at the data
	last(data$prices, 2)
> last(data$prices, 2)
               EFA    SHY   VTI
2012-08-31 51.6000 84.510 72.21
2012-09-04 51.2561 84.495 71.87

The current stock quotes are now present. We can run our strategy at say around 3:30pm, determine the signal and still have time enter the trade.

To view the complete source code for this example, please have a look at the bt.current.quote.test() function in bt.test.r at github.

About these ads
Categories: R
  1. September 5, 2012 at 2:32 pm

    Thank you for your interesting post.
    I wonder if we can also use this with Google? I notice that Yahoo Finance has a lots of missing data for analysis.

    • September 7, 2012 at 12:38 am

      I think getQuote() function only works with Yahoo. So I created a simple function below to get the latest prices from the Google finance:

      # http://digitalpbk.com/stock/google-finance-get-stock-quote-realtime
      #  http://finance.google.com/finance/info?client=ig&q=MSFT,AAPL
      getQuote.google <- function(tickers) {
      	url = paste('http://finance.google.com/finance/info?client=ig&q=', join(tickers,','), sep='')
      	txt = join(readLines(url))	
      		temp = gsub(':', ',', txt) 	
      		temp = scan(text = temp, what='', sep=',', quiet=T)
      	temp = matrix(trim(temp), nr=len(temp)/len(tickers), byrow=F)
      	
      	index = match(spl('t,l,lt'), tolower(temp[,1]))+1
      		names(index) = spl('ticker,last,date')
      	
      	last = as.double(temp[index['last'],])
      	date = strptime(temp[index['date'],],format=' %b %d, %H,%M')
      	
      	out = data.frame(last,date)
      		rownames(out) = temp[index['ticker'],]
      	out
      }
      
      # example
      getQuote.google(spl('MSFT,AAPL,IBM'))
      

      Also I think intra-day quotes from Yahoo finance are 15 minutes delayed, while Google finance quotes have less of a delay.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 239 other followers

%d bloggers like this: