欢迎来到RankFan的Blogs

扩大
缩小

回测Codes

# Ref:Python for Algorithmic Trading
# Calculates the max-drawdown
data['returns'] = np.log(data['price'] / data['price'].shift(1))
data['returns'].hist(bins=35, figsize=(10, 6));

data['strategy'] = data['position'].shift(1) * data['returns']
data[['returns', 'strategy']].sum().apply(np.exp) # calculate the gross performance.

np.exp(data[['returns', 'strategy']].mean() * 252) - 1 # mean for daily
(data[['returns', 'strategy']].apply(np.exp) - 1).std() * 252 ** 0.5 # std for daily
data['cumret'] = data['strategy'].cumsum().apply(np.exp)
data['cummax'] = data['cumret'].cummax()
drawdown = data['cummax'] - data['cumret']
drawdown.max()

# Calculates the element-wise difference
temp = drawdown[drawdown == 0]
periods = (temp.index[1:].to_pydatetime() - temp.index[:-1].to_pydatetime())
periods.max()

posted on 2022-09-08 10:35  RankFan  阅读(22)  评论(0编辑  收藏  举报

导航