addisonlynch / iexfinance

Python SDK for IEX Cloud
https://addisonlynch.github.io/iexfinance
Apache License 2.0
648 stars 136 forks source link

get_historical_data not liking lists of tickers #253

Closed xelcho closed 3 years ago

xelcho commented 3 years ago

Summary (include Python version)

3.8 get_historical_data not processing ticker lists.

Date/time of issue

Dec 30, 2020

Expected behavior

process multiple tickers in a list format

Actual behavior

UnsortedIndexError: 'MultiIndex slicing requires the index to be lexsorted: slicing on levels [1], lexsort depth 0'

addisonlynch commented 3 years ago

Please provide a minimal reproducible code snippet which demonstrates the issue.

xelcho commented 3 years ago

Thx for the quick response! You actually provided me the code :), I used your test code to verify the issue... so: get_historical_data(["AAPL", "TSLA", "MSFT"], start, end ,token="api_key", output_format='pandas')

Daedalos commented 3 years ago

I just hit this issue as well, I believe I found the problem. MultiIndexes in pandas need to be sorted in order to be indexed. The error occurs at line 82 in historical.py:

~/.local/lib/python3.8/site-packages/iexfinance/stocks/historical.py in _format_output(self, out, format) 80 ) 81 idx = pd.IndexSlice ---> 82 result = result.loc[idx[:, self.start : self.end], :] 83 else:

I inserted the following before line 82 and it resolved the error:

81 idx = pd.IndexSlice 82 result.sort_index(inplace=True) 83 result = result.loc[idx[:, self.start : self.end], :]

This does of course mean the returned order will not match the input order, but if I understand pandas docs correctly this is impossible https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html#sorting-a-multiindex https://stackoverflow.com/questions/42412928/multiindex-slicing-doesnt-work-as-expected-error-involving-lexsorted-tuples

Pedler7 commented 3 years ago

I also encountered this issue, it may be less confusing for users to force a .sort() to the symbols list, this is the solution I used, but I implemented in my own code.

wgong commented 3 years ago

@Pedler7 Thank you for the fix

xelcho commented 3 years ago

@Pedler7 Yeah thanks for the fix. For those who are super new to python, here is an example

symbols=['EPV', 'LIVKU', 'QUAL', 'MT', 'IYW'] symbols.sort() df = get_historicaldata(symbols, start, end, token="pk...

should get you started.