Alpha Vantage Introduction Guide

12 min read

Get 10-day Free Algo Trading Course


Last Updated on January 11, 2021

Alpha Vantage Homepage Image
Alpha Vantage’s Homepage

Table of Contents

  1. What is the Alpha Vantage API?
  2. Is the Alpha Vantage API free?
  3. What kind of data does the Alpha Vantage API offer?
  4. What are the advantages of using the Alpha Vantage API?
  5. Why shouldn’t I use the Alpha Vantage API?
  6. What are some alternatives to the Alpha Vantage API?
  7. How do I get started with the Alpha Vantage API?
  8. Do I need to use a library to access the Alpha Vantage API?
  9. How do I configure the Alpha Vantage Library?
  10. How do I retrieve stock data using the Alpha Vantage library in Python?
  11. How can I get retrieve stock data without using the Alpha Vantage library in Python?
  12. Does the Alpha Vantage API work well with the Pandas Library?
  13. Should I use the CSV or JSON format for my data?
  14. How can I use technical indicators with the Alpha Vantage library?
  15. Final Thoughts on the Alpha Vantage API

What is the Alpha Vantage API?

The Alpha Vantage API is a method to obtain historical and realtime data for several markets.

You can access the data directly in Python or any other programming language of your choosing. From there, you can manipulate the data or store it for later use.

Is the Alpha Vantage API free?

Alpha Vantage proudly offers its service for free. They provide a generous rate limit of 5 requests per minute and 500 requests per day.

Several premium plans are available if you require a higher rate limit. The premium plans start at $29.99 per month for 30 requests per minute and go as high as $249.99 per month for 1200 requests per minute.

Premium plans come with 24/7 technical support and don’t have daily limits.

What kind of data does the Alpha Vantage API offer?

Alpha Vantage offers historical and realtime data for stocks, forex, and cryptocurrencies. Several time frames are available ranging from 1-minute bars up to monthly.

In addition to price data, there are more than 50 technical indicators available as well as performance data for 10 US equity sectors.

What are the advantages of using the Alpha Vantage API?

The biggest advantage is that its free. Further, the data is extensive. We found price data dating back 20 years for stocks and forex. Cryptocurrency data for assets like Bitcoin went back as far as 2011 in terms of daily price data.

» Quandl Guide: Learn how to retrieve price and non-price data from Quandl.


  1. WTI Crude Oil prices
  2. US GDP Data
  3. Facebook Annual Report Data

Link: Quandl: A Step-by-Step Guide

Why shouldn’t I use the Alpha Vantage API?

You may not want to use the Alpha Vantage API if you already have access to price data through your broker. Data can differ from one provider to another and its best to use broker data if you plan to execute trades.

Along the same lines, some automated systems are very sensitive to small differences in data between different providers. In this scenario, it’s worthwhile comparing data with other providers. Paid data providers often boast that they have the most accurate data available.

What are some alternatives to the Alpha Vantage API?

There were a number of free data APIs a few years ago such as Google Finance and Yahoo Finance. Unfortunately, they no longer offer an official API.

The Investors Exchange (IEX) is one of the few providers that still offers free API access. Their offering is a bit more extensive compared to Alpha Vantage. However, their rate limits can be a little tricky as each endpoint carries a different weight in terms of how many requests you can make.

» IEX offers earnings data, news, financial statements in addition to historical data. Check out our IEX API guide: IEX API Introduction Guide

Another alternative is who offers free access to their trading API for up to 250 requests per day. Premium plans are available starting at $8 per month and go as high as $32 per month.

How do I get started with the Alpha Vantage API?

The first step is to claim your API key. The process is quick and easy and a key is necessary for all the requests.

After getting your key, we highly recommend having a look at the API documentation. You can see what kind of data is being offered, but more importantly, this is where you can figure out which parameters are required for each API request. You will likely be referring to it a lot.

The next step is deciding if you want to utilize the Alpha Vantage library.

Do I need to use a library to access the Alpha Vantage API?

This is certainly a case where you can get away without using the library, although it does make things a bit easier.

