Pandas 的年化回报
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41293677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Annualized Return in Pandas
提问by northernthinking
I am seeking to confirm that my representation of the annualized return formula (using monthly returns) is optimal.
我试图确认我对年化回报公式(使用月度回报)的表示是最佳的。
The annualized return formula I am using (where M is a monthly return and D is the total count of monthly returns) where the count of monthly returns is greater than 12 is as follows:
我使用的年化回报公式(其中 M 是每月回报,D 是每月回报的总数),其中每月回报的数量大于 12,如下所示:
Alternatively, the this would change in the case of the monthly return count being less than 12:
或者,在每月返回计数小于 12 的情况下,这会发生变化:
Here is my representation of this formula in Pandas:
这是我在 Pandas 中对这个公式的表示:
ann_return = observations.apply(lambda y: y.apply(lambda x: x+1))
ann_return = (ann_return.prod() ** (np.min(12/len(ann_return.index.values)) if len(ann_return.index.values) > 12 else 12/len(ann_return.index.values)))-1
回答by piRSquared
Formula
公式
D = len(ann_return)
ann_return.add(1).prod() ** (12 / D) - 1
回答by Acumenus
This calculates the annualized return percentage. It works with both an individual number or a Pandas dataframe. In the latter case, the first argument percent
and optionally the second argument months
can be a dataframe.
这计算了年化回报率。它适用于单个数字或 Pandas 数据框。在后一种情况下,第一个参数percent
和可选的第二个参数months
可以是数据帧。
This was tested with Python 3.7.0 and Pandas 0.23.4 with NumPy 1.15.2.
这是用 Python 3.7.0 和 Pandas 0.23.4 和 NumPy 1.15.2 测试的。
def annualize_return(percent: float, months: int) -> float:
"""Return the annualized return percentage given the holding return percentage and the number of months held.
>>> annualize_return(1.5, 1) # doctest: +ELLIPSIS
19.56...
>>> annualize_return(6.1, 3) # doctest: +ELLIPSIS
26.72...
>>> annualize_return(30, 12) # doctest: +ELLIPSIS
30.00...
>>> annualize_return(30, 15) # doctest: +ELLIPSIS
23.35...
>>> annualize_return(float('nan'), 15)
nan
>>> annualize_return(0, 0)
0
References:
https://en.wikipedia.org/wiki/Holding_period_return
https://www.wikihow.com/Calculate-Annualized-Portfolio-Return
"""
# Ref: https://stackoverflow.com/a/52618808/
if months == 0:
return percent
rate = percent / 100
years = months / 12
rate = ((rate + 1)**(1 / years)) - 1
percent = rate * 100
return percent
if __name__ == '__main__':
import doctest
doctest.testmod(verbose=True, exclude_empty=True)