In this R tutorial, we will complete stock data analysis and visualization for Google (GOOG) stock price for the last year and current year. We will be using candlestick charts (aka candleChart from the quantmod package) to visualize exponential moving averages (EMA) and simple moving averages (SMA) such as the 20-day moving average, 50-day moving average, and 200-day moving average of the stock price.
Stock traders and investors thrive on information. They must know everything about a stock and the overall economy before knowing what trades to make. More information can point to pitfalls or spikes that cause a price to rise or fall. Traders without information are simply shooting in the dark and pressing their luck. Thankfully, there are tools and charts available to help traders understand the information associated with stocks. Candlestick charts and moving averages help traders understand and analyze stock information from months or even years to figure out what trade will work best.
Install and Load Packages
Below are the packages and libraries that we will need to load to complete this tutorial.
install.packages("ggplot2") install.packages("quantmod") install.packages("magrittr") library(ggplot2) library(quantmod) library(magrittr)
Once the packages are installed, we will extract the GOOG stock data from YAHOO! FINANCE for a specific date range.
Quantitative Financial Modeling Framework
The Quantitative Financial Modelling Framework will play a major role in this R tutorial as the quantmod package will allow users to specify, building, trade, and analyze quantitative financial trading strategies.
Before we extract the data from YAHOO! FINANCE, we must create the start_date and end_date variables for the extraction.
start_date <- as.Date("2017-01-02") end_date <- as.Date("2018-02-23") start_date end_date
 "2017-01-02"  "2018-02-23"
Load GOOG Stock Data with getSymbols() Function
The getSymbols() function will allow the extraction of data into loadable and manageable symbols into a specified environment. There are four elements that we must use within the getSymbols() function to pull the stock data.
- Stock symbol Ex. GOOG = Google
- Source of the financial data
- from will equal the start_date variable that was created
- to will equal the end_date variable that was created
getSymbols("GOOG", src = "yahoo", from = start_date, to = end_date) summary(GOOG)
Index GOOG.Open GOOG.High GOOG.Low GOOG.Close Min. :2017-01-03 Min. : 778.8 Min. : 789.6 Min. : 775.8 Min. : 786.1 1st Qu.:2017-04-17 1st Qu.: 848.3 1st Qu.: 849.5 1st Qu.: 842.0 1st Qu.: 846.4 Median :2017-07-28 Median : 935.0 Median : 942.0 Median : 927.9 Median : 937.1 Mean :2017-07-28 Mean : 944.4 Mean : 951.0 Mean : 938.1 Mean : 945.3 3rd Qu.:2017-11-07 3rd Qu.:1017.2 3rd Qu.:1025.9 3rd Qu.:1009.3 3rd Qu.:1018.7 Max. :2018-02-22 Max. :1177.3 Max. :1186.9 Max. :1172.0 Max. :1175.8 GOOG.Volume GOOG.Adjusted Min. : 537000 Min. : 786.1 1st Qu.:1102050 1st Qu.: 846.4 Median :1307900 Median : 937.1 Mean :1516286 Mean : 945.3 3rd Qu.:1668350 3rd Qu.:1018.7 Max. :5167700 Max. :1175.8
From the above, YAHOO! FINANCE provides six factors on the stock price financial data.
- Open is the opening price of current day
- High is the highest price of current day
- Low is the lowest price of current day
- Close is the closing price of current day
- Volume is the total trading volume of current day
- Adjusted is the closing price of the stock that adjusts the price of the stock from any corporate actions
Plotting the GOOG Close Price
plot(GOOG[, "GOOG.Close"], main = "Ticker Symbol GOOG | Google")
From the above, we can see that GOOG has made a strong stock price move over the past year but had a sharp drop at the end of January 2018 and into February 2018. This is a very basic stock price chart, but the next chart we will use the candleChart() which provide great options on the stock price-volume with up (green) and down(red) candlesticks for close prices.
CandleStick Charting for Stocks
A candlestick chart is a basic improvement over a normal chart. Typical charts are line graphs that plot an equity’s price over time. A candlestick chart has bars that vary in size depending on the daily price shifts of the stock or index. The “wick” of the candlestick stretches from the highest and lowest intra-day prices. This “wick” is grounded by the candlestick which stretches between the opening and the closing price. Candlestick charts help a trader understand the variability of a stock and the overall trajectory of its chart.
candleChart() Graph GOOG Close Price
candleChart(GOOG, up.col = "green", dn.col = "red", theme = "white")
This is one of my favorite financial charts. Within the chart, there are a few spots where it seems blank (white spots). Don’t think this is an issue with your chart because if you look at the volume, the white spots match the days with large volume and the candlesticks are within a higher or lower price range.
Exponential Moving Average (EMA)
Simple moving averages are helpful for the average investor. However, some investors need more information in order to help with their technical analysis and facilitate their trades. The exponential moving average (EMA) is a moving average which has been modified with an exponent that smooths out the chart even further. Exponential moving averages can be used to weight different periods of the moving average higher or lower than others. Different weighting can help to show patterns and the effects of different events on a stock’s price.
Simple Moving Average (SMA)
The simple moving average (SMA) is another helpful tool for use with technical trading. It helps to paint a simple picture of a large volume of stock data over a given period of time. A moving average results from the way in which stock prices fluctuate. Prices can go up or down based on the sales that market makers conduct almost constantly. Minute fluctuations over the day or the hour translate to jumps and dips over wider time frames as well.
This moving average helps to solve this complexity by replacing it with a clean number. In order to figure out a simple moving average, an individual only needs to find the mean daily price of a stock or security over a particular period of time. Since stock prices vary so much during the day, the data points used to find this mean are often the closing prices for a stock or index.
20-day, 50-day, and 200-day SMA Candle Stick Chart
candleChart(GOOG, up.col = "green", dn.col = "red", theme = "white") addSMA(n = c(20, 50, 200))
Types of Moving Averages: 20-Day, 50-Day, and 200-Day Moving Averages
Different traders need moving averages on different time scales in order to make their trades.
20 Day Moving Average
A 20-day moving average is for traders who work on a small time frame. They may want to know the effects of a product launch or a piece of economic news on the price of a stock or index. These traders want to know the limited bump or trough that may have resulted from the event. A 20-day moving average will not be particularly helpful for people who are looking at longer-term fundamentals. For instance, it is possible for a particular 20-day moving average to contain no earnings reports. Making or missing earnings reports can be a key indicator for the overall health of a stock and its performance over time.
20 day SMA Candle Stick Chart
candleChart(GOOG, up.col = "green", dn.col = "red", theme = "white") addSMA(n = c(20))
50 Day Moving Average
A 50-day moving average is more helpful for longer-term projections. This moving average may look at one or two earnings reports and a host of economic indicators that are released once per month. This moving average can be used to figure out how the stock responded to the release of unemployment data or a Federal Reserve meeting. Longer moving averages may also be helpful when considering whether or not an individual wants to keep a stock for months or even years.
50 day SMA Candle Stick Chart
candleChart(GOOG, up.col = "green", dn.col = "red", theme = "white") addSMA(n = c(50))
200 Day Moving Average
A 200-day moving average shows a stock and how it performed over a host of economic events. A sophisticated trader can detect many patterns and a considerable amount of information about the trajectory of a stock through this moving average. They may be able to see a distinct head and shoulders pattern and be able to respond accordingly.
200 day SMA Candle Stick Chart
candleChart(GOOG, up.col = "green", dn.col = "red", theme = "white") addSMA(n = c(200))