首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >索引:如何修复仅对DatetimeIndex、TimedeltaIndex或PeriodIndex有效,但获得了“TypeError”的实例

索引:如何修复仅对DatetimeIndex、TimedeltaIndex或PeriodIndex有效,但获得了“TypeError”的实例
EN

Stack Overflow用户
提问于 2020-03-23 14:53:12
回答 1查看 1.4K关注 0票数 0

我想计算12个月的复合月度股票回报,以获得年度回报。

下面是我所做的,但我得到了一个错误消息

代码语言:javascript
运行
复制
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

然后,我检索了需要计算每月回报的列

代码语言:javascript
运行
复制
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()

我只是简化了脚本,仍然得到相同的错误

代码语言:javascript
运行
复制
TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but 
got an instance of 'Index'
EN

回答 1

Stack Overflow用户

发布于 2020-03-23 14:55:03

我认为您需要将convert列添加到datetimeindex:

代码语言:javascript
运行
复制
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())
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60809045

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档