计算包含财务数据的数据框的收益 [英] Calculating returns from a dataframe with financial data

查看:89
本文介绍了计算包含财务数据的数据框的收益的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含每月财务数据的数据框:

I have a dataframe with monthly financial data:

In [89]: vfiax_monthly.head()
Out[89]: 
            year  month  day       d   open  close   high    low  volume  aclose
2003-01-31  2003      1   31  731246  64.95  64.95  64.95  64.95       0   64.95
2003-02-28  2003      2   28  731274  63.98  63.98  63.98  63.98       0   63.98
2003-03-31  2003      3   31  731305  64.59  64.59  64.59  64.59       0   64.59
2003-04-30  2003      4   30  731335  69.93  69.93  69.93  69.93       0   69.93
2003-05-30  2003      5   30  731365  73.61  73.61  73.61  73.61       0   73.61

我正在尝试像这样计算收益:

I'm trying to calculate the returns like that:

In [90]: returns = (vfiax_monthly.open[1:] - vfiax_monthly.open[:-1])/vfiax_monthly.open[1:]

但是我只有零:

In [91]: returns.head()
Out[91]: 
2003-01-31   NaN
2003-02-28     0
2003-03-31     0
2003-04-30     0
2003-05-30     0
Freq: BM, Name: open

我认为这是因为算术运算在索引上对齐,并且使[1:][:-1]无效.

I think that's because the arithmetic operations get aligned on the index and that makes the [1:] and [:-1] useless.

我的解决方法是:

In [103]: returns = (vfiax_monthly.open[1:].values - vfiax_monthly.open[:-1].values)/vfiax_monthly.open[1:].values

In [104]: returns = pd.Series(returns, index=vfiax_monthly.index[1:])

In [105]: returns.head()
Out[105]: 
2003-02-28   -0.015161
2003-03-31    0.009444
2003-04-30    0.076362
2003-05-30    0.049993
2003-06-30    0.012477
Freq: BM

是否有更好的方法来计算收益?我不喜欢先转换为数组再转换为Series.

Is there a better way to calculate the returns? I don't like the conversion to array and then back to Series.

推荐答案

不是切片,而是使用.shift移动值在DataFrame/Series中的索引位置.例如:

Instead of slicing, use .shift to move the index position of values in a DataFrame/Series. For example:

returns = (vfiax_monthly.open - vfiax_monthly.open.shift(1))/vfiax_monthly.open.shift(1)

这是pct_change在阀盖下所做的事情.您也可以将其用于其他功能,例如:

This is what pct_change is doing under the bonnet. You can also use it for other functions e.g.:

(3*vfiax_monthly.open + 2*vfiax_monthly.open.shift(1))/5

您可能还想研究滚动窗口功能可用于其他类型的财务数据分析.

You might also want to looking into the rolling and window functions for other types of analysis of financial data.

这篇关于计算包含财务数据的数据框的收益的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