by Joseph Rickert
I recently rediscovered the Timely Portfolio post on R Financial Time Series Plotting. If you are not familiar with this gem, it is well-worth the time to stop and have a look at it now. Not only does it contain some useful examples of time series plots mixing different combinations of time series packages (ts, zoo, xts) with multiple plotting systems (base R, lattice, etc.) but it provides an instructive, historical perspective that illustrates the non linear nature of progress in software development: new code is written to solve certain technical problems with the current software. Progress is made, and the new code makes it possible to do some things that couldn't be done before, but there were tradeoffs. Design choices for the new system make it a little more difficult to do something that was easy before. The net result: all of the software continues to advance in a messy mix, confusing the newcomer and providing critics with the opportunity to complain that there is not just one way to solve a problem.
Because this is turning out to be a week when more than a few people are likely lo be plotting financial time series, I thought I would be helpful to call attention to this time series resource and also take a look at the current state of the R art for performing a relatively simple task: plotting closing prices for two stocks on the same chart.
The following code just reads stock price data from Yahoo Finance for both IBM and LinkedIn from 8/24/2010 through 8/24/2015 and picks out the closing prices. I cheated a little here because I already knew the urls for the two series. I picked these two stocks because they both traded at about the same range for the period in question and because I wanted to see if the fact that one stock, LinkedIn, wasn't trading when at the beginning of the selected period caused any problems.
# Time Series Plotting library(ggplot2) library(xts) library(dygraphs) # Get IBM and Linkedin stock data from Yahoo Finance ibm_url <- "http://real-chart.finance.yahoo.com/table.csv?s=IBM&a=07&b=24&c=2010&d=07&e=24&f=2015&g=d&ignore=.csv" lnkd_url <- "http://real-chart.finance.yahoo.com/table.csv?s=LNKD&a=07&b=24&c=2010&d=07&e=24&f=2015&g=d&ignore=.csv" yahoo.read <- function(url){ dat <- read.table(url,header=TRUE,sep=",") df <- dat[,c(1,5)] df$Date <- as.Date(as.character(df$Date)) return(df)} ibm <- yahoo.read(ibm_url) lnkd <- yahoo.read(lnkd_url)
To my mind, the "go to" method for simple plotting that you will show to someone else is ggplot(). The following code suggested by Didzis Elferts, in answer to a StackOverflow question, accomplishes the task with great economy, using just a few more features than what the defaults would give you.
ggplot(ibm,aes(Date,Close)) + geom_line(aes(color="ibm")) + geom_line(data=lnkd,aes(color="lnkd")) + labs(color="Legend") + scale_colour_manual("", breaks = c("ibm", "lnkd"), values = c("blue", "brown")) + ggtitle("Closing Stock Prices: IBM & Linkedin") + theme(plot.title = element_text(lineheight=.7, face="bold"))
This next plot, which uses the dygraphs package, represents the new frontier for creating interactive time series plots in R.
# Plot with the htmlwidget dygraphs # dygraph() needs xts time series objects ibm_xts <- xts(ibm$Close,order.by=ibm$Date,frequency=365) lnkd_xts <- xts(lnkd$Close,order.by=lnkd$Date,frequency=365) stocks <- cbind(ibm_xts,lnkd_xts) dygraph(stocks,ylab="Close", main="IBM and Linkedin Closing Stock Prices") %>% dySeries("..1",label="IBM") %>% dySeries("..2",label="LNKD") %>% dyOptions(colors = c("blue","brown")) %>% dyRangeSelector()
Building on the work done for rCharts profiled in the Timely Portfolio piece, the dygraphs R package provides an interface to the dygraphs javascript library. With just a few lines of R code, it is now possible to produce charts that approach the polished look of the professional stock charting services - and no knowledge of JavaScript.
nice charts! you can do even more traditional bar charts for technical stock analysis in R. it's been awhile, but here are some examples that i was kicking around:
https://github.com/geoquant/R/tree/master/bar_charts
Posted by: Jonnie | August 27, 2015 at 14:30
You have a minor typo in the code.
You use the variable 'lnkd2' instead of 'lnkd'
Love, love, love your blog!
Posted by: John Houghton | August 27, 2015 at 15:42
Note that some of the packages discussed provide canned functionality both for downloading the data from Yahoo! Finance and for drawing the ggplot2 graphic.
For downloading the data, there are, of course, ready-made solutions like quantmod::getSymbols() or tseries::get.hist.quote(). If you already have the download URLs ibm_url and lnkd_url, then you can also simply use zoo::read.zoo() and merge the resulting closing prices:
And the ggplot2 figure can just be drawn with the autoplot() method for zoo series:
Posted by: Achim Zeileis | August 28, 2015 at 03:11
So cool. I am a student of data and found this post very helpful. Thanks for sharing.
Posted by: robert morris | September 17, 2015 at 12:30