从 Yahoo 财务包中提取 Industry/Sector 时出现问题
Issues while extracting Industry/Sector from Yahoo finance package
我必须更改我的问题主题以反映我的实际问题。
如果我用 3 只股票尝试下面的示例,代码运行良好。但是,如果我添加更多代码,我会得到 'Key error'。请帮忙。
代码:
stocks = ['ADSK', 'DDD', 'DM', 'FARO', 'MTLS', 'SSYS', 'XONE', 'AAPL', 'NXTG', 'QCOM']
import yfinance as yf
import pandas as pd
df = pd.DataFrame()
for stock in stocks:
info = yf.Ticker(stock).info
industry = info['industry']
beta = info['beta']
sector = info['sector']
df = df.append({'Stock':stock,'Industry':industry,'Beta':beta,'Sector':sector}, ignore_index=True)
错误如下:
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-35-8ae147fa8723> in <module>
7 for stock in stocks:
8 info = yf.Ticker(stock).info
----> 9 industry = info['industry']
10 beta = info['beta']
11 sector = info['sector']
KeyError: 'industry'
NXTG 股票既没有“行业”字段,也没有“beta”字段。字典方法 get()
可用于避免 KeyError:
stocks = ['ADSK', 'DDD', 'DM', 'FARO', 'MTLS', 'SSYS', 'XONE', 'AAPL', 'NXTG', 'QCOM']
import yfinance as yf
import pandas as pd
df = pd.DataFrame()
for stock in stocks:
info = yf.Ticker(stock).info
industry = info.get('industry')
beta = info.get('beta')
sector = info.get('sector')
df = df.append({'Stock':stock,'Industry':industry,'Beta':beta,'Sector':sector}, ignore_index=True)
df
这将给出以下结果:
我必须更改我的问题主题以反映我的实际问题。
如果我用 3 只股票尝试下面的示例,代码运行良好。但是,如果我添加更多代码,我会得到 'Key error'。请帮忙。
代码:
stocks = ['ADSK', 'DDD', 'DM', 'FARO', 'MTLS', 'SSYS', 'XONE', 'AAPL', 'NXTG', 'QCOM']
import yfinance as yf
import pandas as pd
df = pd.DataFrame()
for stock in stocks:
info = yf.Ticker(stock).info
industry = info['industry']
beta = info['beta']
sector = info['sector']
df = df.append({'Stock':stock,'Industry':industry,'Beta':beta,'Sector':sector}, ignore_index=True)
错误如下:
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-35-8ae147fa8723> in <module>
7 for stock in stocks:
8 info = yf.Ticker(stock).info
----> 9 industry = info['industry']
10 beta = info['beta']
11 sector = info['sector']
KeyError: 'industry'
NXTG 股票既没有“行业”字段,也没有“beta”字段。字典方法 get()
可用于避免 KeyError:
stocks = ['ADSK', 'DDD', 'DM', 'FARO', 'MTLS', 'SSYS', 'XONE', 'AAPL', 'NXTG', 'QCOM']
import yfinance as yf
import pandas as pd
df = pd.DataFrame()
for stock in stocks:
info = yf.Ticker(stock).info
industry = info.get('industry')
beta = info.get('beta')
sector = info.get('sector')
df = df.append({'Stock':stock,'Industry':industry,'Beta':beta,'Sector':sector}, ignore_index=True)
df
这将给出以下结果: