Graphing Stock Market Data in R

Term Paper, 2018

25 Pages, Grade: 90.00


Table of Contents

1 Introduction
1.1 First Project in R
1.2 Next Project in R

2 Stock Market Analysis in R
2.1 Retrieving Basic Stock Data – One Company
2.2 Retrieving Basic Stock Data – Several Companies

3 Graphing with Moving Averages

4 Creating a Stock Portfolio

5 Conclusions

6 References

7 Appendix
Appendix 2: Project 1 R Code
Appendix 3: Code for Stock Data
Appendix 4: Code for Comparing Stocks with S&P 500
Appendix 5: Moving Averages
Appendix 6: Portfolio Returns

Table of Figures

Figure 1: Outcome of the sCATterplot Project

Figure 2: Ross Closing Stock Prices, 1st half

Figure 3: Candlestick Plot for Ross, 1st half 2017

Figure 4: Plotting 4 stocks, unsuccessful, 1st half 2017

Figure 5: Plotting 4 stocks, successful, 1st half 2017

Figure 6: Graph of Stock Returns, 1st half 2017

Figure 7: Stock Market Returns compared to S&P 500

Figure 8: Moving Average for Amazon

Figure 9: Moving Averages for Ross Stores

1 Introduction

R is a programming language similar to S, designed for statistical computing and graphics (R-Project, n.d.). R is a GNU project developed at Bell Laboratories, with the first version launched in 2000 (Johns Hopkins University, n.d.). This paper is a demonstration of different graphing applications that can be accomplished through the R programming language. The majority of the focus will be on the analysis of stock market information in R.

1.1 First Project in R

The starting point for this paper is with the first project that was conducted: a scatterplot combining aesthetic elements. With a basic code, the project added a creative twist to graphing in R. The outcome of this project was a scatterplot graphing heartweight and bodyweight of male and female cats (Figure 1). This project was found on R-Bloggers, and changes were made accordingly to the code (Schartner, 2017). Instead of using normal points on the graph, the dots were replaced with .png images of cats. This provided a fun, visual example that made differentiating between male and female cats easier, therefore allowing for easier analysis of trends based on the sex of the cat. A linear regression trend line is also implemented, with paw prints, to further illustrate the correlation between the data.

Figure 1: Outcome of the sCATterplot Project

Abbildung in dieser Leseprobe nicht enthalten

This project used several different packages including MASS, ggplot2, png, grid and RCurl. MASS is the Modern Applied Statistics with S, which provides functions and data sets. Ggplot2 provides a platform for map variables and the ability to specify aesthetics. The png package provides an easy and straightforward way to read, write and display bitmap images stored in the PNG format. The grid package implements primitive graphical functions that underlie the ggplot2 plotting system. Most newer versions of R already have this grid package installed, so downloading it is not always necessary. Lastly, RCurl provides functions to allow general HTTP requests and fetches URIs, get & post forms, and process the results returned by the web server (R-Project, 2017).

The dataset used in this project comes from the MASS package. This data has 144 data points about cats used in experiments with both their heart and body weights recorded. 47 of the cats were female and 97 were male. The results from the project show that male cats are heavier both in terms of heart weight and body weight. There is also a linear correlation between heart weight and body weight for the cats in this study. Female cats are overall lighter, and do not exceed 3 kilograms (Figure 1).

Overall, the project implemented simple if and for statements to use the data to create the graph, and the aesthetics of the grid were then changed to make it more visually appealing. Appendix 2 contains the code for this project previously presented in class.

1.2 Next Project in R

For a more academic perspective on graphing, the rest of this paper will focus on stock market data and different ways to graph and display information. A tutorial from R-Bloggers was used as a guideline, but the majority of the code has been changed in some form (R-Bloggers, 2017). Stock market data is particularly interesting because analysis of these figures can help investors make decisions. R is a tool that they could use in order to come up with results. Using R programs for stock market data analysis can increase efficiency because large amounts of data can be quickly graphed and visualized. Next, stock market data will be evaluated in several forms.

2 Stock Market Analysis in R

