1

I am trying to loop through all the dates for the given time period with:

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

But get this error:

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'>

Not sure how to loop through all periods from a given start date (disp_start). Thanks

thomas.mac
  • 1,236
  • 3
  • 17
  • 37

2 Answers2

1

I think you need DataFrame.loc for select by label, because DataFrame.iloc is for select by position(s):

for date in disp_data.index:
    returns = (closingprices.iloc[-1].divide(closingprices.loc[date]))-1

If need iloc for some reason is posssible use Index.get_loc:

for date in disp_data.index:
    returns = (closingprices.iloc[-1].divide(closingprices.iloc[df.index.get_loc(date)]))-1
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
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")

Iterating through a range of dates in Python