Skip to content
Advertisement

Yahoo Finance API yf.Ticker(ticker).info to CSV problem

When I’m using

ticker = "MSFT"
stock = yf.Ticker('MSFT').history('5y')

stock 

I get a dataframe in response

When I use

ticker = "MSFT"
stock_info = yf.Ticker(ticker).info
stock_info 

I’m receiving a list from Yahoo finance API. How can I transform this list to a Dataframe in Pandas? So I could use

stock.to_csv(folder + ticker + ".csv") => Working with 'history' data

stock_info.to_csv(folder + ticker + ".csv") => Not working with 'info' data because it's a list not a dataframe.

How can I save yf.Ticker(ticker).info data to a csv?

enter image description here

ticker = "MSFT"
stock_info = yf.Ticker(ticker).info
stock_info
stock_info.to_csv(folder + ticker + ".csv")

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In [158], line 4
      2 stock_info = yf.Ticker(ticker).info
      3 stock_info
----> 4 stock_info.to_csv(folder + ticker + ".csv")

AttributeError: 'dict' object has no attribute 'to_csv'


ticker = "MSFT"
stock_info = yf.Ticker(ticker).info
stock_info

{'zip': '98052-6399',
 'sector': 'Technology',
 'fullTimeEmployees': 221000,
 'longBusinessSummary': 'Microsoft Corporation develops, licenses, and supports software, services, devices, and solutions worldwide. The company operates in three segments: Productivity and Business Processes, Intelligent Cloud, and More Personal Computing. The Productivity and Business Processes segment offers Office, Exchange, SharePoint, Microsoft Teams, Office 365 Security and Compliance, Microsoft Viva, and Skype for Business; Skype, Outlook.com, OneDrive, and LinkedIn; and Dynamics 365, a set of cloud-based and on-premises business solutions for organizations and enterprise divisions. The Intelligent Cloud segment licenses SQL, Windows Servers, Visual Studio, System Center, and related Client Access Licenses; GitHub that provides a collaboration platform and code hosting service for developers; Nuance provides healthcare and enterprise AI solutions; and Azure, a cloud platform. It also offers enterprise support, Microsoft consulting, and nuance professional services to assist customers in developing, deploying, and managing Microsoft server and desktop solutions; and training and certification on Microsoft products. The More Personal Computing segment provides Windows original equipment manufacturer (OEM) licensing and other non-volume licensing of the Windows operating system; Windows Commercial, such as volume licensing of the Windows operating system, Windows cloud services, and other Windows commercial offerings; patent licensing; and Windows Internet of Things. It also offers Surface, PC accessories, PCs, tablets, gaming and entertainment consoles, and other devices; Gaming, including Xbox hardware, and Xbox content and services; video games and third-party video game royalties; and Search, including Bing and Microsoft advertising. The company sells its products through OEMs, distributors, and resellers; and directly through digital marketplaces, online stores, and retail stores. Microsoft Corporation was founded in 1975 and is headquartered in Redmond, Washington.',
 'city': 'Redmond',
 'phone': '425 882 8080',
 'state': 'WA',
 'country': 'United States',
 'companyOfficers': [],
 'website': 'https://www.microsoft.com',
 'maxAge': 1,
 'address1': 'One Microsoft Way',
 'fax': '425 706 7329',
 'industry': 'Software—Infrastructure',
 'ebitdaMargins': 0.48672,
 'profitMargins': 0.34366,
 'grossMargins': 0.6826,
 'operatingCashflow': 87693000704,
 'revenueGrowth': 0.106,
 'operatingMargins': 0.41691002,
 'ebitda': 98841001984,
 'targetLowPrice': 255,
 'recommendationKey': 'buy',
 'grossProfits': 135620000000,
 'freeCashflow': 46155874304,
...
 'dayHigh': 236.6,
 'coinMarketCapLink': None,
 'regularMarketPrice': 235.87,
 'preMarketPrice': None,
 'logo_url': 'https://logo.clearbit.com/microsoft.com'}

I don’t understand how I can change this list into something I can write to CSV

