我想计算12个月的复合月度股票回报,以获得年度回报。
下面是我所做的,但我得到了一个错误消息
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
然后,我检索了需要计算每月回报的列
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()
我只是简化了脚本,仍然得到相同的错误
TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but
got an instance of 'Index'
发布于 2020-03-23 14:55:03
我认为您需要将convert列添加到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())
https://stackoverflow.com/questions/60809045
复制相似问题