Why does my for loop return "list index out of range" after the first

Viewed 63

I'm somewhat new to programming and would like to use python to pull the expense ratios associated with a list of traded funds in order to compare costs.

import pandas as pd
import numpy as np
import yahoo_fin.stock_info as si
import matplotlib.pyplot as plt
import pandas_datareader as web

I want to feed the loop a list of funds, MFlist1, and then initialize my list of expense ratios by adding "tickers" and "expense ratios in the 0 index. The si.get_quote_table returns a dictionary of several values. I want to get the value for "Expense Ratio (net)"

MFlist1 = ["XLK", "XLT", "XLI"]
expense_ratios_list =[["Ticker", "Expense Ratio"]]

for x in range(len(MFlist1)):
    temp_dic = si.get_quote_table(MFlist1[x])
    expense_ratios_list.append([MFlist1[x] , temp_dic.get('Expense Ratio (net)')])    
    print(expense_ratios_list)

print(expense_ratio_list)    

When I run the code above, it returns

[['Ticker', 'Expense Ratio'], [0, '0.10%']]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-31-94ce584e3a93> in <module>
      2 
      3 for x in range(len(MFlist1)):
----> 4     temp_dic = si.get_quote_table(MFlist1[x])
      5     expense_ratios_list.append([MFlist1[x] , temp_dic.get('Expense Ratio (net)')])
      6     print(expense_ratios_list)

~\anaconda3\lib\site-packages\yahoo_fin\stock_info.py in get_quote_table(ticker, dict_result, headers)
    293     tables = pd.read_html(requests.get(site, headers=headers).text)
    294 
--> 295     data = tables[0].append(tables[1])
    296 
    297     data.columns = ["attribute" , "value"]

IndexError: list index out of range

I'm not sure why it works for the first element in MFlist1, but then errors out.

0 Answers
Related