【问题标题】:Python yahoo finance data optimitzationPython yahoo finance 数据优化
【发布时间】:2022-11-20 22:04:18
【问题描述】:

我在这里找到了一个非常好的代码来检索我需要的一些数据 (Python yahoo finance error market_cap=int(data.get_quote_yahoo(str)['marketCap']) TypeError: 'int' object is not callable):


tickers=["AAPL","GOOG","RY","HPQ"]

# Get market cap (not really necessary for you)
market_cap_data = web.get_quote_yahoo(tickers)['marketCap']

# Get the P/E ratio directly
pe_data = web.get_quote_yahoo(tickers)['trailingPE']

# print stock and p/e ratio
for stock, pe in zip(tickers, pe_data):
    print(stock, pe)

# More keys that can be used
      ['language', 'region', 'quoteType', 'triggerable', 'quoteSourceName',
       'currency', 'preMarketChange', 'preMarketChangePercent',
       'preMarketTime', 'preMarketPrice', 'regularMarketChange',
       'regularMarketChangePercent', 'regularMarketTime', 'regularMarketPrice',
       'regularMarketDayHigh', 'regularMarketDayRange', 'regularMarketDayLow',
       'regularMarketVolume', 'regularMarketPreviousClose', 'bid', 'ask',
       'bidSize', 'askSize', 'fullExchangeName', 'financialCurrency',
       'regularMarketOpen', 'averageDailyVolume3Month',
       'averageDailyVolume10Day', 'fiftyTwoWeekLowChange',
       'fiftyTwoWeekLowChangePercent', 'fiftyTwoWeekRange',
       'fiftyTwoWeekHighChange', 'fiftyTwoWeekHighChangePercent',
       'fiftyTwoWeekLow', 'fiftyTwoWeekHigh', 'dividendDate',
       'earningsTimestamp', 'earningsTimestampStart', 'earningsTimestampEnd',
       'trailingAnnualDividendRate', 'trailingPE',
       'trailingAnnualDividendYield', 'marketState', 'epsTrailingTwelveMonths',
       'epsForward', 'sharesOutstanding', 'bookValue', 'fiftyDayAverage',
       'fiftyDayAverageChange', 'fiftyDayAverageChangePercent',
       'twoHundredDayAverage', 'twoHundredDayAverageChange',
       'twoHundredDayAverageChangePercent', 'marketCap', 'forwardPE',
       'priceToBook', 'sourceInterval', 'exchangeDataDelayedBy', 'tradeable',
       'firstTradeDateMilliseconds', 'priceHint', 'exchange', 'shortName',
       'longName', 'messageBoardId', 'exchangeTimezoneName',
       'exchangeTimezoneShortName', 'gmtOffSetMilliseconds', 'market',
       'esgPopulated', 'price']

我想检索前面代码末尾的大部分注释字段,但到目前为止我已经这样做了:

import pandas_datareader as web

tickers = ["AAPL", "GOOG", "RY", "SAB.MC"]

market_cap_data = web.get_quote_yahoo(tickers)['marketCap']
pe_data = web.get_quote_yahoo(tickers)['trailingPE']
fiftytwo_low_data = web.get_quote_yahoo(tickers)['fiftyTwoWeekLowChangePercent']


for stock, mcap, pe, fiftytwo_low in zip(tickers, market_cap_data, pe_data, fiftytwo_low_data):
    print(stock, mcap, pe, fiftytwo_low)

显然我可以继续我的蛮力,但你知道有什么方法可以使代码更优雅地检索具有列名的整个字段字符串吗?

