Python与Pandas或NumPy滚动夏普比率

问题描述 投票:3回答:2

我试图使用Python和Pandas / NumPy生成6个月滚动夏普比率的图。

我的输入数据如下:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style("whitegrid")

# Generate sample data
d = pd.date_range(start='1/1/2008', end='12/1/2015')
df = pd.DataFrame(d, columns=['Date'])
df['returns'] = np.random.rand(d.size, 1)
df = df.set_index('Date')
print(df.head(20))

             returns
Date                
2008-01-01  0.232794
2008-01-02  0.957157
2008-01-03  0.079939
2008-01-04  0.772999
2008-01-05  0.708377
2008-01-06  0.579662
2008-01-07  0.998632
2008-01-08  0.432605
2008-01-09  0.499041
2008-01-10  0.693420
2008-01-11  0.330222
2008-01-12  0.109280
2008-01-13  0.776309
2008-01-14  0.079325
2008-01-15  0.559206
2008-01-16  0.748133
2008-01-17  0.747319
2008-01-18  0.936322
2008-01-19  0.211246
2008-01-20  0.755340

我想要的是

我想要制作的剧情类型是thisthe first plot from here(见下文)。 enter image description here

我的尝试

这是我正在使用的等式:

def my_rolling_sharpe(y):
    return np.sqrt(126) * (y.mean() / y.std()) # 21 days per month X 6 months = 126

# Calculate rolling Sharpe ratio
df['rs'] = calc_sharpe_ratio(df['returns'])

fig, ax = plt.subplots(figsize=(10, 3))
df['rs'].plot(style='-', lw=3, color='indianred', label='Sharpe')\
        .axhline(y = 0, color = "black", lw = 3)

plt.ylabel('Sharpe ratio')
plt.legend(loc='best')
plt.title('Rolling Sharpe ratio (6-month)')
fig.tight_layout()
plt.show()

enter image description here

问题是我得到一条水平线,因为我的函数给出了夏普比率的单个值。所有日期的值都相同。在示例图中,它们似乎显示出许多比率。

是否有可能绘制一个6个月的夏普比率,从一天到下一天变化?

pandas finance moving-average
2个回答
4
投票

使用df.rolling和固定窗口大小为180天的近似正确的解决方案:

df['rs'] = df['returns'].rolling('180d').apply(my_rolling_sharpe)

此窗口不完全是6个日历月,因为rolling需要固定的窗口大小,因此尝试window='6MS'(6个月开始)会引发ValueError。

为了计算一个正好6个月历月的窗口的夏普比率,我将由SO用户Mike复制this super cool answer

df['rs2'] = [my_rolling_sharpe(df.loc[d - pd.offsets.DateOffset(months=6):d, 'returns']) 
             for d in df.index]

# Compare the two windows
df.plot(y=['rs', 'rs2'], linewidth=0.5)

Sharpe ratio comparison


0
投票

我已经为你的问题准备了另一种解决方案,这个解决方案仅基于使用大熊猫的window functions

这里我已经定义了“即时”夏普比率的计算,请考虑为您的解决方案提供以下参数:

  • 我使用了2%的无风险利率
  • 虚线仅是滚动夏普比率的基准,值为1.6

所以代码如下

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style("whitegrid")

# Generate sample data
d = pd.date_range(start='1/1/2008', end='12/1/2015')
df = pd.DataFrame(d, columns=['Date'])
df['returns'] = np.random.rand(d.size, 1)
df = df.set_index('Date')

df['rolling_SR'] = df.returns.rolling(180).apply(lambda x: (x.mean() - 0.02) / x.std(), raw = True)
df.fillna(0, inplace = True)
df[df['rolling_SR'] > 0].rolling_SR.plot(style='-', lw=3, color='orange', 
                                         label='Sharpe', figsize = (10,7))\
                                         .axhline(y = 1.6, color = "blue", lw = 3,
                                                 linestyle = '--')

plt.ylabel('Sharpe ratio')
plt.legend(loc='best')
plt.title('Rolling Sharpe ratio (6-month)')
plt.show()

print('---------------------------------------------------------------')
print('In case you want to check the result data\n')
print(df.tail()) # I use tail, beacause of the size of your window.

你应该得到类似这张照片的东西

rolling sharpe ratio

© www.soinside.com 2019 - 2024. All rights reserved.