{'zip': '98052-6399',
 'sector': 'Technology',
 'fullTimeEmployees': 221000,
 'longBusinessSummary': 'Microsoft Corporation develops, licenses, and supports software, services, devices, and solutions worldwide. The company operates in three segments: Productivity and Business Processes, Intelligent Cloud, and More Personal Computing. The Productivity and Business Processes segment offers Office, Exchange, SharePoint, Microsoft Teams, Office 365 Security and Compliance, Microsoft Viva, and Skype for Business; Skype, Outlook.com, OneDrive, and LinkedIn; and Dynamics 365, a set of cloud-based and on-premises business solutions for organizations and enterprise divisions. The Intelligent Cloud segment licenses SQL, Windows Servers, Visual Studio, System Center, and related Client Access Licenses; GitHub that provides a collaboration platform and code hosting service for developers; Nuance provides healthcare and enterprise AI solutions; and Azure, a cloud platform. It also offers enterprise support, Microsoft consulting, and nuance professional services to assist customers in developing, deploying, and managing Microsoft server and desktop solutions; and training and certification on Microsoft products. The More Personal Computing segment provides Windows original equipment manufacturer (OEM) licensing and other non-volume licensing of the Windows operating system; Windows Commercial, such as volume licensing of the Windows operating system, Windows cloud services, and other Windows commercial offerings; patent licensing; and Windows Internet of Things. It also offers Surface, PC accessories, PCs, tablets, gaming and entertainment consoles, and other devices; Gaming, including Xbox hardware, and Xbox content and services; video games and third-party video game royalties; and Search, including Bing and Microsoft advertising. The company sells its products through OEMs, distributors, and resellers; and directly through digital marketplaces, online stores, and retail stores. Microsoft Corporation was founded in 1975 and is headquartered in Redmond, Washington.',
 'city': 'Redmond',
 'phone': '425 882 8080',
 'state': 'WA',
 'country': 'United States',
 'companyOfficers': [],
 'website': 'https://www.microsoft.com',
 'maxAge': 1,
 'address1': 'One Microsoft Way',
 'fax': '425 706 7329',
 'industry': 'Software—Infrastructure',
 'ebitdaMargins': 0.48672,
 'profitMargins': 0.34366,
 'grossMargins': 0.6826,
 'operatingCashflow': 87693000704,
 'revenueGrowth': 0.106,
 'operatingMargins': 0.41691002,
 'ebitda': 98841001984,
 'targetLowPrice': 255,
 'recommendationKey': 'buy',
 'grossProfits': 135620000000,
 'freeCashflow': 46155874304,
 'targetMedianPrice': 296,
 'currentPrice': 235.87,
 'earningsGrowth': -0.133,
 'currentRatio': 1.84,
 'returnOnAssets': 0.15223,
 'numberOfAnalystOpinions': 45,
 'targetMeanPrice': 307.58,
 'debtToEquity': 44.442,
 'returnOnEquity': 0.42875,
 'targetHighPrice': 411,
 'totalCash': 107244003328,
 'totalDebt': 77136003072,
 'totalRevenue': 203074994176,
 'totalCashPerShare': 14.387,
 'financialCurrency': 'USD',
 'revenuePerShare': 27.142,
 'quickRatio': 1.585,
 'recommendationMean': 1.7,
 'exchange': 'NMS',
 'shortName': 'Microsoft Corporation',
 'longName': 'Microsoft Corporation',
 'exchangeTimezoneName': 'America/New_York',
 'exchangeTimezoneShortName': 'EDT',
 'isEsgPopulated': False,
 'gmtOffSetMilliseconds': '-14400000',
 'quoteType': 'EQUITY',
 'symbol': 'MSFT',
 'messageBoardId': 'finmb_21835',
 'market': 'us_market',
 'annualHoldingsTurnover': None,
 'enterpriseToRevenue': 8.51,
 'beta3Year': None,
 'enterpriseToEbitda': 17.484,
 '52WeekChange': -0.2838753,
 'morningStarRiskRating': None,
 'forwardEps': 11.35,
 'revenueQuarterlyGrowth': None,
 'sharesOutstanding': 7454470144,
 'fundInceptionDate': None,
 'annualReportExpenseRatio': None,
 'totalAssets': None,
 'bookValue': 23.276,
 'sharesShort': 38213792,
 'sharesPercentSharesOut': 0.0050999997,
 'fundFamily': None,
 'lastFiscalYearEnd': 1656547200,
 'heldPercentInstitutions': 0.71777,
 'netIncomeToCommon': 69788999680,
 'trailingEps': 9.29,
 'lastDividendValue': 0.62,
 'SandP52WeekChange': -0.1544562,
 'priceToBook': 10.133615,
 'heldPercentInsiders': 0.00071000005,
 'nextFiscalYearEnd': 1719705600,
 'yield': None,
 'mostRecentQuarter': 1664496000,
 'shortRatio': 1.28,
 'sharesShortPreviousMonthDate': 1663200000,
 'floatShares': 7399682766,
 'beta': 0.960206,
 'enterpriseValue': 1728178552832,
 'priceHint': 2,
 'threeYearAverageReturn': None,
 'lastSplitDate': 1045526400,
 'lastSplitFactor': '2:1',
 'legalType': None,
 'lastDividendDate': 1660694400,
 'morningStarOverallRating': None,
 'earningsQuarterlyGrowth': -0.144,
 'priceToSalesTrailing12Months': 8.658308,
 'dateShortInterest': 1665705600,
 'pegRatio': 1.8,
 'ytdReturn': None,
 'forwardPE': 20.781496,
 'lastCapGain': None,
 'shortPercentOfFloat': 0.0050999997,
 'sharesShortPriorMonth': 42967330,
 'impliedSharesOutstanding': 0,
 'category': None,
 'fiveYearAverageReturn': None,
 'previousClose': 226.75,
 'regularMarketOpen': 226.24,
 'twoHundredDayAverage': 272.84604,
 'trailingAnnualDividendYield': 0.0112017635,
 'payoutRatio': 0.26700002,
 'volume24Hr': None,
 'regularMarketDayHigh': 236.6,
 'navPrice': None,
 'averageDailyVolume10Day': 34581880,
 'regularMarketPreviousClose': 226.75,
 'fiftyDayAverage': 248.0068,
 'trailingAnnualDividendRate': 2.54,
 'open': 226.24,
 'toCurrency': None,
 'averageVolume10days': 34581880,
 'expireDate': None,
 'algorithm': None,
 'dividendRate': 2.72,
 'exDividendDate': 1668556800,
 'circulatingSupply': None,
 'startDate': None,
 'regularMarketDayLow': 226.06,
 'currency': 'USD',
 'trailingPE': 25.389666,
 'regularMarketVolume': 40593443,
 'lastMarket': None,
 'maxSupply': None,
 'openInterest': None,
 'marketCap': 1758285791232,
 'volumeAllCurrencies': None,
 'strikePrice': None,
 'averageVolume': 26490917,
 'dayLow': 226.06,
 'ask': 235.7,
 'askSize': 1200,
 'volume': 40593443,
 'fiftyTwoWeekHigh': 349.67,
 'fromCurrency': None,
 'fiveYearAvgDividendYield': 1.2,
 'fiftyTwoWeekLow': 219.13,
 'bid': 235.5,
 'tradeable': False,
 'dividendYield': 0.0115,
 'bidSize': 900,
 'dayHigh': 236.6,
 'coinMarketCapLink': None,
 'regularMarketPrice': 235.87,
 'preMarketPrice': None,
 'logo_url': 'https://logo.clearbit.com/microsoft.com'}

This is the full response from Yahoo Finance API from which I only need ‘freeCashflow’, ‘industry’, ‘debtToEquity, ‘returnOnEquity’, ‘sharesOutstanding’ to CSV

ticker = "MSFT"
stock_info = yf.Ticker(ticker).info
stock_info

df = pd.DataFrame(stock_info)
df

This code returns an empty df but I can see the columns. 154 columns but 0 rows??? I should have 1 row of data.

enter image description here

Advertisement

Answer

I fixed it using

        stock_info
        df = pd.DataFrame.from_dict(stock_info,orient='index').T

Thanks anyway :-)

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement