如何计算以熊猫为单位的年回报率?

如何解决如何计算以熊猫为单位的年回报率?

因此,我一直在研究SP500的年度收益以及从quandl订阅中下载的信息。我已经使用resample()和pct_change()来研究数据,但是由于某种原因,我的结果并不能说明预期的结果。

sp500_df = quandl.get("MULTPL/SP500_REAL_PRICE_MONTH",authtoken="YOUR OWN AUTH KEY")
sp500_Y_ret_df = sp500_df['Value'].resample('Y').mean().pct_change().dropna()

SP 500截至2008年底的期望值应该为-38.5%,但是由于某些原因我的代码显示-17%?如果由于某种原因您无法访问数据,我可以为该数据提供一个.csv文件。感谢一百万的帮助。

sp500_Y_ret_df.loc['2008-12-31']

输出:

-0.17319465450687388

最近20年:

sp500_Y_ret_df.tail(20)

输出:

2001-12-31   -0.164631
2002-12-31   -0.164795
2003-12-31   -0.032081
2004-12-31    0.173145
2005-12-31    0.067678
2006-12-31    0.085836
2007-12-31    0.126625
2008-12-31   -0.173195
2009-12-31   -0.224552
2010-12-31    0.203406
2011-12-31    0.113738
2012-12-31    0.087221
2013-12-31    0.190603
2014-12-31    0.175436
2015-12-31    0.067610
2016-12-31    0.014868
2017-12-31    0.170363
2018-12-31    0.121093
2019-12-31    0.065247
2020-12-31    0.061747
Freq: A-DEC,Name: Value,dtype: float64

使用随机生成的数据:

aapl_df = pd.DataFrame({ 
'ticker':np.repeat( ['aapl'],2500 ),'date':pd.date_range('1/1/2011',periods=2500,freq='D'),'price':(np.random.randn(2500).cumsum() + 10) }).set_index('date')
aapl_df.head()

date        
2011-01-01  aapl    9.011290
2011-01-02  aapl    9.092603
2011-01-03  aapl    9.139830
2011-01-04  aapl    7.782112
2011-01-05  aapl    8.316270

使用规定的“最后”产生了更接近的结果,但不确定那是否纯粹是运气

aapl_Y_ret_df = aapl_df['price'].resample('Y').last()
aapl_Y_ret_df.tail()

输出

    date
2013-12-31    18.535328
2014-12-31    15.201832
2015-12-31    36.040411
2016-12-31    42.272464
2017-12-31    20.421079
Freq: A-DEC,Name: price,dtype: float64

-

aapl_Y_ret_df = aapl_df['price'].resample('Y').last().pct_change()
aapl_Y_ret_df.tail()
date
2013-12-31    0.569359
2014-12-31   -0.179846
2015-12-31    1.370794
2016-12-31    0.172918
2017-12-31   -0.516918
Freq: A-DEC,dtype: float64

解决方法

  • 通过在CloseAdj Close中找到每日百分比变化,然后在sum中乘以100,来计算年度回报。
  • 使用groupby按年份获取值。
  • df['Adj Close'].resample('Y').mean()返回每年'Adj Close'值的平均值,这不是确定年度收益的方法。
    • 从2007年到2008年,平均收盘价的变化百分比为-17.4%。这不是回报。
import pandas_datareader as web
import pandas as pd

# load S&P 500 data
df = web.DataReader('^gspc',data_source='yahoo',start='2000-01-01',end='2020-01-01').reset_index()

# display(df)
        Date         High          Low         Open        Close      Volume    Adj Close
0 2000-01-03  1478.000000  1438.359985  1469.250000  1455.219971   931800000  1455.219971
1 2000-01-04  1455.219971  1397.430054  1455.219971  1399.420044  1009000000  1399.420044
2 2000-01-05  1413.270020  1377.680054  1399.420044  1402.109985  1085500000  1402.109985
3 2000-01-06  1411.900024  1392.099976  1402.109985  1403.449951  1092300000  1403.449951
4 2000-01-07  1441.469971  1400.729980  1403.449951  1441.469971  1225200000  1441.469971

# groupby year and determine the daily percent change by year,and add it as a column to df
df['pct_ch'] = df.groupby(df.Date.dt.year)['Adj Close'].apply(pd.Series.pct_change)

# groupby year and aggregate sum of pct_ch to get the yearly return
yearly_pct_ch = df.groupby(df.Date.dt.year)['pct_ch'].sum().mul(100).reset_index().rename(columns={'pct_ch': 'cum_pct_ch_year'})

# display(yearly_pct_ch)
    Date  cum_pct_ch_year
0   2000        -7.274088
1   2001        -8.890805
2   2002       -23.811947
3   2003        21.552072
4   2004         9.535574
5   2005         4.295586
6   2006        11.626670
7   2007         4.860178
8   2008       -38.702107
9   2009        21.622674
10  2010        12.052038
11  2011         1.575069
12  2012        11.840560
13  2013        24.012739
14  2014        12.320664
15  2015         0.501799
16  2016        11.494988
17  2017        17.127082
18  2018        -5.822426
19  2019        26.031938

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)> insert overwrite table dwd_trade_cart_add_inc > select data.id, > data.user_id, > data.course_id, > date_format(
错误1 hive (edu)> insert into huanhuan values(1,'haoge'); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive> show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 <configuration> <property> <name>yarn.nodemanager.res