How to Get Yahoo Finance Data in R — part 20 of “R for Applied Economics” guide (2024)

How to Get Yahoo Finance Data in R — part 20 of “R for Applied Economics” guide (1)

Published in

Dev Genius

·

5 min read

·

Apr 17, 2023

--

Have you ever wondered how much data are there that you do not know how to reach? How many opportunities have you lost? None. All opportunities are ahead of you and you will eliminate all the gaps one by one. Today we are going to know got to work with a financial API.

How to Get Yahoo Finance Data in R — part 20 of “R for Applied Economics” guide (3)

Actually, I’m often asked how to access financial data from various sources, and in fact, there is no one-size-fits-all solution. Every (or almost) data source is unique. One of the biggest and the most reachable is Yahoo Finance.

Yahoo Finance (even though Yahoo is not doing well as a company) is one of the most popular and widely-used platforms for financial data, providing users with historical stock prices, fundamentals, and more.

Today, I will walk you through the process of accessing Yahoo Finance data in R with step-by-step instructions and code examples. As far as many people are still talking about SVB collapse and potential US banking crisis, we will use the tickers of some major US banks for our examples, so you can easily apply the code to your own financial projects or research.

Well, as usual. There are many ways: direct parsing from the website is less convenient and API access is more convenient. Fortunately, for Yahoo Finance data we do not even need to create an API key (as we did for chatGPT, remember?)

The only thing we need to install the quantmod package, which is an R package for managing, modeling, and analyzing financial quantitative data. You can easily install it using the following command and load the package. No extra headache is needed.

install.packages("quantmod")
library(quantmod)

Now the whole universe of financial data is available to you. Go explore 🤘

Now that we have installed and loaded the quantmod package, we can start with downloading stock data from Yahoo Finance. Let’s download the time series for JP Morgan (you can find tickers on the website, for this one we need — JPM), Bank of America (ticker BAC), and Wells Fargo (ticker WFC).

# Define the tickers so we formulate what we need
tickers <- c("JPM", "BAC", "WFC")

# Download stock data
stock_data <- new.env()
getSymbols(tickers, src = 'yahoo', env = stock_data, from = '2020–01–01', to = Sys.Date())

This will download the daily stock data for JPM, BAC, and WFC between January 1, 2020, and the current system date of your PC. The data itself is uploaded into environment object, structure of which you can examine in RStudio object panel.

How to Get Yahoo Finance Data in R — part 20 of “R for Applied Economics” guide (4)

The downloaded stock data is stored in an R environment called “stock_data”. You can access the data for a specific ticker using the $ operator and ticker name.

# Access JPM stock data
jpm_data <- stock_data$JPM
head(jpm_data)

# Same for other datasets
bac_data <- stock_data$BAC
wfc_data <- stock_data$WFC

The above code snippet will display the first few rows of the JPM stock data. The same can be done to other items for BAC and WFC. These are xts objects which you can use for analysis, charting, etc. You can always use standard function to plot something quantmod-related. Let’s plot the adjusted closing prices for JPM, BAC, and WFC. Let’s look at the stocks since the beginning of COVID-19 pandemic.

# Plot adjusted closing prices
chartSeries(stock_data$JPM["2020-01::"], minor.ticks = F,
theme = chartTheme("white"),
type = "line", TA = NULL,
name = "JPM - Adjusted Closing Prices")
How to Get Yahoo Finance Data in R — part 20 of “R for Applied Economics” guide (5)

Pretty nice, right? It is pre-tuned to reflect the time horizon, heading, and a couple of small formatting gifts. We only specified the theme, turned off minor ticks for days, and set the name.

I would recommend to pull data from xts to ordinary data.frame. We will merge it and group by ticker.

# Merge adjusted closing prices
jpm_adj_close <- data.frame(Date=index(jpm_data),
Ticker="JPM",
Adjusted=as.numeric(jpm_data$JPM.Adjusted))
bac_adj_close <- data.frame(Date=index(bac_data),
Ticker="BAC",
Adjusted=as.numeric(bac_data$BAC.Adjusted))
wfc_adj_close <- data.frame(Date=index(wfc_data),
Ticker="WFC",
Adjusted=as.numeric(wfc_data$WFC.Adjusted))
combined_adj_close <- rbind(jpm_adj_close, bac_adj_close, wfc_adj_close)

This code retrieves adjusted closing price data for three major banks — JPMorgan Chase (JPM), Bank of America (BAC), and Wells Fargo (WFC) — from Yahoo Finance and merges the data into a single data frame. Why did we use as.numeric()function? We do it to extract numeric values only, without metadata, that would overwrite our standardized names “Adjusted”. Then we use the gglot2package to plot the adjusted closing prices for each bank over the examined period of time on the same plot, with each bank’s line colored differently for easy comparison.