Aside from standard API functionality, the library offers panda’s integration and simplifies the process of plotting charts.

You can install the library by running pip install alpha_vantage from the command prompt. If you don’t have pandas installed on your system, you can use pip install alpha_vantage pandas.

Alternatively, download the zip file from the GitHub repository and extract the alpha_vantage folder in your projects folder.

If you’ve gone through our Alpaca API guide <INSERT LINK> you will already have the Alpha Vantage python library on your system.

How do I configure the Alpha Vantage Library?

After installing the Alpha Vantage library, it is a good idea to store your API key as an environment variable. This is an extra security precaution so that your key is not visible in plain text within your code.

There have been instances where individuals have pushed code to their public GitHub page only to have someone exploit their key, so this step is highly recommended.

Saving your key as an environment variable

Windows – Click Start and type in environment variables. You should see an option to Edit environment variables for your account.

Setting an environment variable in Windows

In the new window that pops up, click New under the User variables section.

Your variable name should be ALPHAVANTAGE_API_KEY and the variable value is where you can paste in your key.

Creating a New User Variable in Windows

Mac/Linux – From your terminal, type in:

export ALPHAVANTAGE_API_KEY=123456789

Make sure to use your actual API key for the value. You can confirm that the environment variable is saved by typing in the following which should display your API key:

Creating an environment variable in Linux
Creating an environment variable on a Mac

If the environment variable comes up blank in Python you made need to restart your code editor for the changes to take effect.

Importing the library into Python

After setting the environment variable, you’ll want to import the Alpha Vantage library into Python.

The library is set up in such a way that each of the 5 sections within the Alpha Vantage API documentation has been coded in a separate file within the library.

You will have to import the appropriate part of the library and instantiate the class within it. Here is an example.

from alpha_vantage.timeseries import TimeSeries

app = TimeSeries() 

In the above code, we import the TimeSeries class from which is the part of the library that handles API calls for stock data. We then instantiate the TimeSeries class to inherit all of its functions.

If you didn’t store your API key in an environment variable, you can pass it through when instantiating the class like this:

app = TimeSeries('your_api_key_goes_here')

Otherwise, the library will automatically grab the API key from the environment variable for you.

To make things easier, we’ve created a table that links the required import statement corresponding to each section of the Alpha Vantage documentation.

Alpha VantageImport statement for library
Stock Time Series from alpha_vantage.timeseries import TimeSeries
Forex (FX) from alpha_vantage.foreignexchange import ForeignExchange
Cryptocurrenciesfrom alpha_vantage.cryptocurrencies import CryptoCurrencies
Technical Indicatorsfrom alpha_vantage.techindicators import TechIndicators
Sector Performancesfrom alpha_vantage.sectorperformance import SectorPerformances

How do I retrieve stock data using the Alpha Vantage library in Python?

At this point, we’ve imported the library and instantiated the TimeSeries class. Our next step is to grab some data.

There are several options available under the Stock Time Series section of the Alpha Vantage documentation. We will go with Daily Adjusted data, otherwise known as TIME_SERIES_DAILY_ADJUSTED.

We need to figure out which function in the library corresponds with the API endpoint we are trying to call. We can do that by running the help command.


This gives us a printout of all the different functions available within the TimeSeries class. They are in the same order as they appear in the documentation so it should be easy to find the right one.

The image above shows the function we are after. As you can see, the only parameter we need to pass through is the stock ticker symbol.

By default, the library will set the output size to compact. This will return the last 100 data points. If you are looking to for more data then simply pass through output='full' to get all the data available.

from alpha_vantage.timeseries import TimeSeries

app = TimeSeries()

aapl = app.get_daily_adjusted('AAPL', outputsize='full')

And there you have it, the last 100 daily data points for AAPL in four lines of code.

The return output by default is in JSON. Further in the tutorial, we will discuss outputting data in CSV and in pandas.

How can I get retrieve stock data without using the Alpha Vantage library in Python?

We can get the same data in the above example without using the Alpha Vantage library fairly easily. There are numerous libraries available to access URLs. Commonly known libraries include http.client, requests, and urllib just to name a few.

