Code Monkey home page Code Monkey logo

alpha_vantage's Introduction

alpha_vantage

Build Status PyPI version Documentation Status Average time to resolve an issue Percentage of issues still open

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 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')

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, 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 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: alt text

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: alt text

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: alt text

Sector Performance

We can also plot sector performance just as easy:

from alpha_vantage.sectorperformance import SectorPerformances
import matplotlib.pyplot as plt

sp = 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:

alt text

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: alt text

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:

Star if you like it.

If you like or use this project, consider showing your support by starring it.

๐Ÿ‡ป๐Ÿ‡ช-๐Ÿ‡ฉ๐Ÿ‡ช

alpha_vantage's People

Contributors

addisonlynch avatar alphavantagesupport avatar bastienjalbert avatar cclauss avatar dahifi avatar dhoeppe avatar eitanp82 avatar filipefilardi avatar hemphill39 avatar igorborgest avatar ilcardella avatar jackmoody11 avatar javierflip avatar jmcneves avatar joncinque avatar muskoxleader avatar onefarad avatar patrickalphac avatar pnijhara avatar renatomello avatar rishk avatar romeltorres avatar sanmuhe avatar shreypuranik avatar stevealphavantage avatar tkplista avatar tuxskar avatar vasilescur avatar woutdenolf avatar xou avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

alpha_vantage's Issues

Installation: Access is denied

During the installation of the package I reach a point where it stops due to access being denied. I have confirmed that there is no administrator (administrator disabled). I am running Windows 7, Python36-32. Any help would be greatly appreciated. Thank you.

image

Data are being skipped

Hi,

I'm using alpha_vantage to access Indian NSE market. Check this URL:

https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=INFY.NS&interval=30min&outputsize=full&apikey=*****

It misses out on data of 2018-03-14, 2018-03-15 and 2018-03-16.

I even posted this on the website community (second post on that thread):
https://www.alpha-vantage.community/post/missing-prices-for-one-date-for-stock-on-italian-market-9683004

When I posted that, only March 14th and 15th data was missing but 16th was available. (Probably because it was 16th itself). I think it starts to skip data after March 13 and shows the data only of the current date. Please check this.

Seems Issue with API call

Hi tested the below code:
from alpha_vantage.timeseries import TimeSeries
from pandas_datareader import data as web
import pandas as pd

ts = TimeSeries(key='YOUR API', output_format='pandas')
data, meta_data = ts.get_intraday(symbol='DISHTV',interval='5min', outputsize='compact')
print(data)
It's throwing error as below:
image

Something between Compact and Full?

Hey,

Is there a way to download daily data of 2-3 years.
I am downloading data for around 270 Healthcare stock in python and I want it for atleast 3 years.

outputsize='full', takes a lot of time, even compact mode took 20 mins

Is there any other way to do it

Date as index for pandas dataframe

Hello. will the recent update the index column is now an int index. Would be great if there would be an option to have the date as index again. Makes zero sense for me to have an integer index. Thanks for your consideration.
Steffen

Pandas header missing for date time column

Hi .

  The column header missing for the date and time column in the pandas output. It would be great if you add the same. 

                               volume  close   high   open    low

2017-10-13 04:21:00 13418.0 84.35 84.45 84.45 84.35
2017-10-13 04:22:00 4045.0 84.40 84.45 84.35 84.35
2017-10-13 04:23:00 848.0 84.45 84.45 84.40 84.40
2017-10-13 04:24:00 6123.0 84.50 84.50 84.40 84.40
2017-10-13 04:25:00 1591.0 84.40 84.50 84.45 84.40

get_digital_currency_daily() market = USD

One small issue using "get_digital_currency_daily()". The result is returned in two currencies, market and USD, OK. But if I set the market to USD I get duplicate Pandas labels.

So indexing a row ( row['. close (USD)'] ) results in a two element series for USD, and a scalar for other markets.

The duplicate data comes from AV, but is not really an issue for them as they present data as a structured list and parsing would normally take the first match. However inserting all this data into a table (Pandas) results in duplicate keys. Indexing the table gets two matches and returns a list of two values rather than the single USD value we get from other markets.

Test case:
usd.zip

This prints:
For GBP price returns <class 'numpy.float64'>
For USD price returns <class 'pandas.core.series.Series'>

Make pandas dependency optional

It causes a lot of dependencies, including pycrypto which is difficult to install since it includes native libraries.
Maybe we can import it on demand?

timeseries

Copy and pasted the code for the basic GOOGL stock check, error is seen.

from alpha_vantage.timeseries import TimesSeries
ts = TimesSeries(key='YOUR_API_KEY')
data, meta_data = ts.get_intraday('GOOGL')

from alpha_vantage.timeseries import TimesSeries
ModuleNotFoundError: No module named 'alpha_vantage.timeseries'

Anaconda can't find package

Hello,

I'm trying to install the alpha_vantage package but I'm having some trouble. When trying to install it, the package can't be found.

"
C:\ conda install alpha_vantage

Fetching package metadata .............

PackageNotFoundError: Packages missing in current channels:

  • alpha_vantage
    "

What am I doing wrong?

Does not support CSV querys

This package does not support CSV queries as requested by Alpha Vantage for all wrapper libraries as quoted from their FAQ page:

I have built a library/wrapper for Alpha Vantage with a specific programming language. May I open-source it on GitHub?
Certainly - we truly appreciate the help and support from the community to make Alpha Vantage even more accessible and developer-friendly. However, we ask that your language-specific library/wrapper preserves the content of our JSON/CSV responses in both success and error cases. We consider it a top priority that our users get the original debugging and troubleshooting information from Alpha Vantage.

Intraday call is offline at the moment.

The intraday API call is offline for the moment. It should be available again in a couple of weeks.

I hope you guys can work around that for a few weeks

Saludos
Romel

Cannot import name TimeSeries

Hello!

After a fresh pip install alpha_vantage in a virtualenv with python 3.5 I'm trying to do the example:

from alpha_vantage.timeseries import TimesSeries
ts = TimesSeries(key='YOUR_API_KEY')
data, meta_data = ts.get_intraday('GOOGL')

However, when running this i get:

Traceback (most recent call last):
File "av.py", line 1, in <module>
from alpha_vantage.timeseries import TimeSeries
ImportError: cannot import name 'TimeSeries'

I also tried installing from source with the same result and also with python 2.7.

Variable 'err' referenced before assignment

When trying to fetch data for a symbol that does not exist in the api i get the following:

Traceback (most recent call last):
File "manage.py", line 29, in
outputsize='compact')
File "/home/joakim/.virtualenvs/alphavantage/lib/python3.5/site-packages/alpha_vantage/alphavantage.py", line 152, in _format_wrapper
json_response, data_key, meta_data_key = func(self, *args, **kwargs)
File "/home/joakim/.virtualenvs/alphavantage/lib/python3.5/site-packages/alpha_vantage/alphavantage.py", line 138, in _call_wrapper
return self._handle_api_call(url), data_key, meta_data_key
File "/home/joakim/.virtualenvs/alphavantage/lib/python3.5/site-packages/alpha_vantage/alphavantage.py", line 76, in _retry_wrapper
raise ValueError(err)
UnboundLocalError: local variable 'err' referenced before assignment

CSV output error

Hello,

The CSV output of the module is actually a csv reader object. If trying to iterate through it it will return each character of a line, not the fields.

The problem seems to be at the line 275 of alphavantage.py:
csv_response = csv.reader(url_response)

In order for the reader to work correctly, the line should be:
csv_response = csv.reader(url_response.splitlines())

Reproducing the issue:

#!/usr/bin/env python
from alpha_vantage.timeseries import TimeSeries
ts = TimeSeries(key='API_KEY', retries=3, output_format='csv')
data_m15, meta_data_m15 = ts.get_intraday(symbol='GE', interval='15min', outputsize='full')
print meta_data_m15
print data_m15
for line in data_m15:
    print line

Output:

None
<_csv.reader object at 0x287b4b0>
['t']
['i']
['m']
['e']
['s']
['t']
['a']
['m']
['p']
['', '']
['o']
['p']
['e']
['n']
['', '']
['h']
['i']
['g']
['h']
['', '']
['l']
['o']
['w']
['', '']
['c']
['l']
['o']
['s']
['e']
['', '']
['v']
['o']
['l']
['u']
['m']
['e']
[]
[]

Output with the suggested change:

None
['timestamp', 'open', 'high', 'low', 'close', 'volume']
...

Thanks for the great work you did on the module.

Time Series for Daily and Weekly

This is a great project, so far I can get the intraday and techindicators to run with no problem. I was wondering how to run the daily and weekly data. I suspect this can be done by rolling up the smaller timeframes in Pandas, but wasn't sure. Thanks for your help.

Py 3.6.1, alpha_vantage 1.1.4 - traceback: from alpha_vantage.timeseries import TimeSeries

Hello. have Py 3.6.1 and installed alpha_vantage version 1.1.4 via pip3 install.
when i run the following little script i get a traceback:

import alpha_vantage
from alpha_vantage.timeseries import TimeSeries
ts = TimeSeries(key='my key')
data, meta_data = ts.get_intraday('GOOGL')

traceback:
line 2, in
from alpha_vantage.timeseries import TimeSeries
ModuleNotFoundError: No module named 'alpha_vantage.timeseries'

pip3 show alpha_vantage confirms that the model is installed.

Crash on incorrect api key

When I gave it the wrong api key seems to crash:

Traceback (most recent call last):
File "av.py", line 4, in
data, meta_data = ts.get_daily('STO:SAAB-B', outputsize='compact')
File "/home/joakim/.virtualenvs/alphavantage/lib/python3.5/site-packages/alpha_vantage/alphavantage.py", line 152, in _format_wrapper
json_response, data_key, meta_data_key = func(self, *args, **kwargs)
File "/home/joakim/.virtualenvs/alphavantage/lib/python3.5/site-packages/alpha_vantage/alphavantage.py", line 138, in _call_wrapper
return self._handle_api_call(url), data_key, meta_data_key
File "/home/joakim/.virtualenvs/alphavantage/lib/python3.5/site-packages/alpha_vantage/alphavantage.py", line 76, in _retry_wrapper
raise ValueError(err)
UnboundLocalError: local variable 'err' referenced before assignment

