Download Stocks quotes using R and AlphaVantage

Let´s start by covering the basics.

What you need:

Recommendations:

  • In case you are installing for the first time or doing a fresh install, I would recommend to install both R and RStudio in different folders inside the “C:\” directory.
  • Another recommendation, (not required) install everything using Anaconda. Anaconda is a built in suite for Quant and data analysis. It´s easy to use, install and maintain. From the Anaconda ecosystem you can install python, orange and others awesome tools. https://www.anaconda.com/distribution/

Now to the subject at hand. There are a few different ways to retrieve stock data. Some paid, some free, some fast, some slow. Today we will focus on AlphaVantage (https://www.alphavantage.co/)

Let´s start by claiming your free API Key:

You will have to fill a small form and no payment is required, It´s free:

https://www.alphavantage.co/support/#api-key

AlphaVantage API Form

As all things free, it comes with limitations.

API free restrictions

Now Let´s bring up our Rstudio

To run our code, we will need to basic packages:

  • alphavantager to connect to AlphaVantage API
  • xlsx to export our data to excel/csv

Let´s start by installing the packages:

install.packages(alphavantager)

install.packages(xlsx)

RStudio packages installation

Now we are set to go, let´s go right into the code:

Let´s start by initializing the libraries

library(alphavantager)

library(xlsx)

Replace “YOUR_API_KEY” with the API key you registered above

av_api_key("YOUR_API_KEY")

We can retrieve data from AlphaVantage with different timeframes:

#Daily data
quoteData <- av_get(
  symbol = "AAPL",
  av_fun = "TIME_SERIES_DAILY",
  outputsize = "full"
)

#Hourly data
quoteData <- av_get(
  symbol = "AAPL",
  av_fun = "TIME_SERIES_INTRADAY",
  interval = "60min",
  outputsize = "full"
)

The Symbol is the ticker you want to retrieve. If you have any doubts or don´t know the ticker for the company, just try searching for it on yahoo finance ( https://finance.yahoo.com/) the ticker is exactly the same.

Finally, in order to export to excel you need to define where you want to save it and how you want to name the file

write.xlsx(quoteData, "C:\\Folder\\SymbolName.xlsx",sheetName = "Daily data")

Here is the full code snippet

https://bitbucket.org/snippets/tanos-trader/Ebokz4/alphavantage-sample

If you have any question, just leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.