Search code examples
pythonjsonyahoo-finance

Error when reading yahoofinancials JSON: Unexpected character found when decoding 'NaN'


I am trying to read a json, which I get from the python package 'yahoofinancials' (it pulls the data from Yahoo Finance):

import numpy as np
import pandas as pd
from yahoofinancials import YahooFinancials

yahoo_financials = YahooFinancials(ticker)
cash_statements = yahoo_financials.get_financial_stmts('annual', 'income')
cash_statements
pd.read_json(str(cash_statements).replace("'", '"'), orient='records')

However I get the error: Unexpected character found when decoding 'NaN'


Solution

  • The problem is this command: str(cash_statements).replace("'", '"').

    You tried to "convert" from a python dictionary to a json string, by replacing single with double quotes, which does not properly work.

    Use the json.dump(cash_statements) function for converting your dictionary object into a json string.

    Updated Code:

    import numpy as np
    import pandas as pd
    from yahoofinancials import YahooFinancials
    
    # ADJUSTMENT 1 - import json
    import json
    
    
    # just some sample data for testing
    ticker = ['AAPL', 'MSFT', 'INTC']
    
    yahoo_financials = YahooFinancials(ticker)
    cash_statements = yahoo_financials.get_financial_stmts('annual', 'income')
    
    # ADJUSTMENT 2 - dict to json
    cash_statements_json = json.dumps(cash_statements)
    pd.read_json(cash_statements_json, orient='records')