can we control the outputsize with numbers?

Hello,

In order to only get the latest real-time data point with

get_intraday(symbol='AAPL', interval='30min', outputsize = 'compact' )

according to the docs. output size is either 'full' or 'compact'.

if I call the API every 15min with 'compact' I am still getting 100 data points per API call.
so I have to delete all the 99 points and append my database with the latest (100th) data point.

Is there a way to query only the latest datapoint or control the outputsize with numbers?

get_intraday(symbol='AAPL', interval='30min', outputsize = '1' )

thank you

Getting TypeError on basic commands

When running:
ts = TimeSeries(key='MY_API_KEY', output_format='pandas')
data, meta_data = ts.get_intraday(symbol='MSFT',interval='1min', outputsize='full')
data['close'].plot()
plt.title('Intraday Times Series for the MSFT stock (1 min)')
plt.show()

I am receiving a TypeError: argument of type 'int' is not iterable command. Not sure why this is, I'm copying the exact code from the documentation.

I receive the same error for everything except for SectorPerformances

Date Column

The date column doesn't become a valid column when I use:

ts = TimeSeries(key=os.environ.get('ALPHAVANTAGE_API'), output_format='pandas')
data = ts.get_daily_adjusted('aapl', outputsize='full')

TimeSeries not working

This code does not work:

ts = TimeSeries(key=ALPHAVANTAGE_API_KEY, output_format='pandas')
data, meta_data = ts.get_intraday(symbol='MSFT',interval='1min', outputsize='full')

It creates the following error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-2-49784970f022> in <module>()
      3 
      4 ts = TimeSeries(key=ALPHAVANTAGE_API_KEY, output_format='pandas')
----> 5 data, meta_data = ts.get_intraday(symbol='MSFT',interval='1min', outputsize='full')
      6 
      7 data['close'].plot()

D:\Programs\Anaconda3\lib\site-packages\alpha_vantage\alphavantage.py in _format_wrapper(self, *args, **kwargs)
    171         def _format_wrapper(self, *args, **kwargs):
    172             call_response, data_key, meta_data_key = func(
--> 173                 self, *args, **kwargs)
    174             if 'json' in self.output_format.lower() or 'pandas' \
    175                     in self.output_format.lower():

D:\Programs\Anaconda3\lib\site-packages\alpha_vantage\alphavantage.py in _call_wrapper(self, *args, **kwargs)
    156             else:
    157                 url = '{}&apikey={}'.format(url, self.key)
--> 158             return self._handle_api_call(url), data_key, meta_data_key
    159         return _call_wrapper
    160 

D:\Programs\Anaconda3\lib\site-packages\alpha_vantage\alphavantage.py in _retry_wrapper(self, *args, **kwargs)
     75                 except ValueError as err:
     76                     error_message = str(err)
---> 77             raise ValueError(str(error_message))
     78         return _retry_wrapper
     79 

ValueError: Invalid API call. Please retry or visit the documentation (https://www.alphavantage.co/documentation/) for TIME_SERIES_INTRADAY.

I am using Python 3.6.4 on Jupyter Notebook.

Certification Verification failed

While connecting to my alpha vantage API, I receive an "Verification error". There are two possibilities I see that could cause this problem:

  1. My campus internet is not giving me permission. However, I tried switching to another campus internet service and still found the same problem. Is there a way I can test my hypothesis?

  2. I looked at the requirements file and I could not download Spinx-napolean. However, this is not part of the instruction, so I am not sure if this is required for just downloading data.

Given below in my error message

`Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 1318, in do_open
encode_chunked=req.has_header('Transfer-encoding'))
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1239, in request
self._send_request(method, url, body, headers, encode_chunked)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1285, in _send_request
self.endheaders(body, encode_chunked=encode_chunked)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1234, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1026, in _send_output
self.send(msg)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 964, in send
self.connect()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1400, in connect
server_hostname=server_hostname)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 401, in wrap_socket
_context=self, _session=session)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 808, in init
self.do_handshake()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 1061, in do_handshake
self._sslobj.do_handshake()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py", line 683, in do_handshake
self._sslobj.do_handshake()
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:748)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "temp.py", line 4, in
data, meta_data = ts.get_intraday('GOOGL')
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/alpha_vantage/alphavantage.py", line 173, in _format_wrapper
self, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/alpha_vantage/alphavantage.py", line 158, in _call_wrapper
return self._handle_api_call(url), data_key, meta_data_key
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/alpha_vantage/alphavantage.py", line 74, in _retry_wrapper
return func(self, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/alpha_vantage/alphavantage.py", line 259, in _handle_api_call
response = urllib.request.urlopen(url)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 223, in urlopen
return opener.open(url, data, timeout)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 532, in open
response = meth(req, response)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 642, in http_response
'http', request, response, code, msg, hdrs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 564, in error
result = self._call_chain(*args)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 504, in _call_chain
result = func(*args)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 756, in http_error_302
return self.parent.open(new, timeout=req.timeout)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 526, in open
response = self._open(req, data)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 544, in _open
'_open', req)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 504, in _call_chain
result = func(*args)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 1361, in https_open
context=self._context, check_hostname=self._check_hostname)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 1320, in do_open
raise URLError(err)
urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:748)>`

New version cannot address dataframe values anymore

Hi,

Thanks for the great module. I noticed since the new version you cannot address the data.column.values anymore without error. For example:

ts = TimeSeries(key=self.args.api_key, retries=3, output_format='pandas')
data, meta_data = ts.get_daily(symbol=self.args.symbol,outputsize='full')
print data.open.values
print data.close.values

These methods were really convenient to use with ta-lib. It seems in the new version the colum names are more like:

1. open

instead of just open

4. close

instead of just close

I guess there used to be something that stripped those off?

Thanks!

Small errata in the example of the Bollinger Bands

Hola Romel.

I tested your package and it's a great work! Thank you for your effort.

I am sure it will be a very popular package now that the Yahoo Finance API service has been canceled.

But I wanted to point out that in the BB example there is a small error in the code:

You write :

from alpha_vantage.techindicators import TechIndicators
import matplotlib.pyplot as plt

ts = 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()

and the correct is a ts at line 5:

from alpha_vantage.techindicators import TechIndicators
import matplotlib.pyplot as plt

ts = TechIndicators(key='YOUR_API_KEY', output_format='pandas')
data, meta_data = ts.get_bbands(symbol='MSFT', interval='60min', time_period=60)
data.plot()
plt.title('BBbands indicator for  MSFT stock (60 min)')
plt.show()

I know that isn't very important, but this way it's perfect.

You've done a great job!

Inconstiney in SYMOBOL for Indian stock exchnage

Hi While using the api found the inconsistent behavior some symbol work from TIME_SERIES_DAILY but the same symbol does not work when I use it in TIME_SERIES_INTRADAY

example NSE index symbole (NSEI took from yahoo as suggested from others) works in TIME_SERIES_INTRADAY, not in TIME_SERIES_DAILY

ex

https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=NSEI&interval=5min&outputsize=full&apikey=key

https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol= NSEI&outputsize=full&apikey=key

Another example of stock PVR code PVR.NS (as per yahoo finance) works for daily but not work for intraday

https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=PVR.NS&interval=5min&outputsize=full&apikey=key

Many stocks with the same ticker symbol

Hello,

It seems like there are many stocks with the same ticker symbol, the API is not able to differentiate between various stock markets, priority is given to NYSE over others.
ex:
American Campus Communities, Inc.(NYSE:ACC)
ACC Ltd(NSE:ACC)
Is there a way to use NSE's ACC
I found more than 30 scrips with same ticker symbol in the top 250 scrips.

Thank you

Just after a pip install : ImportError: No module named 'alpha_vantage'

It looks like it doesn't work out of the box. What I did :

  • set my environment with virtualenv
  • pip install alpha_vantage
  • type python and try to import module
  • fail :)

I look forward to be able to test your module!


Python console

$ python
Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.

import alpha_vantage
Traceback (most recent call last):
File "", line 1, in
ImportError: No module named 'alpha_vantage'


pip install

pip install alpha_vantage
Collecting alpha_vantage
Downloading alpha_vantage-0.1.3.tar.gz
Requirement already satisfied: simplejson in ./env/lib/python3.5/site-packages (from alpha_vantage)
Collecting pandas (from alpha_vantage)
Downloading pandas-0.20.1-cp35-cp35m-manylinux1_x86_64.whl (24.0MB)
100% |โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ| 24.0MB 38kB/s
Collecting nose (from alpha_vantage)
Downloading nose-1.3.7-py3-none-any.whl (154kB)
100% |โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ| 163kB 253kB/s
Requirement already satisfied: python-dateutil>=2 in ./env/lib/python3.5/site-packages (from pandas->alpha_vantage)
Requirement already satisfied: pytz>=2011k in ./env/lib/python3.5/site-packages (from pandas->alpha_vantage)
Requirement already satisfied: numpy>=1.7.0 in ./env/lib/python3.5/site-packages (from pandas->alpha_vantage)
Requirement already satisfied: six>=1.5 in ./env/lib/python3.5/site-packages (from python-dateutil>=2->pandas->alpha_vantage)
Building wheels for collected packages: alpha-vantage
Running setup.py bdist_wheel for alpha-vantage ... done
Stored in directory: /home/cyrille/.cache/pip/wheels/37/2b/e9/95c76cfabd97fa92b83c1ff19e3ee3b17d7d9620b373d8b577
Successfully built alpha-vantage
Installing collected packages: pandas, nose, alpha-vantage
Successfully installed alpha-vantage-0.1.3 nose-1.3.7 pandas-0.20.1

ts.get_daily() returns Error. Was working previously

Hi Romel.
trying

data, metadta = ts.get_daily(symbol='^TNX')

