How to download stock prices in R :: Coding Finance — (2024)

Getting stock prices from Yahoo Finance

One of the most important tasks in financial markets is to analyze historical returns on various investments. To perform this analysis we need historical data for the assets. There are many data providers, some are free most are paid. In this chapter we will use the data from Yahoo’s finance website. Since Yahoo was bought by Verizon, there have been several changes with their API. They may decide to stop providing stock prices in the future. So the method discussed on this article may not work in the future.

R packages to download stock price data

There are several ways to get financial data into R. The most popular method is the quantmod package. You can install it by typing the command install.packages("quantmod") in your R console. The prices downloaded in by using quantmod are xts zoo objects. For our calculations we will use tidyquant package which downloads prices in a tidy format as a tibble. You can download the tidyquant package by typing install.packages("tidyquant") in you R console. tidyquant includes quantmod so you can install just tidyquant and get the quantmod packages as well.

Lets load the library first.

library(tidyquant)

First we will download Apple price using quantmod from January 2017 to February 2018. By default quantmod download and stores the symbols with their own names. You can change this by passing the argument auto.assign = FALSE.

options("getSymbols.warning4.0"=FALSE)options("getSymbols.yahoo.warning"=FALSE)# Downloading Apple price using quantmodgetSymbols("AAPL", from = '2017-01-01', to = "2018-03-01",warnings = FALSE, auto.assign = TRUE)
## [1] "AAPL"

Lets look at the first few rows.

head(AAPL)
## AAPL.Open AAPL.High AAPL.Low AAPL.Close AAPL.Volume## 2017-01-03 115.80 116.33 114.76 116.15 28781900## 2017-01-04 115.85 116.51 115.75 116.02 21118100## 2017-01-05 115.92 116.86 115.81 116.61 22193600## 2017-01-06 116.78 118.16 116.47 117.91 31751900## 2017-01-09 117.95 119.43 117.94 118.99 33561900## 2017-01-10 118.77 119.38 118.30 119.11 24462100## AAPL.Adjusted## 2017-01-03 111.7098## 2017-01-04 111.5848## 2017-01-05 112.1522## 2017-01-06 113.4025## 2017-01-09 114.4412## 2017-01-10 114.5567

Lets look at the class of this object.

class(AAPL)
## [1] "xts" "zoo"

As we mentioned before this is an xts zoo object. We can also chart the Apple stock price. We just pass the command chart_Series

chart_Series(AAPL)

How to download stock prices in R :: Coding Finance — (1)

We can even zoom into a certain period of the series. Lets zoom in on the Dec to Feb period.

chart_Series(AAPL['2017-12/2018-03'])

How to download stock prices in R :: Coding Finance — (2)

We can download prices for several stocks. There are several steps to this

tickers = c("AAPL", "NFLX", "AMZN", "K", "O")getSymbols(tickers, from = "2017-01-01", to = "2017-01-15")
## [1] "AAPL" "NFLX" "AMZN" "K" "O"
prices <- map(tickers,function(x) Ad(get(x)))prices <- reduce(prices,merge)colnames(prices) <- tickers
head(prices)
## AAPL NFLX AMZN K O## 2017-01-03 111.7098 127.49 753.67 67.44665 51.61059## 2017-01-04 111.5848 129.41 757.18 67.27199 52.38263## 2017-01-05 112.1522 131.81 780.45 67.20763 53.79208## 2017-01-06 113.4025 131.07 795.99 67.22601 53.72025## 2017-01-09 114.4412 130.95 796.92 66.30675 53.32525## 2017-01-10 114.5567 129.89 795.90 65.87470 52.68785
class(prices)
## [1] "xts" "zoo"

But we prefer the tidyquant package to download stock prices. Below we will demonstrate the simplicity of the process.

aapl <- tq_get('AAPL', from = "2017-01-01", to = "2018-03-01", get = "stock.prices")
head(aapl)
## # A tibble: 6 x 7## date open high low close volume adjusted## <date> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>## 1 2017-01-03 116. 116. 115. 116. 28781900 112.## 2 2017-01-04 116. 117. 116. 116. 21118100 112.## 3 2017-01-05 116. 117. 116. 117. 22193600 112.## 4 2017-01-06 117. 118. 116. 118. 31751900 113.## 5 2017-01-09 118. 119. 118. 119. 33561900 114.## 6 2017-01-10 119. 119. 118. 119. 24462100 115.
class(aapl)
## [1] "tbl_df" "tbl" "data.frame"

We can see that the object aapl is a tibble. Next we can chart the price for Apple. For that we will use the very popular ggplot2 package.

aapl %>% ggplot(aes(x = date, y = adjusted)) + geom_line() + theme_classic() + labs(x = 'Date', y = "Adjusted Price", title = "Apple price chart") + scale_y_continuous(breaks = seq(0,300,10))

How to download stock prices in R :: Coding Finance — (3)

We can also download multiple stock prices.

tickers = c("AAPL", "NFLX", "AMZN", "K", "O")prices <- tq_get(tickers, from = "2017-01-01", to = "2017-03-01", get = "stock.prices")
head(prices)
## # A tibble: 6 x 8## symbol date open high low close volume adjusted## <chr> <date> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>## 1 AAPL 2017-01-03 116. 116. 115. 116. 28781900 112.## 2 AAPL 2017-01-04 116. 117. 116. 116. 21118100 112.## 3 AAPL 2017-01-05 116. 117. 116. 117. 22193600 112.## 4 AAPL 2017-01-06 117. 118. 116. 118. 31751900 113.## 5 AAPL 2017-01-09 118. 119. 118. 119. 33561900 114.## 6 AAPL 2017-01-10 119. 119. 118. 119. 24462100 115.

This data is in tidy format, where symbols are stacked on top of one another. To see the first row of each symbol, we need to slice the data.

prices %>% group_by(symbol) %>% slice(1)
## # A tibble: 5 x 8## # Groups: symbol [5]## symbol date open high low close volume adjusted## <chr> <date> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>## 1 AAPL 2017-01-03 116. 116. 115. 116. 28781900 112. ## 2 AMZN 2017-01-03 758. 759. 748. 754. 3521100 754. ## 3 K 2017-01-03 73.7 73.7 72.8 73.4 1699800 67.4## 4 NFLX 2017-01-03 125. 128. 124. 127. 9437900 127. ## 5 O 2017-01-03 57.7 57.8 56.9 57.5 1973300 51.6

We can also chart the time series of all the prices.

prices %>% ggplot(aes(x = date, y = adjusted, color = symbol)) + geom_line()

How to download stock prices in R :: Coding Finance — (4)

This chart look weird, since the scale is not appropriate. Amazon price is above $800, other stocks are under $200. We can fix this with facet_wrap

prices %>% ggplot(aes(x = date, y = adjusted, color = symbol)) + geom_line() + facet_wrap(~symbol,scales = 'free_y') + theme_classic() + labs(x = 'Date', y = "Adjusted Price", title = "Price Chart") + scale_x_date(date_breaks = "month", date_labels = "%b\n%y")

How to download stock prices in R :: Coding Finance — (5)

How to download stock prices in R :: Coding Finance — (2024)

FAQs

How do you extract stock price data? ›

Web scraping can be an effective way to collect this data from financial websites that provide historical price information. By specifying the date range and the stock symbol, you can extract historical price data for analysis.

How do I download stock data from Google Finance? ›

In the Get External Data section of Excel, choose the 'From Web' option to initiate the process of importing stock prices from Google Finance. This action opens up a pathway for users to seamlessly extract real-time stock data from an online source directly into their Excel spreadsheets.

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")

Why can't I download S&P data from Yahoo Finance? ›

This is most likely caused by licensing terms between Yahoo and the particular stock exchange or index provider. Unfortunately this currently (2023) applies to some of the most popular stock indices, including S&P500 (^GSPC) and the Dow Jones Industrial Average (^DJI).

How do I export data from Yahoo Finance to Excel? ›

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 get stock price from Yahoo Finance in Google Sheets? ›

Visit Yahoo Finance, search for your desired company or stock, and navigate to the 'historical data' tab. Select the time period and frequency for the data you need and click on 'Apply'. Click on 'download' to export the Yahoo Finance data as a CSV file. Open Google Sheets and create a new spreadsheet.

Where can I download stock market data? ›

Internet Sources for Historical Market & Stock Data
  • Yahoo! Finance - Historical Prices. ...
  • Dow Jones Industrial Averages. Historical and current performance data. ...
  • S&P Indices. Historical performance data.
  • IPL Newspaper Collection. ...
  • Securities Industry and Financial Markets Association. ...
  • FINRA: Market Data Center.
Apr 15, 2024

How do I download US stock data? ›

Save historical data from a mobile browser
  1. Go to Yahoo Finance.
  2. Enter a company name or stock symbol into the Quote Lookup field.
  3. Tap a quote in the search results to view it.
  4. Tap Historical Data above the chart.
  5. Select a Time Period, data to Show, and Frequency.
  6. Tap Apply.

What is the R package for stock data? ›

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 financial data into R? ›

You can obtain financial data in R using various packages and APIs. The "quantmod" package is commonly used to retrieve financial data from sources like Yahoo Finance. You can install it using `install. packages("quantmod")` and then use functions like `getSymbols()` to fetch data.

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.

Is there a way to pull stock prices into Excel? ›

To insert a stock price into Excel, first convert text into the Stocks data type. Then you can use another column to extract certain details relative to that data type, like the stock price, change in price, and so on.

How to fetch live stock prices in Excel? ›

You can use the function like =qm_stream_last (“MSFT“) or =qm-stream_last(B2) where cell B2 is the one that contains the stock symbol. As soon as you do that, the stock prices will start showing in your Excel cell.

How to get real-time stock data? ›

There are several companies (including Market Data) that can supply live market data for stocks for US markets:
  1. Market Data API.
  2. Intrinio.
  3. Market Stack.
  4. Finnhub.
  5. Alphavantage.
  6. Polygon.
  7. Tiingo.
  8. IEX Cloud.
Jan 28, 2024

Top Articles
Latest Posts
Article information

Author: Fredrick Kertzmann

Last Updated:

Views: 5839

Rating: 4.6 / 5 (66 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Fredrick Kertzmann

Birthday: 2000-04-29

Address: Apt. 203 613 Huels Gateway, Ralphtown, LA 40204

Phone: +2135150832870

Job: Regional Design Producer

Hobby: Nordic skating, Lacemaking, Mountain biking, Rowing, Gardening, Water sports, role-playing games

Introduction: My name is Fredrick Kertzmann, I am a gleaming, encouraging, inexpensive, thankful, tender, quaint, precious person who loves writing and wants to share my knowledge and understanding with you.