[英]TypeError: How to fix Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Index'
I want to compute Compound monthly stock returns over 12 months to obtain annual returns.我想计算 12 个月内的复合月度股票回报以获得年度回报。
Here is what I have done, but I am getting an error massage这是我所做的,但我收到了错误消息
Month_Return = pd.read_csv("Monthly Stock Return.csv")
Month_Return.set_index('gvkey', inplace=True,drop = False)
Month_Return = Month_Return.rename(columns={"gvkey": "Global_comp_key",
'iid':"issue identifier","tic":"ticker","conm":"Company name",
"prccm":"Price_Close_Monthly","exchg":"Stock Exchange
","datadate":"Date})
Month_Return['Date'] = pd.to_datetime(Month_Return['Date'], format='%Y%M%d')
Month_Return = Month_Return.set_index('Date')
###Month_Return['Date'] = Month_Return['Date'].dt.date###
gvkey issue datadate ticker Company_name Price_Close_Monthly Stock Exchange gsector
1003 1 2003-01-31 ANTQ A.A 0.0400 19.0 25.0
1003 1 2004-01-31 ANTQ A.A. 0.0400 19.0 25.0
1003 1 2004-01-29 ANTQ A.A. 0.0400 19.0 25.0
1003 1 2004-01-31 ANTQ A.B 0.0400 19.0 25.0
1003 1 2004-01-30 ANTQ A.C 0.0001 19.0 25.0
Then I retrieved the colunm I need to calculate the monthly return然后我检索了我需要计算每月回报的列
results_storage['month'] = Month_Return.index.month
results_storage['year'] = Month_Return.index.year
Date Price_Close_Monthly year month
2003-01-31 0.0400 2003 1
2004-01-31 0.0400 2004 1
2004-01-29 0.0400 2004 1
2004-01-31 0.0400 2004 1
2004-01-30 0.0001 2004 1
df_Month_Return_annual =results_storage['Price_Close_Monthly'].
resample('M').ffill().pct_change()
I just simplified the script, and am still getting the same error我只是简化了脚本,但仍然出现相同的错误
TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but
got an instance of 'Index'
I think you need add convert column to datetimeindex:我认为您需要将转换列添加到 datetimeindex:
Month_Return = pd.read_csv("Monthly Stock Return.csv")
Month_Return.set_index('gvkey', inplace=True,drop = False)
Month_Return['Date'] = pd.to_datetime(Month_Return['Date'], format='%Y%M%d')
Month_Return = Month_Return.set_index('Date')
Month_Return['month'] = Month_Return.index.month
Month_Return['year'] = Month_Return.index.year
df_Month_Return_annual = (Month_Return['Price_Close_Monthly'].resample('M')
.ffill()
.pct_change())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.