which previously worked is throwing an error.
ValueError: Invalid API call. Please retry or visit the documentation (https://www.alphavantage.co/documentation/) for TIME_SERIES_DAILY.

Updated to latest alpha_vantage 1.3.6 earlier today. Could that be the problem?

when trying to download other data i get HTTP Error 503. AlphaVantage not so reliable anymore sadly.

OTC and PINK sheet

Could you tell me if I could pull OTC and PINK sheet data ($Volume, Volume, # trades, bid and ask) with Alpha Vantage Api? For instance, could I pull the last price for HEMP, MJNA, PHOT and POTN?

Problems to install the package

Hola Romel.

I tried to install to package following your instructions, but wasn't possible.
I use Python 2.7, and I get this message:

$ sudo python setup.py install
/usr/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'install_requires'
  warnings.warn(msg)
running install
running build
running install_egg_info
Removing /usr/local/lib/python2.7/dist-packages/alpha_vantage-0.0.1.egg-info
Writing /usr/local/lib/python2.7/dist-packages/alpha_vantage-0.0.1.egg-info

When run nosetest this other:

ERROR: Failure: ImportError (No module named alpha_vantage.api_calls.alphavantage)

I also install with pip correctly nose and simplejson.
What's the problem?
Thanks

Alpha Vantage API Review

Alpha Vantage API Review from a Python Developer

@RomelTorres congratulations on your wonderful python library for Alpha Vantage!

I am a full-stack python developer who uses the Alpha Vantage API to develop trading strategies for stocks, ETFs, and OTCs. I am wondering whether you are affiliated with Alpha Vantage, and whether this is a good place for me to leave a 360ยฐ review on their API service for future reference by the developer community.

So technically this is not a bug report or feature request - hope it's OK with you :)

The Experience

I was one of the "yahoo refugees" who stumbled upon Alpha Vantage via Google search. My first interactions with their website could be summarized by the good-old term WYSIWYG (what-you-see-is-what-you-get). Their documentation promised three things: (1) time series data with various resolutions, (2) over 50 technical signals, (3) sector data, and they kept their promise by providing demo URLs for all the said API functions.

image

They promised free API keys, and they also delivered. They promised "no promotional materials to your inbox," and indeed the only email I got from them so far was the announcement email for their new CSV feature.

This being said, there are a couple areas they could optimize upon.

  • Be more specific about their business model. Being "100% free" is good, but it can also be a bit scary, especially for a yahoo refugee like me.
  • Add multi-symbol support so that one can query multiple stocks with a single API call.
  • Their FAQ recommends "~200 API calls per minute." It would be great if they can set a hard limit on the call volume to prevent client-side abuses in the form of ultra-high-frequency requests.

The Data

Of the thousands of US-based equities I have analyzed so far, their historical data and technical indicators seem to match other reputable data sources. Their intraday data is realtime up to the current minute, which is fine for my research purposes but may not satisfy users who want to beat the market with millisecond precision. Perhaps a premium feature for this down the road?

Their JSON output is easily readable and python-parsable. For the daily time series, however, I understand that their most recent data point is the cumulative information of the current trading day (updated realtime), but why is the first timestamp in YYYY-MM-DD HH:MM:SS format while all the others are in the normal YYYY-MM-DD format typical of the EOD data?

"Meta Data": {
"1. Information": "Daily Prices (open, high, low, close) and Volumes",
"2. Symbol": "MSFT",
"3. Last Refreshed": "2017-08-18 16:00:00",
"4. Output Size": "Compact",
"5. Time Zone": "US/Eastern"
},
"Time Series (Daily)": {
"2017-08-18 16:00:00": {
"1. open": "72.2700",
"2. high": "72.8400",
"3. low": "71.9300",
"4. close": "72.4900",
"5. volume": "18215276"
},
"2017-08-17": {
"1. open": "73.5800",
"2. high": "73.8700",
"3. low": "72.4000",
"4. close": "72.4000",
"5. volume": "21834250"
},

I would love to see a consistent YYYY-MM-DD format across all the timestamps. The "last refreshed" timestamp can be specified in Meta Data instead:

"Meta Data": {
"1. Information": "Daily Prices (open, high, low, close) and Volumes",
"2. Symbol": "MSFT",
"3. Last Refreshed": "2017-08-18 16:00:00",
"4. Output Size": "Compact",
"5. Time Zone": "US/Eastern"
},
"Time Series (Daily)": {
"2017-08-18": {
"1. open": "72.2700",
"2. high": "72.8400",
"3. low": "71.9300",
"4. close": "72.4900",
"5. volume": "18215276"
},
"2017-08-17": {
"1. open": "73.5800",
"2. high": "73.8700",
"3. low": "72.4000",
"4. close": "72.4000",
"5. volume": "21834250"
},

In addition to the data presentation aspects, below are couple other data-related proposals:

  • Expand CSV support to all API functions. CSV is currently enabled only for the time series APIs.
  • Make error messages more informative for debugging purposes.

In Summary

It is always a pleasure to have an API service that is well documented, platform/language-agnostic, and easily integratable. The fact that we have several third-party libraries built on top of Alpha Vantage on GitHub is in a sense testament to its developer-friendly nature. While there is still room for them to become a better version of themselves, I hope they thrive and stay true to the description on their home page - "driven by rigorous research, cutting edge technology, and a disciplined focus on democratizing access to data."

TimeSeries doesn't work on python 3.6.4

ts.get_daily('VFINX')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.6/site-packages/alpha_vantage/alphavantage.py", line 173, in _format_wrapper
self, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/alpha_vantage/alphavantage.py", line 158, in _call_wrapper
return self._handle_api_call(url), data_key, meta_data_key
File "/usr/local/lib/python3.6/site-packages/alpha_vantage/alphavantage.py", line 74, in _retry_wrapper
return func(self, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/alpha_vantage/alphavantage.py", line 259, in _handle_api_call
response = urllib.request.urlopen(url)
AttributeError: module 'urllib' has no attribute 'request'

I think that you need to go back to importing urlopen directly. 1.3.6 works correctly.

Example Code Doesn't Work in Python 3.6.1

Installed alpha_vantage from pip.

`from alpha_vantage.timeseries import TimeSeries
import matplotlib.pyplot as plt

ts = TimeSeries(key='my key was here', output_format='pandas')
data, meta_data = ts.get_intraday(symbol='MSFT',interval='1min', outputsize='full')
data['close'].plot()
plt.title('Intraday Times Series for the MSFT stock (1 min)')
plt.show()`

"C:\Users\Doug\OneDrive\family\doug\work in progress\alphavantage\alphaenv\Scripts\python.exe" "C:/Users/Doug/OneDrive/family/doug/work in progress/alphavantage/rolling returns/alpha_play.py"
Traceback (most recent call last):
File "C:\Users\Doug\OneDrive\family\doug\work in progress\alphavantage\alphaenv\lib\site-packages\pandas\core\indexes\base.py", line 2525, in get_loc
return self._engine.get_loc(key)
File "pandas_libs\index.pyx", line 117, in pandas._libs.index.IndexEngine.get_loc
File "pandas_libs\index.pyx", line 139, in pandas._libs.index.IndexEngine.get_loc
File "pandas_libs\hashtable_class_helper.pxi", line 1265, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas_libs\hashtable_class_helper.pxi", line 1273, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'close'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:/Users/Doug/OneDrive/family/doug/work in progress/alphavantage/rolling returns/alpha_play.py", line 6, in
data['close'].plot()
File "C:\Users\Doug\OneDrive\family\doug\work in progress\alphavantage\alphaenv\lib\site-packages\pandas\core\frame.py", line 2139, in getitem
return self._getitem_column(key)
File "C:\Users\Doug\OneDrive\family\doug\work in progress\alphavantage\alphaenv\lib\site-packages\pandas\core\frame.py", line 2146, in _getitem_column
return self._get_item_cache(key)
File "C:\Users\Doug\OneDrive\family\doug\work in progress\alphavantage\alphaenv\lib\site-packages\pandas\core\generic.py", line 1842, in _get_item_cache
values = self._data.get(item)
File "C:\Users\Doug\OneDrive\family\doug\work in progress\alphavantage\alphaenv\lib\site-packages\pandas\core\internals.py", line 3843, in get
loc = self.items.get_loc(item)
File "C:\Users\Doug\OneDrive\family\doug\work in progress\alphavantage\alphaenv\lib\site-packages\pandas\core\indexes\base.py", line 2527, in get_loc
return self._engine.get_loc(self._maybe_cast_indexer(key))
File "pandas_libs\index.pyx", line 117, in pandas._libs.index.IndexEngine.get_loc
File "pandas_libs\index.pyx", line 139, in pandas._libs.index.IndexEngine.get_loc
File "pandas_libs\hashtable_class_helper.pxi", line 1265, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas_libs\hashtable_class_helper.pxi", line 1273, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'close'

Process finished with exit code 1

Searching, Sorting and Slicing Pandas dataframe for dates and collumn names with spaces

@RomelTorres having never used panda frames I am on a steep learning curve going through pandas docs. However I am blocked on searching the date collumn and having issues with collumn names with spaces.

Concerning date collumn:
As a alpha Avantage python developer
I want to search (query), sort and slice on the Date/Time column.
So that I can find specific values based on data and time

Issue: I can not seem to reference the date/time column in the same manner as I can for the other collumns. Am I missing something?

Concerning collumn names with spaces:
As an alpha avantage python developer
I want a consistant way to reference collumns
So that I can re-use code patterns and keep my code readable

Issue: I find that when a column name does not have a space there are nice tight and elegant ways to refer to the column names. For columns that have spaces I find that there is a limited number of ways to call those columns, and you need to use more verbose syntax (including quotes). This becomes especially challenging when using other pandas features such as query.

Perhaps the column names in the dataframe can use underscores instead of spaces to help avoid the complexities of dealing with spaces. I wonder if there is a concept in pandas that might allow a column name and a column lable to applied, where the lable has a space and the name has an underscore?

Just some thoughts.

Cheers

how to insert ajusted close and dividend in this code ?

Option Explicit

Public Const addInName As String = "AVQ"

'' Signatur of XLQ function.
Public Function XLQ(ticker As String, _
Optional side As String = "LAST", _
Optional hist As String = "") As Variant
On Error GoTo Error

'' Check if Alpha Vantage API Key is set, if not exit function.
Dim apiKey As String
If CheckApiKey = False Then
    XLQ = CVErr(xlErrNA)
    Exit Function
Else
    apiKey = GetApiKey
End If

Static sendUnsupportedHistMessage As Boolean
Static sendUnsupportedSideMessage As Boolean
Dim item As String
'' If no quote was found, then return Excel #N/A error.
Dim quote As Variant: quote = CVErr(xlErrNA)

If hist <> vbNullString Then
    '' Send notification only once in a session.
    If sendUnsupportedHistMessage = False Then
        MsgBox hist + " is not supported by AVQ.", , addInName
        sendUnsupportedHistMessage = True
    End If
    Exit Function
ElseIf UCase(side) = "LAST" Then
    item = "close"
ElseIf UCase(side) = "CLOSE" Then
    item = "close"
ElseIf UCase(side) = "LOW" Then
    item = "low"
ElseIf UCase(side) = "HIGH" Then
    item = "low"
ElseIf UCase(side) = "VOLUME" Then
    item = "volume"
ElseIf UCase(side) = "ADJUSTED_CLOSE" Then
    item = "adjusted_close"

    
Else
    '' Send notification only once in a session.
    If sendUnsupportedSideMessage = False Then
        MsgBox side + " is not provided by Alpha Vantage.", , addInName
        sendUnsupportedSideMessage = True
    End If
    Exit Function
End If

quote = AVQD(ticker, item)
XLQ = quote

Exit Function

Error:
'' If an error occurs, then return #NULL! error.
XLQ = CVErr(xlErrNull)
End Function

'' Alpha Vantage Query for daily equity data.
Public Function AVQD(ByVal symbol As String, _
Optional ByVal item As String = "close", _
Optional ByVal day As Integer = 0, _
Optional ByVal quoteDate As Date) As Variant
On Error GoTo Error

'' Check if Alpha Vantage API Key is set, if not exit function.
Dim apiKey As String
If CheckApiKey = False Then
    AVQD = CVErr(xlErrNA)
    Exit Function
Else
    apiKey = GetApiKey
End If

'' Switch to wait cursor, to notificate the user about background activities.
Application.Cursor = xlWait

'' "This API returns daily time series (date, daily open, daily high, daily low, daily close, daily volume) _
    of the equity specified, covering up to 20 years of historical data."
Rem Const apiKey As String = "<Alpha Vantage API Key>"
Const API_FUNCTION As String = "TIME_SERIES_DAILY_ADJUSTED"
Const URL_ALPHA_VANTAGE_QUERY As String = "https://www.alphavantage.co/query"

Dim url As String
Dim http As Object
Dim json As Dictionary
Dim timeSeriesDaily As Dictionary
Dim strQuoteDate As String: strQuoteDate = ""
Dim quoteDay As Dictionary
'' If no quote was found, then return Excel #N/A error.
Dim quote As Variant: quote = CVErr(xlErrNA)

'' Provided Alpha Vantage Time Series Data (Default is "4. close").
'' For ease of use, the preceding numbering is not necessary.
Select Case item
    Case "open", "1. adj close"
        item = "1. adj close"
    Case "high", "2. high"
        item = "2. high"
    Case "low", "3. low"
        item = "3. low"
    Case "close", "4. close"
        item = "4. close"
    Case "volume", "5. volume"
        item = "5. volume"
    Case "volume", "6. adjusted_close"
        item = "6. adjusted_close"
    
End Select

'' If optional quoteDate parameter is set, then select the data point of given quoteDate.
If quoteDate <> "00:00:00" Then
    strQuoteDate = Format(quoteDate, "YYYY-MM-DD")
Else
    '' Select the most recent data point if 0 (default) was given.
    If day <> 0 Then
        '' If day is negative, then select data point "current date minus <day>".
        If day < 0 Then
            strQuoteDate = Format(DateAdd("d", day, Date), "YYYY-MM-DD")
        Else '' Else select the data point at position <day> (zero-based index).
            day = day - 1
        End If
    End If
End If

'' API documentation: https://www.alphavantage.co/documentation/#daily
url = URL_ALPHA_VANTAGE_QUERY + "?" + "function=" + API_FUNCTION + "&symbol=" + symbol + "&apikey=" + apiKey

Set http = CreateObject("MSXML2.XMLHTTP")
With http
    .Open "GET", url, False
    .Send
    '' Get JSON text/data and convert to Dictionary object.
    Set json = JsonConverter.ParseJson(.responseText)
    If Not (json Is Nothing) Then
        '' Get JSON object "Time Series (Daily)" with time series data points.
        Set timeSeriesDailyAdjusted = json("Time Series (Daily)")
        If strQuoteDate <> vbNullString Then '' Get JSON object "Date" by given <quoteDate>.
            If timeSeriesDailyAdjusted.Exists(strQuoteDate) Then
                Set quoteDay = timeSeriesDailyAdjusted(strQuoteDate)
            End If
        '' Get JSON object "Date" by index "day".
        ElseIf timeSeriesDailyAdjusted.Count >= day + 1 Then
            Set quoteDay = timeSeriesDailyAdjusted.Items(day)
        End If
        If Not (quoteDay Is Nothing) Then
            If quoteDay.Exists(item) Then
                quote = quoteDay.item(item)
                '' Set quote value as Double with decimal separator which match to current Excel settings.
                Select Case Application.International(xlDecimalSeparator)
                    Case ","
                        quote = CDbl(Replace(Replace(quote, ",", ""), ".", ","))
                    Case Else
                        quote = CDbl(quote)
                End Select
            End If
        End If
        '' Return quote.
        AVQD = quote
        GoTo Cleanup
    End If
End With

Error:
'' If an error occurs, then return #NULL! error.
AVQD = CVErr(xlErrNull)

Cleanup:
'' Switch back to default cursor.
Application.Cursor = xlDefault
'' Cleanup.
Set http = Nothing
End Function

Private Function CheckApiKey() As Boolean
Static sendMissingApiKeyMessage As Boolean
Dim apiKey As String
apiKey = GetApiKey
If apiKey = vbNullString Then
'' Send notification only once in a session.
If sendMissingApiKeyMessage = False Then
MsgBox "Please set Alpha Vantage API Key." + vbNewLine + _
"Go to Ribbon AVQ -> Set Api Key." + vbNewLine + _
"Claim your free API Key here: https://www.alphavantage.co/support/#api-key", , addInName
sendMissingApiKeyMessage = True
End If
CheckApiKey = False
Else
CheckApiKey = True
End If
End Function

Private Function GetApiKey() As String
Dim apiKey As String
apiKey = Settings.Range("A1").Value2
GetApiKey = apiKey
End Function

Private Sub SaveApiKey(ByVal apiKey As String)
On Error Resume Next
'' Alpha Vantage API Key is saved in "internal" worksheet "Settings".
Settings.Range("A1").Value2 = apiKey
If Application.Workbooks.Count > 0 Then
Application.CalculateBeforeSave = False
End If
ThisWorkbook.Save
If Application.Workbooks.Count > 0 Then
Application.CalculateBeforeSave = True
End If
End Sub

Public Sub SetApiKey(control As IRibbonControl)
Dim apiKey As String
apiKey = InputBox("Alpha Vantage API Key:", addInName)
If apiKey <> vbNullString Then
SaveApiKey apiKey
Rem Application.CalculateFullRebuild
RefreshAll Nothing
End If
End Sub

Public Sub RefreshAll(control As IRibbonControl)
Rem Application.CalculateFull
If Not ActiveWorkbook Is Nothing Then
'' Re-Calculate only AVQ UDFs.
Cells.Replace What:="=AVQD(", Replacement:="=AVQD("
'' Re-Calculate only XLQ UDF.
Cells.Replace What:="=XLQ(", Replacement:="=XLQ("
End If
End Sub

Public Sub RefreshSelection(control As IRibbonControl)
If Not Selection Is Nothing Then
Selection.Replace What:="=", Replacement:="="
End If
End Sub

Private Sub OpenLink(ByVal url As String)
Dim wshShell As Object
Set wshShell = CreateObject("WScript.Shell")
'' For security reasons only opening of links are allowed.
wshShell.Run "http://" + url

Cleanup:
'' Cleanup.
Set wshShell = Nothing
End Sub

Public Sub OpenHelpLink(control As IRibbonControl)
Dim url As String
url = control.Tag
OpenLink (url)
End Sub

Private Sub Build()
Dim fileName As String
Dim fileFullName As String

SaveApiKey ""

ThisWorkbook.RemovePersonalInformation = False

fileName = Left(ThisWorkbook.Name, Len(ThisWorkbook.Name) - InStrRev(ThisWorkbook.Name, ".") - 1)

fileFullName = ThisWorkbook.Path + "\GitHub.local\" + fileName + ".xlam"
ThisWorkbook.SaveAs fileFullName, XlFileFormat.xlOpenXMLAddIn, , , , , , , False

'' Excel 2003 currently not supported.
Rem fileFullName = ThisWorkbook.Path + "\GitHub.local\" + fileName + ".xla"
Rem ThisWorkbook.SaveAs fileFullName, XlFileFormat.xlAddIn, , , , , , , False

ThisWorkbook.Close

End Sub

Information Error Message not handled properly

The Information message when the API call has been called too many times is not being processed properly and will probably return a json/panda data frame without any errors.

{
    "Information": "Please consider optimizing your API call frequency"
}```

Unit tests fail sometimes in Travis

I made a mistake when I was writing the uni tests for the package, as I did not differentiate from unit testing and integration tests.

I would like to change that so all the calls to the API in the unit tests are replaced by mock ups and the real calls are moved to integration tests that are allowed to fail in Travis .

Romel

outputsize='full' in get_daily_adjusted() traceback

Hello, when i use the optional argument outputsize='full' in the get_daily_adjusted() function i get:
TypeError: init() got an unexpected keyword argument 'outputsize'

code snipped I use:

import alpha_vantage
from alpha_vantage.timeseries import TimeSeries
ts = TimeSeries(key='my API key', outputsize='full')
data = ts.get_daily_adjusted('VOO')

what am I doing wrong?
another question: Is there a way to retrieve a defined timeframe of data (like for example the last year)?

Hong Kong Stock not working

Dear RomelTorres
Thank you for the great package. I used it really comfortably. However, whenever I use

symbol = '0005.HK'

It doesn't work and gives Valueerror.
0005.HK is a stock in Hong Kong, and it doesn't work for some reason.
I can use the symbol in normal api documentation from the official website.

Details:
line 173, in _format_wrapper(self, *args, ** kwargs)
line 158, in call_wrpper
retry wrapper
raise ValueError(str(error_message))
ValueError Invaild API call. Please retry or ......

Thank you very much.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.