首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >雅虎财经API yf.Ticker(ticker).info to CSV问题

雅虎财经API yf.Ticker(ticker).info to CSV问题
EN

Stack Overflow用户
提问于 2022-10-30 18:07:06
回答 2查看 55关注 0票数 0

当我用

代码语言:javascript
复制
ticker = "MSFT"
stock = yf.Ticker('MSFT').history('5y')

stock 

我得到了一个数据作为回应

当我用

代码语言:javascript
复制
ticker = "MSFT"
stock_info = yf.Ticker(ticker).info
stock_info 

我收到了一个来自雅虎财经API的列表。如何将此列表转换为Pandas中的Dataframe?所以我可以用

代码语言:javascript
复制
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.

如何将yf.Ticker(代码机).info数据保存到csv?

代码语言:javascript
复制
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'}

我不明白我怎么能把这个列表变成我能写给CSV的东西

代码语言:javascript
复制
{'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'}

这是来自Yahoo的完整响应,我只需要使用“freeCashflow”、“行业”、“debtToEquity”、“返回industry”、“sharesOutstanding”到CSV。

代码语言:javascript
复制
ticker = "MSFT"
stock_info = yf.Ticker(ticker).info
stock_info

df = pd.DataFrame(stock_info)
df

这段代码返回一个空的df,但我可以看到列。154列,0行??我应该有一排数据。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-10-31 09:33:33

我把它修好了

代码语言:javascript
复制
        stock_info
        df = pd.DataFrame.from_dict(stock_info,orient='index').T

无论如何,谢谢-)

票数 0
EN

Stack Overflow用户

发布于 2022-10-30 23:39:33

反应是一个小块,所以把它放在方括号里,然后把它传递给熊猫。

代码语言:javascript
复制
pd.DataFrame([stock_info]).to_csv("/path/to/write/MSFT.csv", index=False)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74255549

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档