0

I have a dataset that looks like:

sp_data.head()
Out[21]: 
         Date       Open       High        Low      Close  Adj Close  Volume
0  1927-12-30  17.660000  17.660000  17.660000  17.660000  17.660000       0
1  1928-01-03  17.760000  17.760000  17.760000  17.760000  17.760000       0
2  1928-01-04  17.719999  17.719999  17.719999  17.719999  17.719999       0
3  1928-01-05  17.549999  17.549999  17.549999  17.549999  17.549999       0
4  1928-01-06  17.660000  17.660000  17.660000  17.660000  17.660000       0

which contains daily data, and I would like to get the returns per week, per month, per 3, 6 months etc. I tried the following:

sp_data_daily_returns = sp_data['Close'].pct_change()
sp_data_monthly_returns = sp_data['Close'].resample('M').ffill().pct_change()

but I am getting this error:

TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex'

How can I fix that?

adrCoder
  • 3,145
  • 4
  • 31
  • 56
  • you need make resample on datetime series. – Zaraki Kenpachi Mar 11 '20 at 08:59
  • Does this answer your question? [Pandas Resampling error: Only valid with DatetimeIndex or PeriodIndex](https://stackoverflow.com/questions/30857680/pandas-resampling-error-only-valid-with-datetimeindex-or-periodindex) – Shaido Mar 11 '20 at 09:10

1 Answers1

1

Basically, we apply any conversion on date we have to check its data-type. So error you are getting is based on data type error, you can change it using pd.to_datetime().

You can have a look at this too:

Pandas Resampling error: Only valid with DatetimeIndex or PeriodIndex

deepak sen
  • 437
  • 4
  • 13