使用Pandas DataFrame计算每日收益 [英] Calculate Daily Returns with Pandas DataFrame
本文介绍了使用Pandas DataFrame计算每日收益的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的熊猫数据框:
prices = pandas.DataFrame([1035.23, 1032.47, 1011.78, 1010.59, 1016.03, 1007.95,
1022.75, 1021.52, 1026.11, 1027.04, 1030.58, 1030.42,
1036.24, 1015.00, 1015.20])
这是我的daily_return
函数:
def daily_return(prices):
return prices[:-1] / prices[1:] - 1
以下是此函数的输出:
0 NaN
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
10 0
11 0
12 0
13 0
14 NaN
为什么会有这个输出?
推荐答案
由于操作将对索引进行对齐,因此可以将其中一个DataFrame转换为数组:
Because operations will do alignment on index, you can convert one of the DataFrames to array:
prices[:-1].values / prices[1:] - 1
或
prices[:-1] / prices[1:].values - 1
取决于所需结果的索引.
depends on what the index of the result you want.
或使用shift()
方法:
prices.shift(1) / prices - 1
和:
prices / prices.shift(1) - 1
这篇关于使用Pandas DataFrame计算每日收益的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文