I am pulling some financial data from the IEX Cloud API. Since it is a paid API w/ rate limits, I would like to do this as efficiently as possible (i.e., as few calls as possible). Given that the
tickers list is likely to have thousands of indexes (oftentimes with duplicates), is there a better/more efficient way than what I'm currently doing?
(Feel free to use the token in the code, as there is no limit to the number of API calls that you can make to sandboxed data.)
import os from iexfinance.stocks import Stock import iexfinance import pandas as pd # Set IEX Finance API Token (Test) os.environ['IEX_API_VERSION'] = 'iexcloud-sandbox' os.environ['IEX_TOKEN'] = 'Tsk_5798c0ab124d49639bb1575b322841c4' # List of ticker symbols tickers = ['MSFT', 'V', 'ERROR', 'INVALID', 'BRK.B', 'MSFT'] # Create output Dataframe output_df = pd.DataFrame(columns=['Net Income', 'Book Value']) # Loop through companies in tickers list for ticker in tickers: # Call IEX Cloud API, and output to Dataframe try: company = Stock(ticker, output_format='pandas') try: # Get income from last 4 quarters, sum it, and store to temp Dataframe df_income = company.get_income_statement(period="quarter", last='4') df_income['TTM'] = df_income.sum(axis=1) income_ttm = int(df_income.loc['netIncome', 'TTM']) # Get book value from most recent quarter, and store to temp Dataframe df_book = company.get_balance_sheet(period="quarter") book_value = int(df_book.loc['shareholderEquity']) # If IEX Cloud errors, make stats = 0 except (iexfinance.utils.exceptions.IEXQueryError, TypeError, KeyError) as e: book_value = 0 income_ttm = 0 # Store stats to output Dataframe output_df.loc[ticker] = [income_ttm, book_value] except ValueError: pass print(output_df)