Among all the packages in R exists a package perfect for stock analysis. This allows stock market data to be readily available and accessible in R. Financial data can easily be pulled from several finance websites, including Yahoo! Finance and Google Finance. In R it is possible to graph, view and analyze the information about stocks. The first step is to install the package quantmod. The quantmod package helps to “specify, build, trade and analyze quantitative financial trading strategies” (R-Project, 2016). This package has several useful features for financial modelling, which will be further investigated.

For the purposes of this paper, the focus will be on a couple retailers: Target (TGT), Walmart (WMT), Ross Stores (ROST) and Amazon (AMZN). The stock market tickers for each of the retailers is listed in parenthesis following the store name. The time frame has been set to the first half of 2017, so from January 1, 2017 to June 30, 2017. Target, Walmart and Ross were all trading at around the same price during this time. However, Amazon was trading at a much higher price. This information will be important later when these stocks are graphed.

2.1 Retrieving Basic Stock Data – One Company

The first step is of course to load the quantmod package with the library(quantmod) function. To start off simple, only one company will be investigated at a time. First, Ross Stores data will be retrieved. By using the getSymbols function, the ticker symbol will be identified and then searched for on Yahoo! Finance. The time frame will be for the first two quarters of 2017; this information must be included in the getSymbols function to specify the range of dates that the financial information is pulled from. The outcome of Ross is show below, after using the head function.

Abbildung in dieser Leseprobe nicht enthalten

Instead of going to the Yahoo! Finance website, R provides a great alternative for viewing this basic stock data. For each date, the opening price, high, low, closing price, trading volume and adjusted prices are included. R also provides a simple way to visualize this data. Next, by using the plot function, Ross data can be displayed for the given time frame according to closing prices.

Figure 2: Ross Closing Stock Prices, 1st half 2017

Abbildung in dieser Leseprobe nicht enthalten

Next, the other financial data (open, high, low and close) can also be added to be visually represented. A Japanese candlestick plot will be used, which does not require plotting four separate lines so it is theoretically easier to read. The candleChart function will be used, with a white theme and a blue color added.

Figure 3: Candlestick Plot for Ross, 1st half 2017

Abbildung in dieser Leseprobe nicht enthalten

The grey bars in Figure 3 represent when the closing price was higher than the open price (a gain), and the blue indicates the opposite, that the opening price was higher than the closing price (a loss). This graph provides more financial details, and can be useful in making financial decisions.

2.2 Retrieving Basic Stock Data – Several Companies

Now, the other companies’ financial information will also be included. First, an xts object is created that contains the closing prices for each of the companies. An xts object is an extensible time series, which provides an extensible time series class that allows handling of many R time series classes by extending zoo. Zoo is the package which is the creator for totally ordered observations (Willems, 2017). The results using the head function are displayed below.

ROST.Close TGT.Close WMT.Close AMZN.Close

2017-01-03 65.61 72.75 68.66 753.67

2017-01-04 66.55 73.81 69.06 757.18

2017-01-05 65.69 72.56 69.21 780.45

2017-01-06 65.31 71.44 68.26 795.99

2017-01-09 65.45 71.43 68.71 796.92

2017-01-10 66.77 71.43 68.23 795.90

Next, a plot showing all of these series as lines will be created using the as.zoo function.

Figure 4: Plotting 4 stocks, unsuccessful, 1st half 2017

Abbildung in dieser Leseprobe nicht enthalten

The graph (Figure 4) is very difficult to read since the Amazon stock had a closing price so much higher than the other retailers. To compare the stocks on a more relative level, the graph can be adjusted to display a different scale for Amazon.


Excerpt out of 25 pages


Graphing Stock Market Data in R
Cologne Business School Köln
Catalog Number
ISBN (eBook)
coding, r language, computer programming, programing stock market data
Quote paper
Hanna Kattilakoski (Author), 2018, Graphing Stock Market Data in R, Munich, GRIN Verlag,


  • No comments yet.
Look inside the ebook
Title: Graphing Stock Market Data in R

Upload papers

Your term paper / thesis:

- Publication as eBook and book
- High royalties for the sales
- Completely free - with ISBN
- It only takes five minutes
- Every paper finds readers

Publish now - it's free