Are you tired of struggling to understand how to use the Alpha Vantage API in your Python application? Look no further! In this article, we’ll take a step-by-step approach to retrieve stock market and cryptocurrency data using the Python alpha_vantage library and the Python requests module.
We’ll cover the mapping between the Alpha Vantage API endpoints and the Python alpha_vantage library classes and methods and show you how to call endpoints not covered by the alpha_vantage library.
Don’t waste time trying to figure it out on your own – by the end of this article, whether you’re a trader or a developer, you’ll know exactly how to use the Alpha Vantage API and the alpha_vantage library to get the information you need. Let’s get started!
You can even follow along with the Alpha Vantage API Python Tutorial Jupyter Notebook.
What Is Alpha Vantage?
Alpha Vantage is a widely used tool for accessing and analyzing financial market data. A wide range of asset classes is available. From stocks, Exchange Traded Funds (ETFs), foreign exchange rates (forex), and cryptocurrencies over economic metrics to fundamental and technical indicators: Alpha Vantage provides you with the data you need for your quantitative trading research.
What Is the Alpha Vantage API?
The Alpha Vantage Application Programming Interface (API) is a developer-friendly, easy-to-use interface to access global stock data. The API allows you to access live and historical stock data for various national and international assets. You can retrieve free historical stock price data on daily, weekly, and monthly time granularities reaching back more than 20 years. Since Cryptocurrencies have not been around for quite that long, historical data for daily Bitcoin (BTC) prices, for example, go as far back as 2011.
Alpha Vantage Pros and Cons
- Free to use.
- Offers a vast amount of historical and real-time market data and technical indicators.
- Easy to use for beginners.
- The data provided may have inconsistencies.
- Not suitable for intraday trading and use cases sensitive to the slightest price variations.
Alpha Vantage API Pricing Plans
Alpha vantage offers free and premium API plans.
The rate limit for the free API is five requests per minute and 500 requests per day. With premium plans, you can get up to 1200 API calls a minute for 249.99 USD/month.
|Number of API Requests Per Minute||Monthly Price|
How to Get Started with Alpha Vantage API in Python
You need an Alpha Vantage API key to access the financial data. You will need to answer a two-question questionnaire and leave an email address on their support page to authenticate with the Alpha Vantage APIs.
Make sure you copy and save it in a safe place in your project directory or as an environment variable.
API Key Security Advice
Your API key should be private to you and not shared with others. One way to keep your credentials safe is to store your API Keys and secrets in environment variables.
The advantage of this approach is that you can update environment variables without changing any code. You run little to no risk of accidentally checking them into your repository, thereby exposing your authentication credentials to the public.
Environment Variables for Your API Key on Windows
The easiest way to create and modify environment variables on Windows is to run the following command from PowerShell.
Ensure you replace <YOUR_API_KEY> with the API key you received from the Alpha Vantage support page.
Environment Variables for Your API Key on Linux / macOS
To set up a variable in Linux or macOS, you can start a terminal and run the following command:
Setting your temporary variable as an environment variable is as easy as running a single command on Linux; and MaxOS.
If you cannot immediately access the environment variables in code, restart your shell or coding editor for changes to come into effect.
Simple Example Fetching Data Using Alpha Vantage API in Python
To get acquainted with the API, checking out the Alpha Vantage Documentation might be worth your time. It even has some code examples of retrieving data from the API.
You can make calls to the Alpha Vantage API in three main ways:
- Using the default urllib Library
- Using the Python requests method
- Using the Alpha Vantage API Python Wrapper
Alpha Vantage API Default Urllib Library Example
If you do not want to install additional libraries, you can access Alpha Vantage’s API endpoints with the preinstalled packages only. You can use Python’s preinstalled urllib and json packages to retrieve JSON data from Alpha Vantage’s APIs like so:
Alpha Vantage API Requests Module Example
To follow along, you need to install a Python module called requests by running pip install requests. The library lets you easily send HTTP requests to the Alpha Vantage API, as shown in the following example.
Alpha Vantage API Python Library Example
Alpha Vantage API Python wrapper is a popular Python library that makes working with the Alpha Vantage API even more effortless.
To install the Python alpha_vantage library, we can use the pip package installer for Python and run:
As you will see in the later sections, the alpha vantage API consists of various endpoints. To a call function from an endpoint, you must import the alpha_vantage<endpoint_name> module followed by the class name containing your desired API function.
For instance, you must import the TimeSeries class
from the alpha_vantage to get time series intraday trading data.timeseries module, and call the intraday() method. You must pass the ticker value (IBM in the following example) to the intraday() method.
You will get a tuple containing the response’s data and metadata. You can convert the response into a Pandas dataframe, as the following output shows:
You can, by default, receive a response from the TimeSeries class methods in the form of a Pandas dataframe if you pass output_format = ‘pandas’ as an attribute value for the TimeSeries class constructor.
You can get a response in CSV format by passing `CSV` as the value for the `output_format` attribute of the TimeSeries class.
What Are The Alpha Vantage API Endpoints
As per the official documentation, Alpha Vantage groups its API functions into the following endpoints:
- Core Stock APIs Endpoint
- Alpha Intelligence Endpoint
- Fundamental Data Endpoint
- Forex Endpoint
- Cryptocurrencies Endpoint
- Technical Indicators Endpoint
- Economic Indicators Endpoint
The Python alpha_vantage library implements the above API endpoints functions into the following classes:
|Class Name||Alpha Vantage API Endpoint|
|timeseries.py||Core Stock APIs|
|fundamentaldata.py||Fundamental Data Endpoint|
|techindicators.py||Technical Indicators Endpoint|
I could not find any class or functions for the alpha intelligence and economic indicators endpoints inside the Python alpha_vantage. The library’s documentation is also silent on these endpoints. I suggest using the Python requests module to access these endpoints, as I will demonstrate in the upcoming sections.
Core Stock APIs Endpoints
As the name suggests, the Alpha Vantage Core Stock APIs endpoint implements functionalities to access basic information about stock prices. The Alpha Vantage Core APIs are useful when retrieving a stock’s real-time and historical time series data.
The Alpha Vantage also implements the fundamental data endpoint. The distinction between the naming conventions of the two endpoints needs to be clarified.
The TimeSeries class from the alpha_vantage.timeseries module contains functionalities to access Alpha Vantage’s core stock APIs endpoints.
Get Intraday Trading Data
The get_intraday() method returns intraday trading data (open, high, low, close, volume) for a symbol. You must use the symbol name to retrieve data. Optionally pass values for the `interval` and `outputsize` attributes.
Valid interval values are: ‘1min’, ‘5min’, ’15min’, ’30min’, ’60min’ (default ’15min’).
The valid values for the `outputsize` attribute are ‘full’ and ‘compact.’ The former returns full-length intraday data of more than 1MB in size. The `compact’ output returns the last 100 points in the time series. The default value is `compact`
Here is an example that returns intraday trading data for IBM with 15 minutes intervals.
You can plot intraday trading data using the plot() function of a pandas dataframe:
Get Daily Time Serie Data
You can get daily time series data for a stock using the `get_daily()` method. This is a premium method and is not available with the free API. Running the following script will throw an exception.
To see all premium endpoints, see the Alpha Vantage documentation. You will see the `premium` tag with the premium endpoints.
The get_daily_adjusted() method returns daily adjusted intraday data for a stock. This endpoint is available with the free API.
Get Weekly Time Series Data
To get weekly time series data of a stock, you can call the get_weekly() method.
If you want to retrieve weekly adjusted time series values for a stock, you can use the get_weekly_adjusted() method.
Get Monthly Time Series Data
You can use the get_monthly() method if you want monthly time series data.
You can use the get_monthly_adjusted() method for adjusted monthly time series data.
Get Latest Alpha Vantage Quotes
Time series methods can take some time to get a response from the Alpha Vantage API. If you are only interested in the latest price and volume information of stock, you can use the get_quote_endpoint() method.
Search Symbols Information with Alpha Vantage
The search symbol endpoint allows you to search for a company or stock information using keywords. You can even enter incomplete keywords. The endpoint will return information about all the matching entities. This endpoint is handy if you want to add an autocomplete search box to your financial applications.
Enter keywords in the get_symbol_search() method to search for a company or symbol.
Alpha Intelligence Endpoint
The alpha intelligence endpoint contains AI-based functions that help you make more informed trading decisions. For instance, you can get news and sentiments about a stock, and based on that information; you can decide whether or not to invest in that stock.
Get Stock News and Sentiment with Alpha Vantage
The Python alpha_vantage library doesn’t implement the alpha intelligence endpoint. The Python requests module functions can retrieve news and sentiments about a stock.
You must pass values for the `function`, `tickers`, and topics `attributes` to the API call. For example, the following script searches for news sentiment for IBM on technology-related topics.
For better viewing, I convert the output to a Pandas dataframe.
You can use the `title`, `summary`, `overall_sentiment_score`, and `over_sentiment_label` columns of the Pandas dataframe to view the corresponding values.
Fundamental Data Endpoint
The fundamental data endpoint returns fundamental information about companies or stocks, e.g., company overviews, annual earnings, exchanges, etc.
Get Company Overview Data
The get_company_overview() method returns a high-level overview of a company, including the exchange name where it trades, dividend per share, book value, revenue per share, profit margin, etc.
Get Company Annual Earnings
Strangely, unlike other fundamental data endpoint functions, the alpha_vantage library doesn’t implement a function inside the fundamentaldata.py class to retrieve a company’s annual earnings.
You can use the Python requests module, as the following script demonstrates.
Get a List of All Stocks
The alpha_vantage library doesn’t implement a function to retrieve the list of all stocks on Alpha Vantage. You can retrieve all stocks via the Python requests module.
Alpha Vantage Forex Endpoint
The forex endpoint functions return real-time and historical exchange rate information.
Get Forex Exchange Rates
The get_currency_exchange_rate() method returns exchange rates for one currency in terms of the other. For instance, the following script returns exchange rates for euros in dollars.
Get Historical Exchange Rates
You can get daily exchange rates for currency using the get_currency_exchange_daily() method.
You can retrieve weekly and monthly currency exchange rates using the get_currency_exchange_weekly() and get_currency_exchange_monthly() methods, respectively.
If you want to see currency exchange rates for shorter intervals, you can use the premium get_currency_exchange_intraday() method. You must pass the currency symbol and optional time interval to retrieve intraday currency exchange rates. Valid interval values are: ‘1min’, ‘5min’, ’15min’, ’30min’, and ’60min’ (default ’15min’).
The cryptocurrencies endpoint returns exchange rates and historical data for cryptocurrencies.
Get Cryptocurrencies Exchange Rates with Alpha Vantage
The get_digitial_currency_exchange_rate() returns real-time exchange rates for cryptocurrencies. The following script returns a Bitcoin’s value in US dollars.
Get Historical Cryptocurrencies Data
You can get daily, weekly, and monthly cryptocurrencies information via get_digital_currency_daily(), get_digital_currency_weekly(), get_digital_currency_monthly() methods, respectively.
You must pass these methods, a cryptocurrency symbol, and an exchange market symbol from the market lists.
The script below retrieves daily cryptocurrency price and volume information.
The following script retrieves monthly cryptocurrency price and volume information.
You can plot a line plot that displays time series values for cryptocurrency prices. For example, the following script plots a monthly time series plot for Bitcoin’s closing price in USD.
Technical Indicators Endpoint
Technical indicators are a handy source of information for making trading decisions. The technical indicators endpoint, as the name suggests, returns various technical indicators for a stock, e.g., weighted moving average (WMA), simple moving average (SMA), volume weighted average price (VWAP), Kaufman Adaptive Moving Average (KAMA), etc.
Get Weighted Moving Average (WMA)
The get_wma() method returns a stock’s weighted moving average values. The method accepts the following parameters:
- The stock symbol.
- The interval (optional) – valid values are ‘1min’, ‘5min’, ’15min’, ’30min’, ’60min’, ‘daily’, ‘weekly’, ‘monthly’ (default ‘daily’).
- The time period (optional): the number of data points to average. (default 20)
- The series type (optional): valid values are ‘close’, ‘open’, ‘high’, ‘low’ (default ‘close’).
Plot Kaufman Adaptive Moving Average (KAMA)
You can retrieve Kaufman Adaptive Moving Average (KAMA) values using the get_kama() method. You can then plot the returned values using the plot() method of the Pandas dataframe.
Economic Indicators Endpoint
The economic indicators endpoint contains functions that return US economic indicators frequently used for investment strategies. The alpha_vantage library doesn’t implement the functions in this endpoint. Alternatively, you can use the Python requests module.
Get Yearly USA Inflation Rates
You can retrieve the yearly US inflation rates by passing the `INFLATION` as the value for the `function` attribute of the API request to Alpha Vantage API.
Get Monthly Customer Sentiment Information
The following script returns monthly consumer sentiment and confidence data of the United States as measured by the University of Michigan Consumer Surveys.
Alpha Vantage Alternatives
Following are some alternatives to the Alpha Vantage library.
Frequently Asked Questions
How Far Back Does Alpha Vantage Data Go?
Depending upon the stock, the Alpha Vantage API returns historical data dating back more than 20 years.
Does Alpha Vantage Have ETF (Exchange Traded Fund) Data?
Alpha vantage provides various types of financial data, including stocks, ETFs, forex, mutual funds, and cryptocurrency.
Does Alpha Vantage Give Live Data?
Alpha Vantage claims to deliver real-time and historical global market data ranging from 1-minute bars up to 20+ years.
What Clients Are Available for the Alpha Vantage API?
Following are some of the clients available for the Alpha Vantage API.
How Does Alpha Vantage Make Money?
Alpha Vantage is not purely free, as the free plan allows only five requests per minute with 500 requests per day. Alpha Vantage generates most of its revenue through its premium plans.
Is Alpha Vantage Reliable?
Users report that Alpha Vantage data is mostly reliable for large and established companies. For smaller companies, the data may not be too reliable.
The Bottom Line
Alpha Vantage is a free and reliable real-time and historical financial data source. The Alpha Vantage API allows users to access financial information in code, which you can use to develop financial applications and trading bots. Researchers can also leverage the Alpha Vantage API for financial data science research.
This article showed you how to access the Alpha Vantage API endpoints in Python code using the Python alpha_vantage library and the Python requests module. The alpha_vantage client doesn’t implement all of the Alpha Vantage API endpoints. You can use the Python requests method to call the Alpha Vantage API endpoint in such cases.