In our example, we will use the requests library. If you don’t already have it installed, type in pip install requests to install it.

Our first step is to import the requests library and the os library. The latter will be used to retrieve our API key from the environment variable that we created.

import requests
import os

api_key = os.getenv('ALPHAVANTAGE_API_KEY')

The above code will print out your API key, just to make sure everything is working. If you don’t have your key saved as an environment variable, you can assign your key to the api_key variable at this point.

You may have noticed that the Alpha Vantage documentation has examples in each section. Let’s copy the first example URL in the documentation for TIME_SERIES_DAILY_ADJUSTED and create a request.

response = requests.get('')

In the above code, we’ve passed in the entire URL right into the request. At that point, we used .json(), which is part of the requests library, to convert the JSON data to a Python dictionary.

As you can see, we can make requests by simply passing through our parameters into the URL.

We can even use an f string to make the parameters a bit more dynamic.

base_url = ''
symbol = 'IBM'

response = requests.get(f'{base_url}function={function}&symbol={symbol}&apikey={api_key}')

The above code allows us to easily change the parameters by assigning different values for the associated variables.

Passing through the entire URL with parameters, or using f strings, will give you the desired result. However, it’s not a very Pythonic way of doing things. The code snippet below attempts to ‘clean things up a bit’.

base_url = ''
params = {'function': 'TIME_SERIES_DAILY_ADJUSTED',
		 'symbol': 'IBM',
		 'apikey': api_key}

response = requests.get(base_url, params=params)

What we’ve done here is created a dictionary that holds all of our parameters. We then pass the dictionary into our request which is a much cleaner way of doing this. Especially for calls where several parameters are required. It also makes our code much more readable in case we have to make changes down the road.

Now that we have our base code for making requests, you should be able to query any of the Alpha Vantage endpoints. Simply modify or append the params dictionary with the required API parameters listed within the documentation. The base URL will remain the same for all queries.

Does the Alpha Vantage API work well with the pandas library?

The pandas library is great for manipulating data and is popular among algo traders.

Integration with pandas is built into the Alpha Vantage library. Simply pass through output_format='pandas' when instantiating the appropriate class for your request.

from alpha_vantage.foreignexchange import ForeignExchange

app = ForeignExchange(output_format='pandas')

eurusd = app.get_currency_exchange_intraday('EUR', 'USD')

In the above example, we are requesting intraday data for EUR/USD. By default, the library returns 15 minute candles for this particular endpoint.

The returned data is a tuple that contains the pandas dataframe as well as information about the returned data. Since we’re only interested in the dataframe, we’ve specified print(eurusd[0]) to separate the dataframe from the tuple.

What’s great about the dataframe returned by the library is that it is formated with a time-series index. That means we can run commands like this:


This allows us to narrow down our dataframe to only candles from April 1st.

Below is the code to perform the same function without using the library.

import os
import requests
import pandas as pd 

api_key = os.getenv('ALPHAVANTAGE_API_KEY')

base_url = ''
params = {'function': 'FX_INTRADAY',
  'from_symbol': 'EUR',
  'to_symbol': 'USD', 
  'interval': '15min',
  'apikey': api_key}

response = requests.get(base_url, params=params)
response_dict = response.json()
_, header = response.json()

#Convert to pandas dataframe
df = pd.DataFrame.from_dict(response_dict[header], orient='index')

#Clean up column names
df_cols = [i.split(' ')[1] for i in df.columns]
df.columns = df_cols

df.set_index('timestamp', inplace=True) #Time-series index 


Getting the response into a dataframe isn’t straightforward but can be done with a few tweaks.

First, we had to separate out our price data from the JSON response as it contains two parts of information. The first part provides information about the query, or essentially, metadata. The second part is the price data that we are after. So we’ve had to specify that we only want to convert the time series data into a dataframe.

We were able to separate the two parts of the response with this command: _, header = response.json(). This is a dynamic method to obtain the dictionary key value for the price data. We then use that information to convert our dictionary to a pandas dataframe.

We also had to add orient='index'. Otherwise, the row and columns are inversed due to the nature of the response format.

