Top Related Projects
Download market data from Yahoo! Finance's API
Extract data from a wide range of Internet sources into a pandas DataFrame.
Zipline, a Pythonic Algorithmic Trading Library
ffn - a financial function library for Python
Python module to get stock data from Yahoo! Finance
Quick Overview
Alpha Vantage is a Python wrapper for the Alpha Vantage API, which provides real-time and historical financial market data. This library simplifies the process of fetching stock market data, forex rates, cryptocurrencies, and technical indicators by offering an easy-to-use interface for interacting with the Alpha Vantage API.
Pros
- Easy to use and well-documented API wrapper
- Supports a wide range of financial data types and technical indicators
- Includes built-in data visualization capabilities
- Actively maintained and regularly updated
Cons
- Requires an API key from Alpha Vantage, which may have usage limitations
- Some advanced features may require a paid subscription to Alpha Vantage
- Performance can be affected by API rate limits and network latency
- Limited to the data provided by Alpha Vantage API
Code Examples
Fetching daily stock data:
from alpha_vantage.timeseries import TimeSeries
ts = TimeSeries(key='YOUR_API_KEY')
data, _ = ts.get_daily('AAPL')
print(data)
Getting forex exchange rates:
from alpha_vantage.foreignexchange import ForeignExchange
fx = ForeignExchange(key='YOUR_API_KEY')
data, _ = fx.get_currency_exchange_rate(from_currency='USD', to_currency='EUR')
print(data)
Retrieving technical indicators:
from alpha_vantage.techindicators import TechIndicators
ti = TechIndicators(key='YOUR_API_KEY')
data, _ = ti.get_rsi('GOOGL', interval='daily', time_period=14, series_type='close')
print(data)
Getting Started
-
Install the library:
pip install alpha_vantage
-
Sign up for a free API key at Alpha Vantage.
-
Import the desired module and create an instance:
from alpha_vantage.timeseries import TimeSeries ts = TimeSeries(key='YOUR_API_KEY')
-
Fetch data using the available methods:
data, _ = ts.get_intraday('MSFT') print(data)
Remember to replace 'YOUR_API_KEY' with your actual Alpha Vantage API key in all examples.
Competitor Comparisons
Download market data from Yahoo! Finance's API
Pros of yfinance
- Free to use without API key requirements
- Supports a wider range of financial data, including options and cryptocurrency
- Generally faster data retrieval due to less stringent rate limiting
Cons of yfinance
- Less reliable data source as it scrapes Yahoo Finance
- Potential legal concerns due to unofficial API usage
- Limited historical data availability for some financial instruments
Code Comparison
alpha_vantage:
from alpha_vantage.timeseries import TimeSeries
ts = TimeSeries(key='YOUR_API_KEY')
data, _ = ts.get_daily('AAPL')
yfinance:
import yfinance as yf
ticker = yf.Ticker('AAPL')
data = ticker.history(period='1d')
Both libraries offer straightforward ways to fetch stock data, but yfinance doesn't require an API key. alpha_vantage provides more granular control over data retrieval parameters, while yfinance offers a simpler interface for quick data access. yfinance also includes additional methods for accessing various types of financial information beyond just price data.
Extract data from a wide range of Internet sources into a pandas DataFrame.
Pros of pandas-datareader
- Broader data source support, including Yahoo Finance, Google Finance, World Bank, and more
- Seamless integration with pandas DataFrame structures
- Part of the larger pandas ecosystem, benefiting from community support and updates
Cons of pandas-datareader
- Less focused on a single data provider, potentially leading to inconsistencies
- May require additional setup or dependencies for certain data sources
- Some data sources might become deprecated or change their APIs
Code Comparison
pandas-datareader:
import pandas_datareader as pdr
data = pdr.get_data_yahoo("AAPL", start="2020-01-01", end="2021-01-01")
alpha_vantage:
from alpha_vantage.timeseries import TimeSeries
ts = TimeSeries(key='YOUR_API_KEY')
data, _ = ts.get_daily("AAPL", outputsize='full')
Both libraries offer straightforward ways to fetch financial data, but alpha_vantage requires an API key and focuses specifically on the Alpha Vantage data provider. pandas-datareader provides a more generalized approach, allowing access to multiple data sources without requiring API keys for some providers.
Zipline, a Pythonic Algorithmic Trading Library
Pros of zipline
- Comprehensive backtesting engine for trading strategies
- Supports multiple asset classes and data sources
- Integrates well with Jupyter notebooks for interactive analysis
Cons of zipline
- Steeper learning curve due to its complexity
- Less frequent updates and maintenance compared to alpha_vantage
- Requires more setup and configuration for basic usage
Code Comparison
zipline:
from zipline.api import order, record, symbol
from zipline.finance import commission, slippage
def initialize(context):
context.asset = symbol('AAPL')
context.set_commission(commission.PerShare(cost=0.0075, min_trade_cost=1.0))
context.set_slippage(slippage.VolumeShareSlippage(volume_limit=0.025, price_impact=0.1))
alpha_vantage:
from alpha_vantage.timeseries import TimeSeries
ts = TimeSeries(key='YOUR_API_KEY')
data, _ = ts.get_daily('AAPL')
print(data.head())
The zipline code demonstrates setting up a trading strategy with commission and slippage models, while the alpha_vantage code shows a simple API call to fetch stock data. zipline offers more advanced features for strategy development, while alpha_vantage provides easier access to financial data.
ffn - a financial function library for Python
Pros of ffn
- Offers a wider range of financial analysis tools and performance metrics
- Provides built-in portfolio optimization capabilities
- Supports multiple data sources, not limited to a single API
Cons of ffn
- Less frequent updates and maintenance compared to alpha_vantage
- May require more setup and configuration for data retrieval
- Limited real-time data capabilities
Code Comparison
ffn:
import ffn
data = ffn.get('SPY, AAPL, MSFT', start='2010-01-01')
perf = data.calc_stats()
print(perf.display())
alpha_vantage:
from alpha_vantage.timeseries import TimeSeries
ts = TimeSeries(key='YOUR_API_KEY')
data, _ = ts.get_daily('MSFT')
print(data.head())
ffn focuses on comprehensive financial analysis and portfolio management, while alpha_vantage specializes in retrieving financial data from the Alpha Vantage API. ffn offers more built-in analysis tools, but alpha_vantage provides easier access to real-time and historical data from a specific source.
Python module to get stock data from Yahoo! Finance
Pros of yahoo-finance
- Free to use without API key requirements
- Provides real-time and historical stock data
- Offers additional financial information like company profiles and analyst recommendations
Cons of yahoo-finance
- Less reliable and may have occasional data inconsistencies
- Limited in terms of available data types and financial instruments
- May face potential legal issues due to web scraping
Code Comparison
alpha_vantage:
from alpha_vantage.timeseries import TimeSeries
ts = TimeSeries(key='YOUR_API_KEY')
data, _ = ts.get_daily('AAPL')
yahoo-finance:
import yfinance as yf
ticker = yf.Ticker('AAPL')
data = ticker.history(period='1d')
Both libraries offer simple ways to fetch stock data, but alpha_vantage requires an API key while yahoo-finance does not. alpha_vantage provides more structured data retrieval methods, while yahoo-finance offers a more straightforward approach with additional features like company information and analyst recommendations. However, alpha_vantage generally provides more reliable and consistent data compared to yahoo-finance.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
alpha_vantage
Python module to get stock data/cryptocurrencies from the Alpha Vantage API
Alpha Vantage delivers a free API for real time financial data and most used finance indicators in a simple json or pandas format. This module implements a python interface to the free API provided by Alpha Vantage. It requires a free API key, that can be requested from http://www.alphavantage.co/support/#api-key. You can have a look at all the API calls available in their API documentation.
For code-less access to financial market data, you may also consider Wisesheets or the official Google Sheet Add-on or the Microsoft Excel Add-on by Alpha Vantage. Check out this guide for some common tips on working with financial market data.
News
- From version 3.0.0 onwards, all options, commodities, and economic indicators are supported, as well as various additional features in alpha intelligence and fundamental data. All sector performance, extended intraday, and the FCAS crypto rating have been deprecated. Support for the month parameter for technical indicators and entitlement, as necessary, have also been added.
- From version 2.3.0 onwards, fundamentals data and extended intraday is supported.
- From version 2.2.0 onwards, asyncio support now provided. See below for more information.
- From version 2.1.3 onwards, rapidAPI key integration is now available.
- From version 2.1.0 onwards, error logging of bad API calls has been made more apparent.
- From version 1.9.0 onwards, the urllib was substituted by pythons request library that is thread safe. If you have any error, post an issue.
- From version 1.8.0 onwards, the column names of the data frames have changed, they are now exactly what alphavantage gives back in their json response. You can see the examples in better detail in the following git repo: https://github.com/RomelTorres/av_example
- From version 1.6.0, pandas was taken out as a hard dependency.
Install
To install the package use:
pip install alpha_vantage
Or install with pandas support, simply install pandas too:
pip install alpha_vantage pandas
If you want to install from source, then use:
git clone https://github.com/RomelTorres/alpha_vantage.git
pip install -e alpha_vantage
Usage
To get data from the API, simply import the library and call the object with your API key. Next, get ready for some awesome, free, realtime finance data. Your API key may also be stored in the environment variable ALPHAVANTAGE_API_KEY
.
from alpha_vantage.timeseries import TimeSeries
ts = TimeSeries(key='YOUR_API_KEY')
# Get json object with the intraday data and another with the call's metadata
data, meta_data = ts.get_intraday('GOOGL')
To query data from a specific month in history, you may use the 'month' parameter for various features.
from alpha_vantage.timeseries import TimeSeries
from alpha_vantage.techindicators import TechIndicators
ts = TimeSeries(key='YOUR_API_KEY')
ti = TechIndicators(key='YOUR_API_KEY')
# Get json object with the 30-min interval intraday data and another with the call's metadata for January, 2014.
data, meta_data = ts.get_intraday('GOOGL', month='2014-01', interval='30min')
#Get json object with the 30-min interval simple moving average (SMA) values and another with the call's metadata for January, 2014.
data, meta_data = ti.get_sma('GOOGL', month='2014-01', interval='30min')
You may also get a key from rapidAPI. Use your rapidAPI key for the key variable, and set rapidapi=True
ts = TimeSeries(key='YOUR_API_KEY',rapidapi=True)
Internally there is a retries counter, that can be used to minimize connection errors (in case that the API is not able to respond in time), the default is set to 5 but can be increased or decreased whenever needed.
ts = TimeSeries(key='YOUR_API_KEY',retries='YOUR_RETRIES')
The library supports giving its results as json dictionaries (default), pandas dataframe (if installed) or csv, simply pass the parameter output_format='pandas' to change the format of the output for all the API calls in the given class. Please note that some API calls do not support the csv format (namely ForeignExchange and TechIndicators
) because the API endpoint does not support the format on their calls either.
ts = TimeSeries(key='YOUR_API_KEY',output_format='pandas')
The pandas data frame given by the call, can have either a date string indexing or an integer indexing (by default the indexing is 'date'), depending on your needs, you can use both.
# For the default date string index behavior
ts = TimeSeries(key='YOUR_API_KEY',output_format='pandas', indexing_type='date')
# For the default integer index behavior
ts = TimeSeries(key='YOUR_API_KEY',output_format='pandas', indexing_type='integer')
Data frame structure
The data frame structure is given by the call on alpha vantage rest API. The column names of the data frames are the ones given by their data structure. For example, the following call:
from alpha_vantage.timeseries import TimeSeries
from pprint import pprint
ts = TimeSeries(key='YOUR_API_KEY', output_format='pandas')
data, meta_data = ts.get_intraday(symbol='MSFT',interval='1min', outputsize='full')
pprint(data.head(2))
Would result on:
The headers from the data are specified from Alpha Vantage (in previous versions, the numbers in the headers were removed, but long term is better to have the data exactly as Alpha Vantage produces it.)
Plotting
Time Series
Using pandas support we can plot the intra-minute value for 'MSFT' stock quite easily:
from alpha_vantage.timeseries import TimeSeries
import matplotlib.pyplot as plt
ts = TimeSeries(key='YOUR_API_KEY', output_format='pandas')
data, meta_data = ts.get_intraday(symbol='MSFT',interval='1min', outputsize='full')
data['4. close'].plot()
plt.title('Intraday Times Series for the MSFT stock (1 min)')
plt.show()
Giving us as output:
Technical indicators
The same way we can get pandas to plot technical indicators like Bollinger Bands®
from alpha_vantage.techindicators import TechIndicators
import matplotlib.pyplot as plt
ti = TechIndicators(key='YOUR_API_KEY', output_format='pandas')
data, meta_data = ti.get_bbands(symbol='MSFT', interval='60min', time_period=60)
data.plot()
plt.title('BBbands indicator for MSFT stock (60 min)')
plt.show()
Giving us as output:
Crypto currencies.
We can also plot crypto currencies prices like BTC:
from alpha_vantage.cryptocurrencies import CryptoCurrencies
import matplotlib.pyplot as plt
cc = CryptoCurrencies(key='YOUR_API_KEY', output_format='pandas')
data, meta_data = cc.get_digital_currency_daily(symbol='BTC', market='CNY')
data['4b. close (USD)'].plot()
plt.tight_layout()
plt.title('Daily close value for bitcoin (BTC)')
plt.grid()
plt.show()
Giving us as output:
Foreign Exchange (FX)
The foreign exchange endpoint has no metadata, thus only available as json format and pandas (using the 'csv' format will raise an Error)
from alpha_vantage.foreignexchange import ForeignExchange
from pprint import pprint
cc = ForeignExchange(key='YOUR_API_KEY')
# There is no metadata in this call
data, _ = cc.get_currency_exchange_rate(from_currency='BTC',to_currency='USD')
pprint(data)
Giving us as output:
{
'1. From_Currency Code': 'BTC',
'2. From_Currency Name': 'Bitcoin',
'3. To_Currency Code': 'USD',
'4. To_Currency Name': 'United States Dollar',
'5. Exchange Rate': '5566.80500105',
'6. Last Refreshed': '2017-10-15 15:13:08',
'7. Time Zone': 'UTC'
}
Asyncio support
From version 2.2.0 on, asyncio support will now be available. This is only for python versions 3.5+. If you do not have 3.5+, the code will break.
The syntax is simple, just mark your methods with the async
keyword, and use the await
keyword.
Here is an example of a for loop for getting multiple symbols asyncronously. This greatly improving the performance of a program with multiple API calls.
import asyncio
from alpha_vantage.async_support.timeseries import TimeSeries
symbols = ['AAPL', 'GOOG', 'TSLA', 'MSFT']
async def get_data(symbol):
ts = TimeSeries(key='YOUR_KEY_HERE')
data, _ = await ts.get_quote_endpoint(symbol)
await ts.close()
return data
loop = asyncio.get_event_loop()
tasks = [get_data(symbol) for symbol in symbols]
group1 = asyncio.gather(*tasks)
results = loop.run_until_complete(group1)
loop.close()
print(results)
We have written a much more in depth article to explain asyncio for those who have never used it but want to learn about asyncio, concurrency, and multi-threading. Check it out here: Which Should You Use: Asynchronous Programming or Multi-Threading?
Examples
I have added a repository with examples in a python notebook to better see the usage of the library: https://github.com/RomelTorres/av_example
Tests
In order to run the tests you have to first export your API key so that the test can use it to run, also the tests require pandas, mock and nose.
export API_KEY=YOUR_API_KEY
cd alpha_vantage
nosetests
Documentation
The code documentation can be found at https://alpha-vantage.readthedocs.io/en/latest/
Contributing
Contributing is always welcome. Just contact us on how best you can contribute, add an issue, or make a PR.
TODOs:
- The integration tests are not being run at the moment within travis, gotta fix them to run.
- Add test for csv calls as well.
- Add tests for incompatible parameter raise errors.
- Github actions & other items in the issues page.
Contact:
You can reach/follow the Alpha Vantage team on any of the following platforms:
- Slack
- Twitter: @alpha_vantage
- Medium-Patrick
- Medium-AlphaVantage
- Email: support@alphavantage.co
- Community events: https://alphavhack.devpost.com/
Star if you like it.
If you like or use this project, consider showing your support by starring it.
:venezuela:-:de:
Top Related Projects
Download market data from Yahoo! Finance's API
Extract data from a wide range of Internet sources into a pandas DataFrame.
Zipline, a Pythonic Algorithmic Trading Library
ffn - a financial function library for Python
Python module to get stock data from Yahoo! Finance
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot