我试图通过以下方式遍历给定时间段的所有日期:
disp_start = dt.datetime(2017,1,6) #####START DATE
disp_data = closingprices.loc[disp_start:] #closing prices is data w/ stock prices
for date in disp_data.index:
returns = (closingprices.iloc[-1].divide(closingprices.iloc[date]))-1
但是得到这个错误:
TypeError: cannot do positional indexing on <class 'pandas.core.indexes.datetimes.DatetimeIndex'> with these indexers [2017-01-06 00:00:00] of <class 'pandas._libs.tslib.Timestamp'>
不确定如何遍历给定开始日期(disp_start)的所有时段。感谢
答案 0 :(得分:1)
我认为您需要DataFrame.loc
来选择标签,因为DataFrame.iloc
用于按位置选择:
for date in disp_data.index:
returns = (closingprices.iloc[-1].divide(closingprices.loc[date]))-1
如果出于某种原因需要iloc
,请使用Index.get_loc
:
for date in disp_data.index:
returns = (closingprices.iloc[-1].divide(closingprices.iloc[df.index.get_loc(date)]))-1
答案 1 :(得分:0)
def daterange(start_date, end_date):
for n in range(int ((end_date - start_date).days)):
yield start_date + timedelta(n)
start_date = date(2013, 1, 1)
end_date = date(2015, 6, 2)
for single_date in daterange(start_date, end_date):
print single_date.strftime("%Y-%m-%d")