Giter Site home page Giter Site logo

addisonlynch / iexfinance Goto Github PK

View Code? Open in Web Editor NEW
648.0 36.0 136.0 10.23 MB

Python SDK for IEX Cloud

Home Page: https://addisonlynch.github.io/iexfinance

License: Apache License 2.0

Python 99.03% Shell 0.82% Makefile 0.15%
finance data stocks-api stock-data stock-prices pandas

iexfinance's People

Contributors

addisonlynch avatar anthonyvd avatar b1twhys avatar dgnsrekt avatar edwardbetts avatar gliptak avatar jackmoody11 avatar kafana avatar nckturner avatar olshansk avatar saymv avatar stubs avatar yairmz avatar yehoshuadimarsky 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

iexfinance's Issues

Cleanup Items

A few things need to be cleaned up involving iexfinance's setup as a package.

Docstrings

  • Clean and verify all necessary docstrings

Docs

  • Create CONTRIBUTING section of readme and docs
    • Repair flake8 requirements
  • Test and verify all hyperlinks and images in docs

Github

  • Create issue template
  • Create pull request template

BUG: Maximum of 10 types allowed in request. 0.2.0 IexFinance/Share/Batch broken

Hello,

I'm having trouble getting this to work all of a sudden. I was testing some of the code last night and it was working perfectly fine, but now I get the following traceback. I have included a sample of the code I'm using.

The traceback led me to this part in iexretriever.py:

    def _validate_response(response):
        if response.text == "Unknown symbol":
            raise IEXSymbolError(self.symbolList[0])

        json_response = response.json()
        if not json_response:
            raise IEXQueryError()
        elif "Error Message" in json_response:
            raise IEXQueryError()
        return json_response

When I had the response.text printed to console it said:

"Maximum of 10 types allowed." Hopefully, that helps. I have no idea what that means.

Code sample:

import iexfinance as iex
batch = ['AAPL', 'GOOGL', 'TSLA']
for symbol in batch:
    print(iex.Share(symbol))
print(iex.Batch(batch))

Traceback (most recent call last):
File "C:/PycharmProjects/run_test.py", line 92, in
print(iex.Share(symbol))
File "C:\Python3\lib\site-packages\iexfinance_init_.py", line 39, in init
self.data_set = self.refresh()
File "C:\Python3\lib\site-packages\iexfinance_init_.py", line 43, in refresh
data = super(Share, self)._fetch()
File "C:\Python3\lib\site-packages\iexfinance\iexretriever.py", line 180, in _fetch
return self._fetch_default_options()
File "C:\Python3\lib\site-packages\iexfinance\iexretriever.py", line 166, in _fetch_default_options
response = self._executeIEXQuery(query)
File "C:\Python3\lib\site-packages\iexfinance\iexretriever.py", line 131, in _executeIEXQuery
return _api_call(cls, url)
File "C:\Python3\lib\site-packages\iexfinance\iexretriever.py", line 130, in _api_call
return cls._validate_response(r)
File "C:\Python3\lib\site-packages\iexfinance\iexretriever.py", line 110, in validate_response
json_response = response.json()
File "C:\Python3\lib\site-packages\requests\models.py", line 866, in json
return complexjson.loads(self.text, **kwargs)
File "C:\Python3\lib\site-packages\simplejson_init
.py", line 518, in loads
return _default_decoder.decode(s)
File "C:\Python3\lib\site-packages\simplejson\decoder.py", line 370, in decode
obj, end = self.raw_decode(s)
File "C:\Python3\lib\site-packages\simplejson\decoder.py", line 400, in raw_decode
return self.scan_once(s, idx=_w(s, idx).end())
File "C:\Python3\lib\site-packages\simplejson\scanner.py", line 79, in scan_once
return _scan_once(string, idx)
File "C:\Python3\lib\site-packages\simplejson\scanner.py", line 70, in _scan_once
raise JSONDecodeError(errmsg, string, idx)
simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

rls 0.3.2

Python 2.7+ install errors (#44), test case failures (#45), and errors with the IEX Market Data Functions (#46) will trigger a new minor release 0.3.2

BUG: Chart endpoint date parameter not functional

Per the docs, the chart endpoint parameter values also include:

date: IEX-only data by minute for a specified date in the format YYYYMMDD if available

The following script

from iexfinance import IexFinance as iex

aapl = iex("AAPL", chartRange="date")

aapl.get_chart()

returns:

[]

when it should return IEX's intra-day prices from a specified date.

ImportError: cannot import name 'Stock'

Installed the package using

pip install iexfinance

When I try to import the package, in Python 3.6

from iexfinance import Stock

I get the error

ImportError: cannot import name 'Stock'

Did I miss out something?

Stocks Field Methods return int instead of float

Consider the following get_open result

{"open":{"price":178,"time":1520346600658},"close":{"price":176.67,"time":1520370000495},"high":178.25,"low":176.13}

price will be cast as an int at some point. this should remain a float (and possibly display 178.00). Returning an int is incorrect behavior.

Chart endpoint not correctly downloading

Default options

aapl = iex("AAPL")
aapl.get_chart()

Returns

[]

Non-default options

aapl2 = iex("AAPL", chartRange='1d')

Returns

Traceback (most recent call last):
File "test.py", line 3, in
aapl = iex("AAPL", chartRange='1d')
File "/home/addison/Documents/iex/iexenv/lib/python3.5/site-packages/iexfinance/init.py", line 14, in IexFinance
inst = Share(symbol, **kwargs)
File "/home/addison/Documents/iex/iexenv/lib/python3.5/site-packages/iexfinance/init.py", line 39, in init
self.data_set = self.refresh()
File "/home/addison/Documents/iex/iexenv/lib/python3.5/site-packages/iexfinance/init.py", line 43, in refresh
data = super(Share, self)._fetch()
File "/home/addison/Documents/iex/iexenv/lib/python3.5/site-packages/iexfinance/iexretriever.py", line 215, in _fetch
raise ValueError("Not all endpoints downloaded")
ValueError: Not all endpoints downloaded

lookback

Summary (include Python version)

python 3.6.4
stock.StockReader.get_time_series returns '1m' lookback date regardless of lookback parameter passed (e. g. pass '6m' still returns '1m' data

Date/time of issue

2018/11/03

Expected behavior

data from 2018/06/03 to 2018/11/03 returned

Actual behavior

data from 2018/10/03 to 2018/11/03 returned

IEX Market Data functions not filtering when symbol passed

get_market_tops and get_market_last should restrict their results to a single symbol or list of symbols if they are passed, else return data for all listed symbols. Thus we would expect:

from iexfinance import get_market_tops
len(get_market_tops("AAPL"))

to be 1. But as of now both this function and get_market_last return the entire list (~8600 tickers) each time.

ENH: Pandas support

Currently only JSON is supported. Changing outputFormat to pandas does not do anything.

Some Stocks endpoints return incorrectly

It appears that some endpoints (such as get_earnings are returning incorrectly-formatted data)

from iexfinance import Stock

aapl = Stock("AAPL", output_format='pandas')
aapl.get_earnings()

#                                                                            AAPL
# earnings [{'fiscalPeriod': 'Q4 2017', 'announceTime': '...
# symbol                                                                     AAPL

This is incorrect. In addition, odd behavior is that get_earnings sometimes returns with a symbol index, and sometimes does not. This would cause calls like aapl.get_earnings()["totalDebt"] to fail.

COMPAT: Repair for 5/23/18 IEX Update

Summary (include Python version)

The provider updated a few endpoints on May 23, 2018 (see IEX Docs).

The following will need to be changed and/or updated:

Add /largest-trades endpoint
Add chartLast and changeFromClose parameters to /stock/chart
Add extendedPrice, extendedChange, extendedChangePercent and extendedPriceTime to
/stock/quote
Add yearAgo, yearAgoChangePercent, estimatedChangePercent and symbolId
to /stock/earnings
Updated Attribution section of docs. Simplified attribution by removing second step.
Corrected /stock/chart section of docs. Corrected date format for 1d. Updated return value
coverage.

Date/time of issue

Expected behavior

Actual behavior

CI: Codecov Travis configuration broken

RLS 0.3.0 adds codecov support for code coverage.

As of now codecov does not automatically upload coverage reports when commits are made

TODO

  • Repair .travis.yml configuration
  • Verify code coverage

Should include Current Liabilities

There is a function to pull out current debt but not current liabilities. Current liabilities is a more useful feature for finance people to calculate current ratio.

Please consider adding it in.

Thanks,
Fabelsady

COMPAT: IEX API Provider Updates

IEX made major updates to v1.0 of their api on 1/30/2018, per its CHANGELOG. Would like to add integration to most of these features for RLS 0.3.0 of iexfinance. Thinking of pushing back RLS 0.3.0 to integrate all features cleanly.

Stock

Add endpoints

Update Chart endpoint and historical data

  • Add chartReset, chartSimplify, and chartInterval parameters

Reference Data

Add endpoints

IEX Market Data

- [ ] Add sector and securityType to TOPS

How to multiprocess GET requests

Does this module aim to create a way to make multiprocessing easier? If somebody is trying to run get_historical_data() on thousands of tickers, this would save a lot of time (if you are running four or eight processes at once, that could take time down from 30 seconds to 5 seconds).

Below, I've attached some code that I've made for receiving requests from IEX, but it is not nearly as clean as the format given by the iexfinance module:

import os
import multiprocessing
import requests
iex_url_base = "https://api.iextrading.com/1.0"


def batch_get(batch, url_end):
    """
    Note: This function is only intended to be used for get_pool_response() function in start module,
    but SHOULD NOT be embedded into get_pool_response to avoid pickling problems.
    :param batch: Give a single batch of tickers (ex: 'A,AA,AAPL,...,MSFT')
    :param url_end: Add the query that you will be using  (ex: "&types=dividends&range=5y")
    :return: all the data necessary to make multiple get requests at once
    """
    batch_url = f"{iex_url_base}stock/market/batch?symbols={batch}{url_end}"
    response = requests.get(batch_url).json()
    return response


def get_pool_response(batch_data, url_end, num_processes=os.cpu_count()):

    """
    :param batch_data: List of concatenated symbols -- use get_symbols() and set_batches()
    functions to set batch_data
    :param url_end: Add the query that you will be using  (ex: "&types=dividends&range=5y")
    :param num_processes: Defaults to # of computer cores, but it is possible to have more.
    Increase this as your computer capacity allows for faster multiprocessing.
    :return: Returns all batch GET requests from API for given url_end.
    """
    pool = multiprocessing.Pool(processes=num_processes)
    outputs = []
    outputs.append(pool.starmap(batch_get, [[batch, url_end] for batch in batch_data]))
    pool.close()
    pool.join()
    return outputs

RLS: 0.3.0

0.3.0 will be the first official release of iexfinance. Changes are currently being merged into the master branch with a projected release date of 2/5/2018.

COMPAT: Add support for 8/8/2018 Updates

Summary (include Python version)

  • Add /collections endpoint
  • Add /crypto endpoint
  • Add /today-earnings endpoint
  • Add /upcoming-ipos endpoint
  • Add /today-ipos endpoint
  • Add /sector-performance endpoint

Date/time of issue

Expected behavior

Actual behavior

Pandas dataframe should have a DatetimeIndex instead of just Index

Summary (include Python version)

3.6.6
Pandas dataframe output, specifically the index.

This call returns a dataframe with the date as an 'Index'

In [20]: df = get_historical_data(stock_symbol, start=start, end=end, output_format='pandas')

In [21]: df.info()
<class 'pandas.core.frame.DataFrame'>
Index: 73 entries, 2017-02-09 to 2017-05-24
Data columns (total 5 columns):
open      73 non-null float64
high      73 non-null float64
low       73 non-null float64
close     73 non-null float64
volume    73 non-null int64
dtypes: float64(4), int64(1)
memory usage: 3.4+ KB

I believe the more proper thing to do is return the date as a DatetimeIndex, which means that plotting, sampling, interpolation, etc... all 'do the right thing'

In [22]: df.index = pandas.to_datetime(df.index)

In [23]: df.info()
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 73 entries, 2017-02-09 to 2017-05-24
Data columns (total 5 columns):
open      73 non-null float64
high      73 non-null float64
low       73 non-null float64
close     73 non-null float64
volume    73 non-null int64
dtypes: float64(4), int64(1)
memory usage: 3.4 KB

Date/time of issue

2018-09-04

After installing iex, the tutorial does not work. Please help. I'm coding an important student project.

from iexfinance import IexFinance as iex

aapl = iex("aapl")

JSONDecodeError Traceback (most recent call last)
in ()
1 from iexfinance import Share
----> 2 tsla = Share('TSLA')
3 print(tsla.get_open())
4 print(tsla.get_price())

~\Anaconda3\lib\site-packages\iexfinance_init_.py in init(self, symbol, **kwargs)
37 self.IEX_ENDPOINT_NAME = 'stock/{0}/batch'.format(self.symbol)
38 super(Share, self).init(self.key, self.symbolList, **kwargs)
---> 39 self.data_set = self.refresh()
40
41

~\Anaconda3\lib\site-packages\iexfinance_init_.py in refresh(self)
41
42 def refresh(self):
---> 43 data = super(Share, self)._fetch()
44 self.data_set = data[self.symbol]
45 return data[self.symbol]

~\Anaconda3\lib\site-packages\iexfinance\iexretriever.py in _fetch(self)
178 def _fetch(self):
179 if self._default_options():
--> 180 return self._fetch_default_options()
181 else:
182 data_set = dict.fromkeys(self.symbolList, {})

~\Anaconda3\lib\site-packages\iexfinance\iexretriever.py in _fetch_default_options(self)
164 eps = list(self._ENDPOINTS.keys())
165 query = self._prepare_query(eps)
--> 166 response = self._executeIEXQuery(query)
167 if self._key == "Share":
168 response = {self.symbol : response}

~\Anaconda3\lib\site-packages\iexfinance\iexretriever.py in _executeIEXQuery(cls, url)
129 pass
130 return cls._validate_response(r)
--> 131 return _api_call(cls, url)
132
133 @classmethod

~\Anaconda3\lib\site-packages\iexfinance\iexretriever.py in _api_call(cls, url)
128 except requests.exceptions.RequestException as e:
129 pass
--> 130 return cls._validate_response(r)
131 return _api_call(cls, url)
132

~\Anaconda3\lib\site-packages\iexfinance\iexretriever.py in _validate_response(response)
108 raise IEXSymbolError(self.symbolList[0])
109
--> 110 json_response = response.json()
111 if not json_response:
112 raise IEXQueryError()

~\Anaconda3\lib\site-packages\requests\models.py in json(self, **kwargs)
890 # used.
891 pass
--> 892 return complexjson.loads(self.text, **kwargs)
893
894 @Property

~\Anaconda3\lib\site-packages\simplejson_init_.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, use_decimal, **kw)
516 parse_constant is None and object_pairs_hook is None
517 and not use_decimal and not kw):
--> 518 return _default_decoder.decode(s)
519 if cls is None:
520 cls = JSONDecoder