['language', 'region', 'quoteType', 'triggerable', 'quoteSourceName',
       'currency', 'preMarketChange', 'preMarketChangePercent',
       'preMarketTime', 'preMarketPrice', 'regularMarketChange',
       'regularMarketChangePercent', 'regularMarketTime', 'regularMarketPrice',
       'regularMarketDayHigh', 'regularMarketDayRange', 'regularMarketDayLow',
       'regularMarketVolume', 'regularMarketPreviousClose', 'bid', 'ask',
       'bidSize', 'askSize', 'fullExchangeName', 'financialCurrency',
       'regularMarketOpen', 'averageDailyVolume3Month',
       'averageDailyVolume10Day', 'fiftyTwoWeekLowChange',
       'fiftyTwoWeekLowChangePercent', 'fiftyTwoWeekRange',
       'fiftyTwoWeekHighChange', 'fiftyTwoWeekHighChangePercent',
       'fiftyTwoWeekLow', 'fiftyTwoWeekHigh', 'dividendDate',
       'earningsTimestamp', 'earningsTimestampStart', 'earningsTimestampEnd',
       'trailingAnnualDividendRate', 'trailingPE',
       'trailingAnnualDividendYield', 'marketState', 'epsTrailingTwelveMonths',
       'epsForward', 'sharesOutstanding', 'bookValue', 'fiftyDayAverage',
       'fiftyDayAverageChange', 'fiftyDayAverageChangePercent',
       'twoHundredDayAverage', 'twoHundredDayAverageChange',
       'twoHundredDayAverageChangePercent', 'marketCap', 'forwardPE',
       'priceToBook', 'sourceInterval', 'exchangeDataDelayedBy', 'tradeable',
       'firstTradeDateMilliseconds', 'priceHint', 'exchange', 'shortName',
       'longName', 'messageBoardId', 'exchangeTimezoneName',
       'exchangeTimezoneShortName', 'gmtOffSetMilliseconds', 'market',
       'esgPopulated', 'price']

谢谢

【问题讨论】:

    标签: python yahoo-finance


    【解决方案1】:

    使用集合,可以得到初始集合中可以被ticker检索到的所有项,使用并集,还可以在一个列表中添加,这样就可以得到所有在集合中有值的项名您要检索的问题。

    import pandas_datareader as web
    import pandas as pd
    
    tickers = ["AAPL", "GOOG", "RY", "SAB.MC"]
    
    names = set()
    for t in tickers:
        market_cap_data = web.get_quote_yahoo(t)
        names |= set(market_cap_data.columns.to_list())
    names
    
    {'ask',
     'askSize',
     'averageAnalystRating',
     'averageDailyVolume10Day',
     'averageDailyVolume3Month',
     'bid',
     'bidSize',
     'bookValue',
     'cryptoTradeable',
     'currency',
     'customPriceAlertConfidence',
     'displayName',
      ...
     'trailingAnnualDividendYield',
     'trailingPE',
     'triggerable',
     'twoHundredDayAverage',
     'twoHundredDayAverageChange',
     'twoHundredDayAverageChangePercent',
     'typeDisp'}
    

    【讨论】:

      【解决方案2】:

      我知道这篇文章很老了,但我现在才看到它。查看“yfinance”库。那里有各种各样的东西!

      import pandas_datareader as web
      import pandas as pd
       
      df = web.DataReader('AAPL', data_source='yahoo', start='2011-01-01', end='2021-01-12')
      df.head()
      
      import yfinance as yf
      aapl = yf.Ticker("AAPL")
      aapl
       
       
      # get stock info
      aapl.info
       
      # get historical market data
      hist = aapl.history(period="max")
       
      # show actions (dividends, splits)
      aapl.actions
       
      # show dividends
      aapl.dividends
       
      # show splits
      aapl.splits
       
      # show financials
      aapl.financials
      aapl.quarterly_financials
       
      # show major holders
      aapl.major_holders
       
      # show institutional holders
      aapl.institutional_holders
       
      # show balance sheet
      aapl.balance_sheet
      aapl.quarterly_balance_sheet
       
      # show cashflow
      aapl.cashflow
      aapl.quarterly_cashflow
       
      # show earnings
      aapl.earnings
      aapl.quarterly_earnings
       
      # show sustainability
      aapl.sustainability
       
      # show analysts recommendations
      aapl.recommendations
       
      # show next event (earnings, etc)
      aapl.calendar
       
      # show ISIN code - *experimental*
      # ISIN = International Securities Identification Number
      aapl.isin
       
      # show options expirations
      aapl.options
       
      # get option chain for specific expiration
      opt = aapl.option_chain('YYYY-MM-DD')
      

      结果:

      {'zip': '95014',
       'sector': 'Technology',
       'fullTimeEmployees': 164000,
       'longBusinessSummary': 'Apple Inc. designs, manufactures, and markets smartphones, personal computers, tablets, wearables, and accessories worldwide. It also sells various related services. In addition, the company offers iPhone, a line of smartphones; Mac, a line of personal computers; iPad, a line of multi-purpose tablets; and wearables, home, and accessories comprising AirPods, Apple TV, Apple Watch, Beats products, and HomePod. Further, it provides AppleCare support and cloud services store services; and operates various platforms, including the App Store that allow customers to discover and download applications and digital content, such as books, music, video, games, and podcasts. Additionally, the company offers various services, such as Apple Arcade, a game subscription service; Apple Fitness+, a personalized fitness service; Apple Music, which offers users a curated listening experience with on-demand radio stations; Apple News+, a subscription news and magazine service; Apple TV+, which offers exclusive original content; Apple Card, a co-branded credit card; and Apple Pay, a cashless payment service, as well as licenses its intellectual property. The company serves consumers, and small and mid-sized businesses; and the education, enterprise, and government markets. It distributes third-party applications for its products through the App Store. The company also sells its products through its retail and online stores, and direct sales force; and third-party cellular network carriers, wholesalers, retailers, and resellers. Apple Inc. was incorporated in 1977 and is headquartered in Cupertino, California.',
       'city': 'Cupertino',
       'phone': '408 996 1010',
       'state': 'CA',
       'country': 'United States',
       'companyOfficers': [],
       'website': 'https://www.apple.com',
       'maxAge': 1,
       'address1': 'One Apple Park Way',
       'industry': 'Consumer Electronics',
       'ebitdaMargins': 0.33105,
       'profitMargins': 0.2531,
       'grossMargins': 0.43310001,
       'operatingCashflow': 122151002112,
       'revenueGrowth': 0.081,
       'operatingMargins': 0.30289,
       'ebitda': 130541002752,
       'targetLowPrice': 122,
       'recommendationKey': 'buy',
       'grossProfits': 170782000000,
       'freeCashflow': 90215251968,
       'targetMedianPrice': 180,
       'currentPrice': 151.29,
       'earningsGrowth': 0.048,
       'currentRatio': 0.879,
       'returnOnAssets': 0.21214001,
       'numberOfAnalystOpinions': 41,
       'targetMeanPrice': 178.15,
       'debtToEquity': 261.446,
       'returnOnEquity': 1.75459,
       'targetHighPrice': 214,
       'totalCash': 48304001024,
       'totalDebt': 132480000000,
       'totalRevenue': 394328014848,
       'totalCashPerShare': 3.036,
       'financialCurrency': 'USD',
       'revenuePerShare': 24.317,
       'quickRatio': 0.709,
       'recommendationMean': 1.9,
       'exchange': 'NMS',
       'shortName': 'Apple Inc.',
       'longName': 'Apple Inc.',
       'exchangeTimezoneName': 'America/New_York',
       'exchangeTimezoneShortName': 'EST',
       'isEsgPopulated': False,
       'gmtOffSetMilliseconds': '-18000000',
       'quoteType': 'EQUITY',
       'symbol': 'AAPL',
       'messageBoardId': 'finmb_24937',
       'market': 'us_market',
       'annualHoldingsTurnover': None,
       'enterpriseToRevenue': 6.317,
       'beta3Year': None,
       'enterpriseToEbitda': 19.081,
       '52WeekChange': -0.06042725,
       'morningStarRiskRating': None,
       'forwardEps': 6.82,
       'revenueQuarterlyGrowth': None,
       'sharesOutstanding': 15908100096,
       'fundInceptionDate': None,
       'annualReportExpenseRatio': None,
       'totalAssets': None,
       'bookValue': 3.178,
       'sharesShort': 103178670,
       'sharesPercentSharesOut': 0.0064999997,
       'fundFamily': None,
       'lastFiscalYearEnd': 1663977600,
       'heldPercentInstitutions': 0.60030997,
       'netIncomeToCommon': 99802996736,
       'trailingEps': 6.11,
       'lastDividendValue': 0.23,
       'SandP52WeekChange': -0.15323704,
       'priceToBook': 47.60541,
       'heldPercentInsiders': 0.00071999995,
       'nextFiscalYearEnd': 1727136000,
       'yield': None,
       'mostRecentQuarter': 1663977600,
       'shortRatio': 1.14,
       'sharesShortPreviousMonthDate': 1664496000,
       'floatShares': 15891414476,
       'beta': 1.246644,
       'enterpriseValue': 2490915094528,
       'priceHint': 2,
       'threeYearAverageReturn': None,
       'lastSplitDate': 1598832000,
       'lastSplitFactor': '4:1',
       'legalType': None,
       'lastDividendDate': 1667520000,
       'morningStarOverallRating': None,
       'earningsQuarterlyGrowth': 0.008,
       'priceToSalesTrailing12Months': 6.103387,
       'dateShortInterest': 1667174400,
       'pegRatio': 2.71,
       'ytdReturn': None,
       'forwardPE': 22.183283,
       'lastCapGain': None,
       'shortPercentOfFloat': 0.0064999997,
       'sharesShortPriorMonth': 103251184,
       'impliedSharesOutstanding': 0,
       'category': None,
       'fiveYearAverageReturn': None,
       'previousClose': 150.72,
       'regularMarketOpen': 152.305,
       'twoHundredDayAverage': 155.0841,
       'trailingAnnualDividendYield': 0.005971337,
       'payoutRatio': 0.14729999,
       'volume24Hr': None,
       'regularMarketDayHigh': 152.57,
       'navPrice': None,
       'averageDailyVolume10Day': 84360340,
       'regularMarketPreviousClose': 150.72,
       'fiftyDayAverage': 147.0834,
       'trailingAnnualDividendRate': 0.9,
       'open': 152.305,
       'toCurrency': None,
       'averageVolume10days': 84360340,
       'expireDate': None,
       'algorithm': None,
       'dividendRate': 0.92,
       'exDividendDate': 1667520000,
       'circulatingSupply': None,
       'startDate': None,
       'regularMarketDayLow': 149.97,
       'currency': 'USD',
       'trailingPE': 24.761045,
       'regularMarketVolume': 74496725,
       'lastMarket': None,
       'maxSupply': None,
       'openInterest': None,
       'marketCap': 2406736461824,
       'volumeAllCurrencies': None,
       'strikePrice': None,
       'averageVolume': 89929545,
       'dayLow': 149.97,
       'ask': 150.95,
       'askSize': 1000,
       'volume': 74496725,
       'fiftyTwoWeekHigh': 182.94,
       'fromCurrency': None,
       'fiveYearAvgDividendYield': 1,
       'fiftyTwoWeekLow': 129.04,
       'bid': 150.82,
       'tradeable': False,
       'dividendYield': 0.0061000003,
       'bidSize': 1100,
       'dayHigh': 152.57,
       'coinMarketCapLink': None,
       'regularMarketPrice': 151.29,
       'preMarketPrice': None,
       'logo_url': 'https://logo.clearb
      

      只需选择/选择您想要的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-09-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-18
        • 1970-01-01
        • 2023-01-23
        相关资源
        最近更新 更多