【问题标题】:Simplifying Try, Except for yahooquery简化尝试,除了 yahooquery
【发布时间】:2021-05-17 17:29:51
【问题描述】:

我正在尝试从 yahooquery 获取大约 10 个股票属性。当某些数据不可用时(例如,当公司没有盈利时,没有 PE 比率)它会引发 KeyError。在这种情况下,我想返回零。有什么办法可以简化我的代码而不是把 Try/Except 放到每个属性上?

def data(ticker): #pulling data about stock from Yahoo Finance API
    try:
        company_name = Ticker(ticker).quote_type[ticker]["shortName"]
    except KeyError:
        company_name = 0
    try:
        stock_price = Ticker(ticker).financial_data[ticker]["currentPrice"]
    except KeyError:
        stock_price = 0
    try:
        change = Ticker(ticker).history(interval='1mo', start=(datetime.datetime.today() - datetime.timedelta(days=90)), end=datetime.datetime.today())
        change = change["open"]
        growth_or_loose = ((change.iloc[-1] / change.iloc[0]) - 1)
    except:
        growth_or_loose = 0
    try:
        recommendation = Ticker(ticker).financial_data[ticker]["recommendationKey"]
    except KeyError:
        recommendation = 0
    try:
        market_cap = Ticker(ticker).summary_detail[ticker]["marketCap"]
    except KeyError:
        market_cap = 0
    try:
        pe = Ticker(ticker).summary_detail[ticker]["trailingPE"]
    except KeyError:
        pe = 0
    try:
        pb = Ticker(ticker).key_stats[ticker]["priceToBook"]
    except KeyError:
        pb = 0
    try:
        rev_growth = Ticker(ticker).financial_data[ticker]["revenueGrowth"]
    except KeyError:
        rev_growth = 0
    try:
        ern_growth = Ticker(ticker).financial_data[ticker]["earningsGrowth"]
    except KeyError:
        ern_growth = 0
    profit_margin = Ticker(ticker).financial_data[ticker]["profitMargins"]
    try:
        debt2equity = Ticker(ticker).financial_data[ticker]["debtToEquity"]
    except KeyError:
        debt2equity = 0
    data =  company_name, stock_price, growth_or_loose,  recommendation, market_cap, pe, pb, rev_growth, ern_growth, profit_margin, debt2equity
    return list(data)```

【问题讨论】:

  • 您发现任何答案有帮助吗?请为有帮助的答案投票,并接受您认为对您的案例最有帮助的答案。谢谢!

标签: python yahoo-finance simplify try-except


【解决方案1】:

在这种情况下,您可以使用字典的 get 方法,如果字典不包含该键,则返回 None 而不是 KeyError,或者如果提供了默认值(第二个参数),它将返回默认值。


my_dict = {
    "hello" : "world"
}

try:
    hello = my_dict["NONEXISTING"]
except KeyError:
    hello = "greetings"

# the try/except block can be replaced with this, and since the key
# doesn't exist, the method returns "greetings" instead of raising a KeyError
hello = my_dict.get("NONEXISTING", "greetings")

【讨论】:

    【解决方案2】:

    您还可以使用集合中的 defaultdict 为任何没有值的变量提供默认值。 首先将您的字典转换为 defaultdict

    # Python program to demonstrate 
    # defaultdict 
      
      
    from collections import defaultdict 
      
      
    # Function to return a default 
    # values for keys that is not 
    # present 
    def def_value(): 
        return "Not Present"
          
    # Defining the dict 
    d = defaultdict(def_value) 
    d["a"] = 1
    d["b"] = 2
      
    print(d["a"]) 
    print(d["b"]) 
    print(d["c"]) 
    

    输出:

    1
    2
    Not Present
    

    【讨论】:

      【解决方案3】:
      from yahooquery import Ticker
      import time
      symbols = {
          'AAPL': 'B12','BABA': 'B13','MSFT': 'B14',
      }
      tickers = Ticker(list(symbols.keys()), asynchronous=True)
      
      try:
          while True:
              prices = tickers.price
              for k, v in symbols.items():
                  try:
                      a = str(prices[k]['regularMarketPrice'])
                      print ("currentPrice : "+a)
                  except Exception as e:print(0)
                  try:
                      b = str(prices[k]['marketCap'])
                      print ("marketCap : "+b)
                  except Exception as e:print(0)
                  try:
                      c = str(prices[k]['payoutRation'])
                      print ("payoutRation : "+c)
                  except Exception as e:print(0)
                  except Exception as e:
                      print(e)
          time.sleep(2)
      except Exception as e:
              print(e)
      

      您还可以使用以下方法将此数据导出到 Excel:

      import xlwings as xw
      wb = xw.Book('Filename.xlsx')
      sht1 = wb.sheets['Sheet1']
      for k, v in symbols.items():
          try:
              sht1.range(v).value = str(prices[k]['regularMarketPrice'])
              v1=v.replace("B", "C")
              sht1.range(v1).value = str(prices[k]['regularMarketDayHigh'])
              v2=v1.replace("C", "D")
              sht1.range(v2).value = str(prices[k]['regularMarketDayLow'])
          except Exception as e:
                  print(e)
      

      【讨论】:

        猜你喜欢
        • 2019-06-24
        • 1970-01-01
        • 2013-07-23
        • 2013-04-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-08
        • 1970-01-01
        相关资源
        最近更新 更多