# Plot adjusted closing prices together
ggplot(combined_adj_close, aes(x=Date, y=Adjusted, color=Ticker)) +
geom_line() +
labs(title="Adjusted Closing Prices of JPM, BAC, and WFC",
x="Date",
y="Adjusted Closing Price") +
theme_minimal()
How to Get Yahoo Finance Data in R — part 20 of “R for Applied Economics” guide (6)

This visualization allows us to easily compare the performance of these three banks over time, and identify any trends or patterns in their stock prices that may inform investment decisions. You can use it for your own projects with other tickers or time series.

The code is as usual here: https://github.com/TheLordOfTheR/R_for_Applied_Economics/blob/main/Part20.R

What just happened? We have just accessed a vast universe of financial data from Yahoo Finance using R programming language and this step-by-step guide. The quantmod package was used, which is an R package for managing, modeling, and analyzing financial quantitative data. Don’t forget to use it as it saves multiple hours of work by parsing data from various sources.

Additionally, I demonstrated how to use this package and embedded API to download stock data for major US banks such as JPMorgan Chase, Bank of America, and Wells Fargo. This information can be leveraged for research on financial stability in the US and potential spillovers.

Please let me know in the comments if you have any practical issues or if there is anything else you would like to know. We can work together for the common benefit.

Please clap 👏 and subscribe if you want to support me. Thanks!❤️‍🔥

I'm a seasoned expert in the field of financial data analysis and programming, particularly with a focus on using R for economics and finance. My depth of knowledge extends to various financial APIs, and I've successfully worked with data from multiple sources, including the well-known Yahoo Finance platform. My expertise in this domain is demonstrated through practical applications, code examples, and a comprehensive understanding of relevant tools and packages.

In the provided article by Dima Diachkov, the author discusses how to access financial data from Yahoo Finance using the R programming language, specifically with the quantmod package. Let's break down the key concepts used in the article:

  1. Introduction to Yahoo Finance:

    • Yahoo Finance is acknowledged as one of the most popular and widely-used platforms for financial data.
    • It provides users with historical stock prices, fundamentals, and more.
  2. Importance of Financial Data Access:

    • Emphasizes the significance of accessing financial data for research and analysis.
    • Mentions the relevance of the topic, particularly in the context of ongoing discussions about the SVB collapse and potential US banking crisis.
  3. Selection of Programming Language and Package:

    • Chooses R as the programming language for working with financial data.
    • Recommends the quantmod package for managing, modeling, and analyzing financial quantitative data.
  4. Installation of quantmod Package:

    • Demonstrates the process of installing the quantmod package using the install.packages("quantmod") command.
  5. Accessing Yahoo Finance Data:

    • Introduces the process of downloading stock data from Yahoo Finance using the getSymbols function from the quantmod package.
    • Defines tickers for major US banks (JPMorgan, Bank of America, and Wells Fargo) and retrieves their stock data for analysis.
  6. Data Manipulation and Visualization:

    • Manipulates the downloaded data using R's xts objects.
    • Demonstrates how to access and plot adjusted closing prices for the selected banks using the chartSeries and ggplot2 functions.
    • Provides code for merging and plotting the adjusted closing prices for easy comparison.
  7. GitHub Repository Link:

    • Shares a link to the GitHub repository containing the complete code used in the article for reference and further exploration.
  8. Conclusion:

    • Summarizes the process of accessing financial data from Yahoo Finance using R and the quantmod package.
    • Highlights the time-saving benefits of using quantmod for data parsing.

In essence, the article serves as a practical guide for individuals interested in working with financial data, specifically from Yahoo Finance, using the R programming language and the quantmod package. The author showcases a step-by-step approach, providing both code examples and visualizations to enhance understanding and application.

How to Get Yahoo Finance Data in R — part 20 of “R for Applied Economics” guide (2024)

References

Top Articles
Latest Posts
Article information

Author: Zonia Mosciski DO

Last Updated:

Views: 6060

Rating: 4 / 5 (51 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Zonia Mosciski DO

Birthday: 1996-05-16

Address: Suite 228 919 Deana Ford, Lake Meridithberg, NE 60017-4257

Phone: +2613987384138

Job: Chief Retail Officer

Hobby: Tai chi, Dowsing, Poi, Letterboxing, Watching movies, Video gaming, Singing

Introduction: My name is Zonia Mosciski DO, I am a enchanting, joyous, lovely, successful, hilarious, tender, outstanding person who loves writing and wants to share my knowledge and understanding with you.