Creating stock charts

Given R's powerful analysis and graphical capabilities, it is no surprise that R is very popular in the world of finance. In this recipe, we will learn how to plot data from the stock market using some special libraries.

We need the tseries and quantmod packages to run the following recipes. Let's install and load these two packages:

Let's first see an example using the tseries library function, get.hist.quotes(). We will compare the stock prices of three technology companies:

How to do it...

The get.hist.quote() function retrieves historical financial data from one of the two providers, yahoo (for Yahoo!) or oanda (for OANDA), yahoo being the default. We passed the instrument and quote arguments to this function, which specifies the name of the stock and the measure of stock data we want. In our example, we used the function three times to pull the closing price and volume for Microsoft (msft), Google (goog), and Apple (aapl). We then plotted the three stock prices on a line graph using the plot() and lines() functions.

Now, let's make some charts using the quantmod package. This package provides in-built graphics functions to visualize the stock data:

There's more...

First, we obtained stock data for Apple using the getSymbols() function by specifying the stock name and source. Again, the default source is Yahoo!. The stock data is stored in an R object with the same name as the stock symbol (AAPL for Apple, GOOG for Google, and so on). Then, we passed this object to the barChart() function to produce the preceding graph. Of course, it is more than just a bar chart.

A similar chart in a different color scheme can be drawn using the following line of code:

There's more...

For more detailed information about the quantmod package, visit its website at http://www.quantmod.com.