pythonpython-3.xfinanceyahoo-financeyahoo

How to reorder Data from yahoo finance(Python)?


I'm trying to write down a python script that allow me to get some items of financial statement from Yahoo.I've tried with yahoofinancials library, but I can get only an entire page of data: For istance,with this code:

from yahoofinancials import YahooFinancials
 yahoo_financials = YahooFinancials('AAPL')
 print(yahoo_financials.get_financial_stmts('annual', 'balance'))

I will get this:

{
    "balanceSheetHistory": {
        "AAPL": [
            {
                "2016-09-24": {
                    "otherCurrentLiab": 8080000000,
                    "otherCurrentAssets": 8283000000,
                    "goodWill": 5414000000,
                    "shortTermInvestments": 46671000000,
                    "longTermInvestments": 170430000000,
                    "cash": 20484000000,
                    "netTangibleAssets": 119629000000,
                    "totalAssets": 321686000000,
                    "otherLiab": 36074000000,
                    "totalStockholderEquity": 128249000000,
                    "inventory": 2132000000,
                    "retainedEarnings": 96364000000,
                    "intangibleAssets": 3206000000,
                    "totalCurrentAssets": 106869000000,
                    "otherStockholderEquity": 634000000,
                    "shortLongTermDebt": 11605000000,
                    "propertyPlantEquipment": 27010000000,
                    "deferredLongTermLiab": 2930000000,
                    "netReceivables": 29299000000,
                    "otherAssets": 8757000000,
                    "longTermDebt": 75427000000,
                    "totalLiab": 193437000000,
                    "commonStock": 31251000000,
                    "accountsPayable": 59321000000,
                    "totalCurrentLiabilities": 79006000000
                }
            }
        ]
    }
}

I want to get every single element, such as "cash" and put it in a variable or an array with all these data,in order to get the single number. So,for example, if I would get "cash",I would have a variable or an array/list that allow me to get the number(in this case 20484000000,for cash). I hope I’ve made myself clear. Someone knows how to do it?Thank you.


Solution

  • Since the output is in json format we must work with json.

    from yahoofinancials import YahooFinancials
    import json
    yahoo_financials = YahooFinancials('AAPL')
    w = yahoo_financials.get_financial_stmts('annual', 'balance')
    print(w["balanceSheetHistory"]["AAPL"][2]['2019-09-28']['totalLiab'])
    

    change 'totalLiab' to get desired data and to change '2019-09-28' you must also change [2].