~\Anaconda3\lib\site-packages\simplejson\decoder.py in decode(self, s, _w, _PY3)
368 if _PY3 and isinstance(s, binary_type):
369 s = s.decode(self.encoding)
--> 370 obj, end = self.raw_decode(s)
371 end = _w(s, end).end()
372 if end != len(s):

~\Anaconda3\lib\site-packages\simplejson\decoder.py in raw_decode(self, s, idx, _w, _PY3)
398 elif ord0 == 0xef and s[idx:idx + 3] == '\xef\xbb\xbf':
399 idx += 3
--> 400 return self.scan_once(s, idx=_w(s, idx).end())

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

In [16]:

from iexfinance import IexFinance as iex
aapl = iex("aapl")

aapl.get_price()

File "", line 3
>>> aapl.get_price()
^
SyntaxError: invalid syntax

In [17]:

from iexfinance import IexFinance as iex
โ€‹
aapl = iex("aapl")


JSONDecodeError Traceback (most recent call last)
in ()
1 from iexfinance import IexFinance as iex
2
----> 3 aapl = iex("aapl")

~\Anaconda3\lib\site-packages\iexfinance_init_.py in IexFinance(symbol, **kwargs)
12 raise ValueError("Please input a symbol or list of symbols")
13 else:
---> 14 inst = Share(symbol, **kwargs)
15 elif type(symbol) is list:
16 if not symbol:

