问题描述
我正在尝试编写一个简单的程序,该程序使用 csv 中的股票列表。我正在使用名为 nsetools
的库,它为印度股市提供股票信息。
Loop 应该从 csv 中选择股票代码并打印股票的当前市场价格。
但是,我收到以下错误:
Traceback (most recent call last):
File "C:/Users/anoopmah/AppData/Roaming/JetBrains/PyCharmCE2020.3/scratches/scratch_7.py",line 15,in <module>
p = nse.get_quote('temp')['lastPrice']
TypeError: 'NoneType' object is not subscriptable
代码:
import nsetools
import pandas as pd
from nsetools import Nse
nse = Nse()
#Import CSV into dataframe
filepath = "C:/temp/Stock/stocklist.csv"
df = pd.read_csv(filepath,encoding='windows-1252')
for i in range(0,len(df)):
temp = df["Name"][i]
print(temp)
p = nse.get_quote('temp')['lastPrice']
print(p)
解决方法
TypeError: 'NoneType' object is not subscriptable
错误表明您尝试下标(使用 []
)一个没有这样做的功能的对象。在这种情况下,它表示试图为具有值 None
(因此,... 'NoneType' object ...
)的对象添加下标。
如果我们检查发生错误的行,您会看到以下代码行:
p = nse.get_quote('temp')['lastPrice']
这里发生的事情是您试图从引用“temp”中检索数据,然后获取与键(在数据字典中)“lastPrice”匹配的值。问题在于,函数 get_quote
可能返回 None
。如您所见,在 documentation 中指定 “如果您对无效代码执行 get_quote 或 get_index_quote,则 API 返回 None。它不会像人们那样引发异常期待。”
因此,您可以断定错误是由于“temp”是无效引用而发生的。