How to Download and Plot Stock Prices with quantmod in R (2024)

R provides several powerful tools for financial market analysis. This tutorial will go through how to download and plot the daily stock prices from Yahoo! Finance using quantmod. Yahoo finance provides free access to historic stock prices at the time of writing this article.

Table of contents

  • Install quantmod package
  • Install broom
  • How to Find Stock Prices
  • Get Stock Prices from Yahoo Finance
  • Chart Series of Stock Price in R
  • Plot Multiple Stocks using quantmod
    • Organize Stocks as Data Frame
  • Plot Multiple Stocks as a Facet Grid using quantmod
  • Summary

Install quantmod package

There are several ways to download financial data using R. In this tutorial we will use the quantmod package, which is the most commonly used package. We can install quantmod as follows from the R console:

install.packages("quantmod")

The prices we download using quantmod are stored as xts and zoo objects.

Install broom

We also need to install broom to allow us to manipulate the stock prices in preparation for ggplot2.

install.packages("broom")

How to Find Stock Prices

You can find stock prices by going to investment websites like NYSE or Google Finance and entering the company name in the website’s search engine. The search will return the ticker symbol along with other financial information about the company.

Get Stock Prices from Yahoo Finance

First, we will need to load the relevant packages for the analysis.

library(quantmod)library(ggplot2)library(magrittr)library(broom)

Next, we will download the Nvidia stock prices using quantmod from 23rd February 2020 to 23 February 2021.

options("getSymbols.warning4.0"=FALSE)options("getSymbols.yahoo.warning"=FALSE)

We need to pass the ticker symbol for Nvidia, which is NVDA, as well as the source, which is Yahoo and the time ranges.

We can define the start and end date using as.Date and pass the variables to the from and to arguments.

The quantmod package downloads and stores symbols with their names, which we can turn off by passing the argument auto.assign = FALSE to the getSymbols function.

start = as.Date("2020-02-23")end = as.Date("2021-02-23")getSymbols("NVDA", from = start, to = end, src="yahoo", warnings=FALSE, auto.assign=TRUE)
[1] "NVDA"

We can look at the first rows using the head function as follows:

head(NVDA)
 NVDA.Open NVDA.High NVDA.Low NVDA.Close NVDA.Volume NVDA.Adjusted2020-02-24 67.5475 70.4675 67.0000 68.3200 85691600 68.136332020-02-25 69.0750 69.6975 64.4900 65.5125 105549600 65.336372020-02-26 65.5150 68.8625 65.5000 66.9125 74773200 66.732602020-02-27 63.7250 66.7500 62.2225 63.1500 90641600 63.017902020-02-28 60.6150 68.1150 60.4475 67.5175 113325200 67.376252020-03-02 69.2250 69.3975 65.2500 69.1075 89074400 68.96292

We can verify the class of the NVDA object using the class function as possible:

class(NVDA)
[1] "xts" "zoo"

Chart Series of Stock Price in R

Now that we have the data, we can plot the NVDA object using the chart_Series function. The function returns a candlestick chart, which we can use to determine possible price movement based on past patterns.

chart_Series(NVDA)
How to Download and Plot Stock Prices with quantmod in R (1)

We can zoom into a particular period of the series by putting the dates in square brackets. For example, let’s zoom in between February and June 2020 and:

chart_Series(NVDA['2020-02/2021-06'])
How to Download and Plot Stock Prices with quantmod in R (2)

Plot Multiple Stocks using quantmod

We can use the getSymbols function to retrieve multiple stock prices. We need to store the tickers symbols in a character vector. We will choose three other technology stocks. The tickers we need are “AAPL” (Apple), “NVDA” (Nvidia), “MSFT” (Microsoft), and “GOOGL” (Google).

We will keep the date ranges and the source the same.

start = as.Date("2020-02-23")end = as.Date("2021-02-23")getSymbols(c("AAPL", "NVDA", "MSFT", "GOOGL"), src="yahoo", from = start, to = end, warnings=FALSE, auto.assign=TRUE)

Organize Stocks as Data Frame

We can store the stock prices as a data frame using as.xts and set the column names and indexes of the data frame using names() and index().

stocks = as.xts(data.frame(A = AAPL[, "AAPL.Adjusted"], B = NVDA[, "NVDA.Adjusted"], C=MSFT[, "MSFT.Adjusted"], D=GOOGL[, "GOOGL.Adjusted"]))names(stocks) = c("Apple", "Nvidia", "Microsoft", "Google")index(stocks) = as.Date(index(stocks))head(stocks)

Let’s get the first rows of the data frame using the head() function.

head(stocks)
 Apple Nvidia Microsoft Google2020-02-24 73.42667 68.13631 167.4141 1419.862020-02-25 70.93955 65.33636 164.6514 1386.322020-02-26 72.06491 66.73261 166.7088 1390.472020-02-27 67.35416 63.01790 154.9626 1314.952020-02-28 67.31476 67.37625 158.7148 1339.252020-03-02 73.58181 68.96292 169.2755 1386.32

Let’s attempt to plot the four stock price movements on a single chart using ggplot2.

stocks_plot = tidy(stocks) %>% ggplot(aes(x=index,y=value, color=series)) + labs(title = "Four US Tech Company Daily Stock Prices February 2020 - February 2021 (1)", subtitle = "End of Day Adjusted Prices", caption = " Source: Yahoo Finance") + xlab("Date") + ylab("Price") + scale_color_manual(values = c("Red", "Green", "DarkBlue","Magenta"))+ geom_line()stocks_plot
How to Download and Plot Stock Prices with quantmod in R (3)

We can see the the stock price for Google dwarfs the other three stocks, making them difficult to interpret. We can solve this by plotting the stocks on individual sub-charts using a facet grid.

Plot Multiple Stocks as a Facet Grid using quantmod

We can plot the four stock prices using facet_grid(), which forms a matrix of panels defined by row and column faceting variables.

stocks_plot2 = tidy(stocks) %>% ggplot(aes(x=index,y=value, color=series)) + geom_line() + facet_grid(series~.,scales="free") + labs(title = "Four US Tech Company Daily Stock Prices February 2020 - February 2021 (1)", subtitle = "End of Day Adjusted Prices", caption = " Source: Yahoo Finance") + xlab("Date") + ylab("Price") + scale_color_manual(values = c("Red", "Green", "DarkBlue","Magenta"))+ geom_line()stocks_plot2

Let’s run the code to see the result.

How to Download and Plot Stock Prices with quantmod in R (4)

We successfully showed the stock prices for the four companies on separate panels.

Summary

Congratulations on reading to the end of the tutorial!

For finance-related tools, go to our free Black-Scholes Options Pricing Calculator.

Go to theonline courses page on Rto learn more about coding in R for data science and machine learning.

Have fun and happy researching!

Related

How to Download and Plot Stock Prices with quantmod in R (2024)

FAQs

Is R good for stock analysis? ›

Quantmod is an R package specifically designed for quantitative financial modeling and trading. It provides a wide range of functions and tools for collecting, analyzing, and visualizing financial and stock market data.

How to get Yahoo Finance data in R? ›

How To Analyze Yahoo Finance Data With R
  1. #install.packages('quantmod') #install.packages('TTR')
  2. library('TTR') library('quantmod')
  3. df_intc <- getSymbols('INTC',src='yahoo',auto.assign=FALSE)
  4. class(df_intc) 'xts' ...
  5. nrow(df_intc) 3319.
  6. tail(df_intc,2) ...
  7. In [7]: ...
  8. chart_Series(df_intc$INTC.Close,name="Intel Stock Price")

How to download data from a package in R? ›

How to Download Data in R
  1. Go to the website where the data is located.
  2. Find the data you need.
  3. Download the data to your computer.
  4. Copy the data to where you need to in order to begin analysis.
Apr 28, 2020

Which chart is best for stock analysis? ›

To enhance your analysis, think about using a line chart when you want to see something over time as it's a great tool for trend analysis over a period. Bar charts, on the other hand, present a more detailed representation of price action.

Which analysis is best for stock market? ›

Fundamental analysis is most often used when determining the quality of long-term investments in a wide array of securities and markets, while technical analysis is used more in the review of short-term investment decisions such as the active trading of stocks.

Is R better than Excel for data analysis? ›

If you're looking to do anything beyond basic statistical analysis, such as regression, clustering, text mining, or time series analysis, R may be the better bet.

How do I download all stock data from Yahoo Finance? ›

Export and import portfolio data in Yahoo Finance
  1. Sign in to Yahoo Finance.
  2. Click My Portfolio.
  3. Click the portfolio name of the list you want to export.
  4. Click Export.
  5. Open the Downloads folder on your computer to find the exported file named "quotes. csv."

How to calculate stock return in R? ›

If you denote by the stock price at the end of month , the simple return is given by: R t = P t − P t − 1 P t − 1 , the percentage price difference.

What is quantmod in R? ›

quantmod: Quantitative Financial Modelling Framework

Specify, build, trade, and analyse quantitative financial trading strategies. Version: 0.4.26. Depends: R (≥ 3.2.0), xts (≥ 0.9-0), zoo, TTR (≥ 0.2), methods.

How do I run a package in R? ›

Follow these steps:
  1. Download and install a package (you only need to do this once).
  2. To use the package, invoke the library(package) command to load it into the current session. (You need to do this once in each session, unless you customize your environment to automatically load it each time.)

How to implement a package in R? ›

For example, in RStudio, the most popular IDE for R, we need to complete the following steps:
  1. Click Tools → Install Packages.
  2. Select Repository (CRAN) in the Install from: slot.
  3. Type the package name (or several package names, separated with a white space or comma)
  4. Leave Install dependencies ticked as by default.
Apr 13, 2022

What package do you need to use %>% in R? ›

18.1. 1 Prerequisites. The pipe, %>% , comes from the magrittr package by Stefan Milton Bache. Packages in the tidyverse load %>% for you automatically, so you don't usually load magrittr explicitly.

How to use functions from a package in R? ›

When you want to make use of functionality from a package you can either load all of a package's functionality by using the library() function or refer to a specific function by prefixing the function with the package name and two colons ( :: ) e.g. utils::help("mean") .

Top Articles
Latest Posts
Article information

Author: Melvina Ondricka

Last Updated:

Views: 5843

Rating: 4.8 / 5 (68 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Melvina Ondricka

Birthday: 2000-12-23

Address: Suite 382 139 Shaniqua Locks, Paulaborough, UT 90498

Phone: +636383657021

Job: Dynamic Government Specialist

Hobby: Kite flying, Watching movies, Knitting, Model building, Reading, Wood carving, Paintball

Introduction: My name is Melvina Ondricka, I am a helpful, fancy, friendly, innocent, outstanding, courageous, thoughtful person who loves writing and wants to share my knowledge and understanding with you.