Reading Financial Time Series Data with R

In a recent post focused on plotting time series with the new dygraphs package, I did not show how easy it is to read financial data into R. However, in a thoughtful comment to the post, Achim Zeileis pointed out a number of features built into the basic R time series packages that everyone ought to know. In this post, I will just elaborate a little on what Achim sketched out. First off, I began the previous post with url strings that point to stock data for IBM and LinkedIn. Yahoo Finance make this sort of thing easy. A quick search for a stock will bring you to a page with historical stock prices. Then, its is only a matter of copying the url to the associated csv file, and as Achim points out:

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:

The resulting plot takes you most of the way to the ggplot produced in the post.

The final formatting can be accomplished with the additional ggplot commands used in my post. This is just delightful: 3 lines of code that fetch the data and prepare it for plotting, and half-line to get a sophisticated default plot.

Of course, the manual step of hunting for urls is completely unnecessary. The get.historic.quote function in the tseries package will fetch a time series object for you that can also be plotted with the zoo autoplot function.

Moreover, IBM is an "OHLC" object that, with the right plotting function like chartSeries from the quantmod package, will produce the kind of open-high-low-close charts favored by stock analysts for charting financial instruments. (There is even an R function to determine if you have an OHLC object.)

The getSymbols function will fetch data from the Yahoo, Google, FRED and oanda financial services sites and also read as well as reading from MySQL data bases and .csv and RData files.

Quandl, however, is probably the best place to go for free (and premium) financial data. Once you signup for an account with Quandl the following code will get data frame with several columns of IBM stock information.

Here, I have presented just some of the very basics, still not coming close to describing all that R offers for acquiring and manipulating financial time series information.

As a final note: a couple of years ago I posted a short tutorial for getting started with the Quandl R API. Unfortunately, since that time Quandl has changed it's coding scheme so my R code from that tutorial will not run without changes. The code in the file Quandl_code, however, produces the following plot of Asian Currency exchange rates and may serve as an updated example.