问题描述
我正在尝试从 yahooquery 获取大约 10 个股票属性。当某些数据不可用时(例如,当公司没有盈利时,没有市盈率)它会引发 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)```
解决方法
在这种情况下,您可以使用字典的 get-method 来代替返回 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")
,
您还可以使用集合中的 defaultdict 为任何没有值的变量提供默认值。 首先将您的字典转换为 defaultdict
private String[] getPurpose(loanPurpose){
String purpose[] = new String[2];
if ("REFINANCE".equalsIgnoreCase(loanPurpose)) {
purpose[0] = "Refinance";
purpose[1] = "Cash-Out";
return purpose;
}
return null;
}
输出:
fun getPurpose(data) =
if(upper("PURCHASE") == data)
// how i can assign the values in string array and return
,
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)