Search code examples
pythonexcelpandasstock

Says I need an index for finvizfinance, but when I add an index = zero it says my collection is zero?


I'm trying to import stock information into an excel sheet via the finvizfinance library using Python. The dataframe correction from pandas is not correctly giving a format that could be put into excel. What is going on? Do I need to set the index to a list that is equal to all outputs of the rows from the finvizlibrary (e.g. 'Company', 'Sector', etc)? Any help would be appreciated.

When I simply print the stock_fundament I get something like the following...

{'Company': 'Tesla, Inc.', 'Sector': 'Consumer Cyclical', 'Industry': 'Auto Manufacturers', ...,'SMA20': '-11.37%', 'SMA50': '4.62%', 'SMA200': '-20.45%', 'Volume': '167,302,066', 'Change': '0.60%'}

Empty DataFrame Columns: [a, b, c, d, e, f, g, h, i, j] Index: []

from finvizfinance.quote import finvizfinance
import pandas as pd
 
stock = finvizfinance('tsla')
stock_fundament = stock.ticker_fundament()
 
 
# Create a Pandas dataframe from the data.
df = pd.DataFrame(stock_fundament, index=0, columns=['a','b','c','d','e','f','g','h','i','j'])
print(stock_fundament)
print(df)

#df = df[list(df.columns[~df.columns.duplicated()])]         
#This was used to delete potential duplicate columns

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter(r'C:\Users\ncwes\AppData\Local\Programs\Python\Python310\pandas_simple.xlsx')
 
# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')
 
# Close the Pandas Excel writer and output the Excel file.
writer.close()


Solution

  • You can use pd.json_normalize(stock_fundament) to read in correctly.

    df = pd.DataFrame(pd.json_normalize(stock_fundament))
    
    print(df)
    
           Company             Sector  ...       Volume Change
    0  Tesla, Inc.  Consumer Cyclical  ...  142,799,036  5.03%