Lastly, we’ve cleaned up the column headers just to remove any numbers or spaces and set the timestamp column as the index to create a time-series index.

Should I use the CSV or JSON format for my data?

Choosing between CSV or JSON comes down to what you intend on doing with the data after the fact, and to a certain degree, personal preference.

The advantage of the CSV format is that it comes with little overhead. Unlike the JSON format, it does not accompany metadata. Further, the column headers are already neatly formatted.

The disadvantage of the CSV format is that it is not easily recognized by Python. You may have noticed how easily the requests module is able to convert JSON objects to a dictionary in the previous examples.

You can use the CSV module which is a standard Python library, although we find that method to be tedious – again personal preference.

If you’re looking to save data for later use, CSV is the way to go. Check out the code snippet below:

import os
import requests
import pandas as pd

api_key = os.getenv('ALPHAVANTAGE_API_KEY')

base_url = ''
params = {'function': 'FX_INTRADAY',
		 'from_symbol': 'EUR',
		 'to_symbol': 'USD', 
		 'interval': '15min',
		 'datatype': 'csv',
		 'apikey': api_key}

response = requests.get(base_url, params=params)

#Save CSV to file
with open('eurusd.csv', 'wb') as file:

df = pd.read_csv('eurusd.csv') #Create pandas dataframe

df.set_index('timestamp', inplace=True) #Time-series index

Notice that we’re able to get save the response as a file in two lines of codes. Further, once saved, we can retrieve the data directly into a pandas dataframe using only one line of code.

If you attempt to save the CSV response directly to a dataframe, you’re likely to get an error unless you clean up the data first.

If you plan to use the Alpha Vantage library, your best bet is to use the pandas output format. If you need to save your pandas dataframe to file, simply use the following syntax:


How can I use technical indicators with the Alpha Vantage library?

A great feature of the Alpha Vantage API is that it has values for over 50 different indicators. This saves having to manually calculate them or use a third-party library.

Let’s look at an example of getting MACD data for AAPL.

The Alpha Vantage library uses a standard naming convention in the TechIndicators class. Simply use get_ and add the name of the indicator as it is stated in the documentation


Similar to one of the prior examples, we can use the help function to find out the required arguments

We can see that we need to supply at least a symbol, the fast period, slow period, and signal period. The indicator will be calculated on the closing price by default which is what we want. The interval is set to daily by default.

from alpha_vantage.techindicators import TechIndicators

app = TechIndicators(output_format='pandas')

aapl_macd = app.get_macd('aapl', fastperiod=12, slowperiod=26, signalperiod=9)

In the code example above, we started by importing the TechIndicators class. We then instantiated our class, specifying that the output should be a pandas data frame. The required parameters were passed through the function and the output was saved as aapl_macd.

You can use the same format used in the code snippet above to get values for other indicators. A cool feature of time-series dataframes is that we can easily merge our indicator dataframe with a price dataframe. Pandas will match up merged dataframes with the index column which in our case is a timestamp.

You may have noticed when we pulled Forex data that we had to separately specify the from currency and to currency. For technical indicators, the syntax differs in that the symbol is used as a whole. Take a look at the following examples for Bitcoin and USD/JPY.

BTC_macd = app.get_macd('BTCUSD', fastperiod=12, slowperiod=26, signalperiod=9)
usdjpy_macd = app.get_macd('USDJPY', fastperiod=12, slowperiod=26, signalperiod=9)

While this is a useful feature of the API, we recommend only using it for historical data. If you attempt to use it for realtime data, especially on smaller time frames, make sure not to go over your rate limit.

Final Thoughts

Alpha Vantage offers a great product, and best of all, the free API has a very generous rate limit. The Alpha Vantage library makes the API easier to use, especially if you plan to use pandas.

If you intend to use the API as part of your automated trading system we suggest you implement some form of error checking to confirm that your request did in fact return valid data as internet interruptions do happen. Also, be mindful of the 500 requests per day limit and make sure your API key is kept secure.

Download Code

The code used in the examples is available on GitHub. From the GitHub page, click the green button on the right “Clone or download” to download or clone the code.

Jignesh Davda