以下代码工作正常。
import pandas as pd
#import numpy as np
import matplotlib.pyplot as plt
from IPython import get_ipython
get_ipython().run_line_magic('matplotlib', 'inline')
sym = 'SPY'
df_close = pd.DataFrame()
df_temp = pd.read_json('https://api.iextrading.com/1.0/stock/'+sym+'/chart/5y')
df_temp.set_index('date',inplace=True)
df_close = df_temp['close']
loc = df_close.index.get_loc('2015-08-17')
我修改它以从 nsepy 包中获取数据。ie 替换了 read_json行并注释了 set_index行,因为从包中获取的数据默认将日期行作为索引
import pandas as pd
#import numpy as np
import matplotlib.pyplot as plt
from IPython import get_ipython
from datetime import date
from nsepy import get_history
get_ipython().run_line_magic('matplotlib', 'inline')
sym = 'SBIN'
df_close = pd.DataFrame()
df_temp = get_history(symbol=sym,
start=date(2014,1,1),
end=date(2018,3,24))
#df_temp.set_index('date',inplace=True)
df_close = df_temp['Close']
loc = df_close.index.get_loc('2015-08-17')
在这两种情况下, df_close 都是一个系列,并且其中包含日期。唯一的区别是,在正确的场景中,它包含格式为 2013-03-25 00:00:00的日期
而在不正确的格式中,它的格式类似于2014-01-01
这是日志。
runfile('C:/Users/Arun/.spyder-py3/Practise files/market_correction.py', wdir='C:/Users/Arun/.spyder-py3/Practise files') Traceback(最近一次通话最后):
文件“”,第 1 行,在 runfile('C:/Users/Arun/.spyder-py3/Practise files/market_correction.py', wdir='C:/Users/Arun/.spyder-py3/Practise files')
文件“C:\Users\Arun\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py”,第 705 行,运行文件 execfile(文件名,命名空间)
文件“C:\Users\Arun\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py”,第 102 行,在 execfile exec(compile(f.read(), filename, 'exec') 中,命名空间)
文件“C:/Users/Arun/.spyder-py3/Practise files/market_correction.py”,第 27 行,在 loc = df_close.index.get_loc('2015-08-17')
文件“C:\Users\Arun\Anaconda3\lib\site-packages\pandas\core\indexes\base.py”,第 2527 行,在 get_loc 返回 self._engine.get_loc(self._maybe_cast_indexer(key))
文件“pandas/_libs/index.pyx”,第 117 行,在 pandas._libs.index.IndexEngine.get_loc
文件“pandas/_libs/index.pyx”,第 139 行,在 pandas._libs.index.IndexEngine.get_loc
文件“pandas/_libs/hashtable_class_helper.pxi”,第 1265 行,在 pandas._libs.hashtable.PyObjectHashTable.get_item
文件“pandas/_libs/hashtable_class_helper.pxi”,第 1273 行,在 pandas._libs.hashtable.PyObjectHashTable.get_item
键错误:'2015-08-17'
我究竟做错了什么?这一天出现在系列中。
我也尝试过 df.loc 方法,但这会产生其他错误。
我在 python 3.6 中使用 anaconda spyder
解决方案 :
import pandas as pd
#import numpy as np
import matplotlib.pyplot as plt
from IPython import get_ipython
from datetime import date
from nsepy import get_history
get_ipython().run_line_magic('matplotlib', 'inline')
sym = 'SBIN'
df_close = pd.DataFrame()
df_temp = get_history(symbol=sym,
start=date(2014,1,1),
end=date(2018,3,24))
**df_temp.reset_index(drop = False, inplace = True)
df_temp['Date']= pd.to_datetime(df_temp['Date'])
df_temp.set_index('Date',inplace=True)**
df_close = df_temp['Close']
loc = df_close.index.get_loc('2015-08-17')