romeltorres / alpha_vantage Goto Github PK
View Code? Open in Web Editor NEWA python wrapper for Alpha Vantage API for financial data.
License: MIT License
A python wrapper for Alpha Vantage API for financial data.
License: MIT License
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.
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'>
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?
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
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:
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.
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
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!
@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
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
Can you provide an example on how to do batch quotes?
Hi Romel, you're doing a great job. Thanks for your job.
To complete the api it's needed a Sector Performance wrapper, are you working on it
best regards
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
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
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!
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?
How is possible to get a list of accessible symbols?
Hi,
I'm using alpha_vantage to access Indian NSE market. Check this URL:
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.
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.
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'
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_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
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
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
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.
@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 :)
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.
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.
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:
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."
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.
It looks like it doesn't work out of the box. What I did :
I look forward to be able to test your module!
$ 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 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
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.
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.
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
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
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
is it possible to retrieve the underlying currency a symbol is traded in ?
e.g AAPL => $
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')
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)?
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"
}```
As a python developer using Alpha vantage python module
I want access to Time Series Daily Adjusted data from the Alpha Vantage API
So that I can extract dividend events
Details:
Docs: https://www.alphavantage.co/documentation/#dailyadj
Daily Adjusted API should expose the following data points:
While connecting to my alpha vantage API, I receive an "Verification error". There are two possibilities I see that could cause this problem:
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?
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)>`
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
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:
What am I doing wrong?
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
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.
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
Hi RomelTorres,
I am trying to get Australian Stock Exchange tickers. e.g.
It works on the https request, but I think there may be a problem with your class in parsing the ':' in the symbol.
Either way, thanks for a great project!
Anton
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.
date
is always set to Invalid Date
in Firefox.
Issue is that newSample['date'] = new Date(key + ' EDT');
isn't proper ES[56]. Date's ctor expects a RFC 2822 or ISO8601 dateString
but YYYY-MM-DD EDT
isn't. Chrome seems more lenient than FF.
See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Can anyone let me know when this is going to be start? Even website not loading.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.