~\Anaconda3\lib\site-packages\iexfinance_init_.py in init(self, symbol, **kwargs)
37 self.IEX_ENDPOINT_NAME = 'stock/{0}/batch'.format(self.symbol)
38 super(Share, self).init(self.key, self.symbolList, **kwargs)
---> 39 self.data_set = self.refresh()
40
41

~\Anaconda3\lib\site-packages\iexfinance_init_.py in refresh(self)
41
42 def refresh(self):
---> 43 data = super(Share, self)._fetch()
44 self.data_set = data[self.symbol]
45 return data[self.symbol]

~\Anaconda3\lib\site-packages\iexfinance\iexretriever.py in _fetch(self)
178 def _fetch(self):
179 if self._default_options():
--> 180 return self._fetch_default_options()
181 else:
182 data_set = dict.fromkeys(self.symbolList, {})

~\Anaconda3\lib\site-packages\iexfinance\iexretriever.py in _fetch_default_options(self)
164 eps = list(self._ENDPOINTS.keys())
165 query = self._prepare_query(eps)
--> 166 response = self._executeIEXQuery(query)
167 if self._key == "Share":
168 response = {self.symbol : response}

~\Anaconda3\lib\site-packages\iexfinance\iexretriever.py in _executeIEXQuery(cls, url)
129 pass
130 return cls._validate_response(r)
--> 131 return _api_call(cls, url)
132
133 @classmethod

~\Anaconda3\lib\site-packages\iexfinance\iexretriever.py in _api_call(cls, url)
128 except requests.exceptions.RequestException as e:
129 pass
--> 130 return cls._validate_response(r)
131 return _api_call(cls, url)
132

~\Anaconda3\lib\site-packages\iexfinance\iexretriever.py in _validate_response(response)
108 raise IEXSymbolError(self.symbolList[0])
109
--> 110 json_response = response.json()
111 if not json_response:
112 raise IEXQueryError()

~\Anaconda3\lib\site-packages\requests\models.py in json(self, **kwargs)
890 # used.
891 pass
--> 892 return complexjson.loads(self.text, **kwargs)
893
894 @Property

~\Anaconda3\lib\site-packages\simplejson_init_.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, use_decimal, **kw)
516 parse_constant is None and object_pairs_hook is None
517 and not use_decimal and not kw):
--> 518 return _default_decoder.decode(s)
519 if cls is None:
520 cls = JSONDecoder

~\Anaconda3\lib\site-packages\simplejson\decoder.py in decode(self, s, _w, _PY3)
368 if _PY3 and isinstance(s, binary_type):
369 s = s.decode(self.encoding)
--> 370 obj, end = self.raw_decode(s)
371 end = _w(s, end).end()
372 if end != len(s):

~\Anaconda3\lib\site-packages\simplejson\decoder.py in raw_decode(self, s, idx, _w, _PY3)
398 elif ord0 == 0xef and s[idx:idx + 3] == '\xef\xbb\xbf':
399 idx += 3
--> 400 return self.scan_once(s, idx=_w(s, idx).end())

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Stock() top-level function restricts batches to lot size 99 rather than 100

Very minor and quick fix, but in __init__.py, Stock() throws a ValueError when a lot size of 100 is used, even though the API is capable of handling it. I've made this change myself on a forked version and can confirm that it works.

Line 40:
elif isinstance(symbols, list) and 0 < len(symbols) < 100:
should be:
elif isinstance(symbols, list) and 0 < len(symbols) <= 100:

DOC: Verify and repair all hyperlinks

Migration from .md/mkdocs to .rst/sphinx has left some hyperlinks broken.

TODO

  • Verify all hyperlinks when docs structure completed.
  • Convert hyperlinks to relative links when possible

Get Financials Endpoint Does Not Handle Blank Values

Summary (include Python version)

a = Stock('AADR')
a.get_financials()
Traceback (most recent call last):
File "", line 1, in
File "/Users/ericxiao/.local/share/virtualenvs/bloom-Eg4XHhZg/lib/python3.6/site-packages/iexfinance/stock.py", line 32, in _format_wrapper
response = func(self, *args, **kwargs)
File "/Users/ericxiao/.local/share/virtualenvs/bloom-Eg4XHhZg/lib/python3.6/site-packages/iexfinance/stock.py", line 391, in get_financials
for symbol in list(data)}
File "/Users/ericxiao/.local/share/virtualenvs/bloom-Eg4XHhZg/lib/python3.6/site-packages/iexfinance/stock.py", line 391, in
for symbol in list(data)}
KeyError: 'financials'

Date/time of issue

Expected behavior

It should handle empty state for finances more gracefully and return an empty dictionary

Actual behavior

On bulk entry for get_financials(), it breaks and shows the KeyError exception

get_dividends not implemented ?

Summary (include Python version)

Is get_dividends not implemented yet ? Python 3

Date/time of issue

09/19/2018 12:57 pm

Expected behavior

Docs says get_dividends is a top level function that can be used

Actual behavior

