Package: alpha-vantage
alpha_vantagePython module to get stock data/cryptocurrencies from the Alpha Vantage APIAlpha 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 byAlpha Vantage. It requires a free API key, that can be requested fromhttp://www.alphavantage.co/support/#api-key. You can have a look at all the API calls available in theirAPI documentation.For code-less access to the APIs, you may also consider the officialGoogle Sheet Add-onor theMicrosoft Excel Add-onby Alpha Vantage. Check outthisguide for some common tips on working with financial market data.NewsFrom 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,rapidAPIkey 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_exampleFrom version 1.6.0, pandas was taken out as a hard dependency.InstallTo install the package use:pipinstallalpha_vantageOr install with pandas support, simply install pandas too:pipinstallalpha_vantagepandasIf you want to install from source, then use:gitclonehttps://github.com/RomelTorres/alpha_vantage.git
pipinstall-ealpha_vantageUsageTo 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 variableALPHAVANTAGE_API_KEY.fromalpha_vantage.timeseriesimportTimeSeriests=TimeSeries(key='YOUR_API_KEY')# Get json object with the intraday data and another with  the call's metadatadata,meta_data=ts.get_intraday('GOOGL')You may also get a key fromrapidAPI. Use your rapidAPI key for the key variable, and setrapidapi=Truets=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 (namelyForeignExchange, SectorPerformances 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 behaviorts=TimeSeries(key='YOUR_API_KEY',output_format='pandas',indexing_type='date')# For the default integer index behaviorts=TimeSeries(key='YOUR_API_KEY',output_format='pandas',indexing_type='integer')Data frame structureThe 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:fromalpha_vantage.timeseriesimportTimeSeriesfrompprintimportpprintts=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.)PlottingTime SeriesUsing pandas support we can plot the intra-minute value for 'MSFT' stock quite easily:fromalpha_vantage.timeseriesimportTimeSeriesimportmatplotlib.pyplotaspltts=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 indicatorsThe same way we can get pandas to plot technical indicators like Bollinger Bands®fromalpha_vantage.techindicatorsimportTechIndicatorsimportmatplotlib.pyplotaspltti=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:Sector PerformanceWe can also plot sector performance just as easy:fromalpha_vantage.sectorperformanceimportSectorPerformancesimportmatplotlib.pyplotaspltsp=SectorPerformances(key='YOUR_API_KEY',output_format='pandas')data,meta_data=sp.get_sector()data['Rank A: Real-Time Performance'].plot(kind='bar')plt.title('Real Time Performance (%) per Sector')plt.tight_layout()plt.grid()plt.show()Giving us as output:Crypto currencies.We can also plot crypto currencies prices like BTC:fromalpha_vantage.cryptocurrenciesimportCryptoCurrenciesimportmatplotlib.pyplotaspltcc=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)fromalpha_vantage.foreignexchangeimportForeignExchangefrompprintimportpprintcc=ForeignExchange(key='YOUR_API_KEY')# There is no metadata in this calldata,_=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 supportFrom 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 theasynckeyword, and use theawaitkeyword.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.importasynciofromalpha_vantage.async_support.timeseriesimportTimeSeriessymbols=['AAPL','GOOG','TSLA','MSFT']asyncdefget_data(symbol):ts=TimeSeries(key='YOUR_KEY_HERE')data,_=awaitts.get_quote_endpoint(symbol)awaitts.close()returndataloop=asyncio.get_event_loop()tasks=[get_data(symbol)forsymbolinsymbols]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?ExamplesI have added a repository with examples in a python notebook to better see the
usage of the library:https://github.com/RomelTorres/av_exampleTestsIn 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.exportAPI_KEY=YOUR_API_KEYcdalpha_vantage
nosetestsDocumentationThe code documentation can be found athttps://alpha-vantage.readthedocs.io/en/latest/ContributingContributing 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:SlackTwitter: @alpha_vantageMedium-PatrickMedium-AlphaVantageEmail:support@alphavantage.coCommunity 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: