我正在接受用户输入来获取特定股票的历史数据,我想处理 2 个可能的错误,第一个是由于错误输入而生成的错误,并且代码生成错误,第二个是如果输入错误但代码被执行并且我得到一个空数据框
while True:
try:
us = input('Enter the symbol of your stock :')
us_sd = input('Enter the start date in yyyy-mm-dd :')
year, month, day = map(int, us_sd.split("-"))
us_sd = datetime.date(year,month,day)
data = ns.get_history(symbol=us.upper(), start=us_sd, end=date.today())
print(data)
break
except Exception as e:
print('there was an error with your input :{0}'.format(e))
上面的代码处理是否发生任何系统错误,但当用户输入错误的股票代码时,例如 SBI 代码是 SBIN,但如果有人输入 SBINSE 或假设有人输入 ZOO 作为股票代码,数据将返回一个空数据帧,没有任何错误,我想要设置一个条件,如果返回的数据帧为空,则循环应继续进行。请帮忙。
上面代码中的 ns 是 nsepy 模块。我的python版本是3.6.4
感谢 David A 为我指明了正确的方向。
这是我在代码中实现的更改,现在它似乎可以处理输入错误的股票代码时的所有空数据框问题
while True:
try:
us = input('Enter the name of your stock :')
us_sd = input('Enter the start date in yyyy-mm-dd :')
year, month, day = map(int, us_sd.split("-"))
us_sd = datetime.date(year,month,day)
data = ns.get_history(symbol=us.upper(), start=us_sd, end=date.today())
if data.empty == True:
raise RuntimeError('Symbol doesn\'t exist')
break
except Exception as e:
print('There was an error in your input, please try again :{0}'.format(e))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)