如何使用python计算回撤,下面给大家举个小例子:
1. 单期简单收益率
import datetime import pandas as pd pd.core.common.is_list_like = pd.api.types.is_list_like
price = pd.Series([3.42,3.51,3.68,3.43,3.56,3.67], index=[datetime.date(2015,7,x) for x in range(3,9)]) price
2015-07-03 3.42 2015-07-04 3.51 2015-07-05 3.68 2015-07-06 3.43 2015-07-07 3.56 2015-07-08 3.67 dtype: float64
利用ffn库计算单期简单收益
import ffn
r = ffn.to_returns(price) r
2015-07-03 NaN 2015-07-04 0.026316 2015-07-05 0.048433 2015-07-06 -0.067935 2015-07-07 0.037901 2015-07-08 0.030899 dtype: float64
2. 回撤
回撤(Maximum Drawdown, MDD) 用来衡量投资(特别是基金)的表现。
2.1 回撤:某资产在时刻T的回撤是指资产在(0,T)的最高峰值与现在价值之间的回落值,用数学公式表达为:
2.2 对应的回撤率为:
2.3 利用收益率计算回撤
value = (1 + r).cumprod() value
2015-07-03 NaN 2015-07-04 1.026316 2015-07-05 1.076023 2015-07-06 1.002924 2015-07-07 1.040936 2015-07-08 1.073099 dtype: float64
D = value.cummax() - value D
2015-07-03 NaN 2015-07-04 0.000000 2015-07-05 0.000000 2015-07-06 0.073099 2015-07-07 0.035088 2015-07-08 0.002924 dtype: float64
d = D / (D + value) d
2015-07-03 NaN 2015-07-04 0.000000 2015-07-05 0.000000 2015-07-06 0.067935 2015-07-07 0.032609 2015-07-08 0.002717 dtype: float64
MDD = D.max() MDD
0.07309941520467844
mdd =d.max() mdd # 对应的回撤率值为
0.06793478260869572
# 采用ffn库计算收益率累积回撤 ffn.calc_max_drawdown(value)
-0.06793478260869568
from empyrical import max_drawdown
# 使用 empyrical 计算收益率序列回撤 max_drawdown(r)
-0.06793478260869572
python学习网,大量的免费python视频教程,欢迎在线学习!