When I add "from iexfinance import get_dividends as div" to a script , I get an error:
ImportError: cannot import name 'get_dividends'

Unable to catch error

Summary (include Python version)

I am using the library to develop a component for Home Assistant. When I try to fetch a quote with get_quote() for a non-existing symbol (for example 'AAA'), an error is raised (see below). A try/except does not catch this.

Date/time of issue

Expected behavior

sample code:

        from iexfinance import Stock
        symbol = 'AAA'
        stock = Stock(symbol)
        try:
            quote = stock.get_quote()
            _LOGGER.debug("Received new values for symbol %s", symbol)
        except ValueError as error:
            _LOGGER.error(
                "Unknown symbol '%s'", self._symbol)

Actual behavior

Traceback (most recent call last):
  File "/usr/local/Cellar/python3/3.6.4_2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/homeassistant/helpers/entity_platform.py", line 248, in _async_add_entity
    await entity.async_device_update(warning=False)
  File "/usr/local/Cellar/python3/3.6.4_2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/homeassistant/helpers/entity.py", line 320, in async_device_update
    yield from self.hass.async_add_job(self.update)
  File "/usr/local/Cellar/python3/3.6.4_2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/concurrent/futures/thread.py", line 56, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/Users/robert/.homeassistant/custom_components/sensor/iex.py", line 136, in update
    self.values = self._stock.get_quote()
  File "/Users/robert/.homeassistant/deps/lib/python/site-packages/iexfinance/stock.py", line 32, in _format_wrapper
    response = func(self, *args, **kwargs)
  File "/Users/robert/.homeassistant/deps/lib/python/site-packages/iexfinance/stock.py", line 521, in get_quote
    data = self._get_endpoint("quote", kwargs)
  File "/Users/robert/.homeassistant/deps/lib/python/site-packages/iexfinance/stock.py", line 208, in _get_endpoint
    raise IEXSymbolError(symbol)
iexfinance.utils.exceptions.IEXSymbolError: Symbol AAA not found.

Unexpected output format for historical data

Summary (include Python version)

When Pandas is selected as output format for get_historical_data, Series is returned instead of DataFrame when one symbol is used

Date/time of issue

Expected behavior

Actual behavior

Add default date parameters

In similar style to Pandas Datareader's _sanitize_dates, we should probably have the date period for functions such as get_historical_data and get_stats_daily default to somthing like 1/1/2015 for start and today for end. This would allow null start and end parameters to make valid requests for those methods...docs will also need to indicate the same.

Still thinking about this.

Expected close test fails

self = <tests.test_stock.TestHistorical object at 0x7fda905e40f0>

def test_single_historical_json(self):

    f = get_historical_data("AAPL", self.good_start, self.good_end)
    assert isinstance(f, dict)
    assert len(f["AAPL"]) == 73

    expected1 = f["AAPL"]["2017-02-09"]
  assert expected1["close"] == 132.42

E assert 130.3577 == 132.42

I was making sure I had everything installed properly, but ran into this test failure. As I started to chase down the fail, I get another fail as the historical high seems to be different. I was ok with the close, as it could be adjusted close, but when high was different, I started to question what it 'should' be.

-- My environment:
https://github.com/akbennett/iex-docker

Package requirements - Pandas ==0.21.0

Summary (include Python version)

Python 3.6 - Is there a huge need for Pandas version 0.21.0? Could you write the requirements to be pandas>=0.21.0 vice pandas==0.21.0?

Date/time of issue

2018-07-12

get_historical_data - key error 'date'

Summary (include Python version)

Python 3.6.4

Date/time of issue

25th September 2018

Expected behavior

to get empty dictionary or empty dataframe

Actual behavior

When calling get_historical_data for symbol 'ZNWAA' I get an keyerror 'date'. This happens on setting index od 'Date'. As long as IEX do not provide any data for this symbol the index can not be set on empty dataframe.

CI: Ensure correct Python version support

Currently in setup.py:

 'Programming Language :: Python',
 'Programming Language :: Python :: 2',
 'Programming Language :: Python :: 2.6',
 'Programming Language :: Python :: 2.7',
 'Programming Language :: Python :: 3',
 'Programming Language :: Python :: 3.3',
 'Programming Language :: Python :: 3.4',
 'Programming Language :: Python :: 3.5',

Travis only runs tests for Python 3.5, per travis.yml

TODO*

  • Update TravisCI to test all listed compatible Python versions
    • If problems arise with tests, patch compatibility issues if able, else remove version from compat list

Error: TimeoutError

I keep getting a TimeoutError for everything I try. Not entirely sure what I'm doing wrong here. The code for this has worked sporadically before but it all seems very intermittent.

from iexfinance import Stock
s = Stock("AAPL")
print(s.get_book())

Here are the error details:

Traceback (most recent call last):
File "C:\Python3\lib\site-packages\urllib3\connection.py", line 141, in _new_conn
(self.host, self.port), self.timeout, **extra_kw)
File "C:\Python3\lib\site-packages\urllib3\util\connection.py", line 83, in create_connection
raise err
File "C:\Python3\lib\site-packages\urllib3\util\connection.py", line 73, in create_connection
sock.connect(sa)
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Python3\lib\site-packages\urllib3\connectionpool.py", line 601, in urlopen
chunked=chunked)
File "C:\Python3\lib\site-packages\urllib3\connectionpool.py", line 346, in _make_request
self._validate_conn(conn)
File "C:\Python3\lib\site-packages\urllib3\connectionpool.py", line 850, in _validate_conn
conn.connect()
File "C:\Python3\lib\site-packages\urllib3\connection.py", line 284, in connect
conn = self._new_conn()
File "C:\Python3\lib\site-packages\urllib3\connection.py", line 150, in _new_conn
self, "Failed to establish a new connection: %s" % e)
urllib3.exceptions.NewConnectionError: <urllib3.connection.VerifiedHTTPSConnection object at 0x070F8AD0>: Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Python3\lib\site-packages\requests\adapters.py", line 440, in send
timeout=timeout
File "C:\Python3\lib\site-packages\urllib3\connectionpool.py", line 639, in urlopen
_stacktrace=sys.exc_info()[2])
File "C:\Python3\lib\site-packages\urllib3\util\retry.py", line 388, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='api.iextrading.com', port=443): Max retries exceeded with url: /1.0/stock/market/batch?symbols=AAPL&types=book (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x070F8AD0>: Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond',))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:/Users/PycharmProjects/run_main.py", line 90, in
print(s.get_book())
File "C:\Python3\lib\site-packages\iexfinance\stock.py", line 32, in _format_wrapper
response = func(self, *args, **kwargs)
File "C:\Python3\lib\site-packages\iexfinance\stock.py", line 270, in get_book
data = self._get_endpoint("book", kwargs)
File "C:\Python3\lib\site-packages\iexfinance\stock.py", line 205, in _get_endpoint
data = self.fetch()
File "C:\Python3\lib\site-packages\iexfinance\base.py", line 141, in fetch
return self._execute_iex_query(url)
File "C:\Python3\lib\site-packages\iexfinance\base.py", line 111, in _execute_iex_query
response = self.session.get(url=url)
File "C:\Python3\lib\site-packages\requests\sessions.py", line 521, in get
return self.request('GET', url, **kwargs)
File "C:\Python3\lib\site-packages\requests\sessions.py", line 508, in request
resp = self.send(prep, **send_kwargs)
File "C:\Python3\lib\site-packages\requests\sessions.py", line 618, in send
r = adapter.send(request, **kwargs)
File "C:\Python3\lib\site-packages\requests\adapters.py", line 508, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.iextrading.com', port=443): Max retries exceeded with url: /1.0/stock/market/batch?symbols=AAPL&types=book (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x070F8AD0>: Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond',))

Process finished with exit code 1

Please change the default requests for the batch symbol

Hi there,

Can you please change the batch request to not request 10 different api endpoints by default and instead make the user specify which requests they are making?

We are seeing lots of users leave the defaults and add thousands of symbols which isnt ideal from our end. In addition, many of the endpoints being requested return duplicate data that is returned in other ones in the same request. Thanks.

Symbols with non-alphanumeric characters fail

The following request will fail:

from iexfinance imort Stock

aig = Stock("aig+")

# iexfinance.utils.exceptions.IEXSymbolError: Symbol AIG+ not found.

per the IEX docs:

Be sure to url-encode the values you pass to your parameter.
(i.e. ?symbols=AIG+ encoded is ?symbols=AIG%2b.)

since we are not doing so now, we are essentially passing:

symbols=AIG+

which will not work. Need to url-encode all symbol names to force percent-encodings of non-alphanum characters.

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.