DAY 25
0
AI & Data

## 量化交易30天 Day25 - 投資組合概念(五) Sharpe ratio

### Sharpe Ratio 夏普比率

``````# 跟前一篇寫的程式碼大致相同，只修改繪圖部分：
import matplotlib.pyplot as plt
plt.figure(figsize=(15,10))
plt.scatter(x = portfolios['Standard Dev.'], y = portfolios['Returns'])
# 效率前緣點，用紅色標註
plt.scatter(x = eff_front_std, y = eff_front_ret, c = 'r')
# 無風險資產
plt.scatter(x = 0, y = 0.007, c = 'g', s = 100)
plt.annotate("100% 美國公債", (0,0.007), textcoords="offset points", xytext=(0,10), ha='left', fontsize=20)
# 繪圖設定
plt.grid()
plt.xlabel("Standard Dev.", fontsize=20)
plt.ylabel("Expected Returns", fontsize=20)
plt.xlim(-0.002,0.19)
plt.ylim(0,0.16)
plt.xticks(fontsize=15)
plt.yticks(fontsize=15)
``````

PS.這張圖的右上角那個圖形跟開頭那張圖是一樣的，只是座標軸的範圍變大，所以圖相對縮小。

Returns Standard Dev. SPY weight TLT weight GLD weight 美國公債

100% 美國公債 0.7% 0 -------- -------- -------- 100%

### 夏普比率最大的效率前緣投組

``````# 找夏普比率最大的投組
max_sharpe = 0
max_sharpe_returns = 0
max_sharpe_std = 0
for i in range(len(eff_front_set)):
sharpe = ( eff_front_set.iloc[i,:]['Returns'] - 0.007 ) / eff_front_set.iloc[i,:]['Standard Dev.']
if sharpe > max_sharpe:
max_sharpe = sharpe
max_sharpe_std = eff_front_set.iloc[i,:]['Standard Dev.']
max_sharpe_returns = eff_front_set.iloc[i,:]['Returns']
max_sharpe_set = (eff_front_set.iloc[i,:]['SPY weight'], eff_front_set.iloc[i,:]['TLT weight'], eff_front_set.iloc[i,:]['GLD weight'])
print("夏普比率最大點的報酬率與標準差 ", "(Returns, Standard Dev.) =", (max_sharpe_returns, max_sharpe_std))
print("夏普比率最大點的投組", "(SPY weight, TLT weight, GLD weight) =", max_sharpe_set)
``````

``````夏普比率最大點的報酬率與標準差  (Returns, Standard Dev.) = (0.10411453792285438, 0.08533161659682831)

``````
``````import matplotlib.pyplot as plt
plt.figure(figsize=(15,10))
# 效率前緣點，用紅色標註
plt.scatter(x = eff_front_std, y = eff_front_ret, c = 'r', s = 0.5)
# 無風險資產
plt.scatter(x = 0, y = 0.007, c = 'g', s = 100)
plt.annotate("100% 美國公債", (0,0.007), textcoords="offset points", xytext=(0,10), ha='left', fontsize=20)
# max sharpe set
plt.scatter(x = max_sharpe_std, y = max_sharpe_returns, c = 'orange', s = 100)
plt.annotate("最大夏普比率投組", (max_sharpe_std, max_sharpe_returns), textcoords="offset points", xytext=(15,-10), ha='left', fontsize=20)
# 切線
plt.plot([0,max_sharpe_std],[0.007, max_sharpe_returns])
# 繪圖設定
plt.grid()
plt.xlabel("Standard Dev.", fontsize=20)
plt.ylabel("Expected Returns", fontsize=20)
plt.xlim(-0.002,0.19)
plt.ylim(0,0.16)
plt.xticks(fontsize=15)
plt.yticks(fontsize=15)
``````