Markowitz有效边界和投资组合优化基于Python（附代码）

MPT的假设：

• 投资者是理性的并且风险厌恶
• 投资者追求收益最大化
• 所有投资者都想最大化期望收益
• 不考虑佣金和税费
• 所有投资者都可以接触到同样的信息源和与投资决策相关的全部必要信息
• 投资者可以以无风险利率不受限制的借入和贷出资金

```import quandl
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

quandl.ApiConfig.api_key = 'PASTE YOUR API KEY HERE'
selected = ['CNP', 'F', 'WMT', 'GE', 'TSLA']
data = quandl.get_table('WIKI/PRICES', ticker = selected,
qopts = { 'columns': ['date', 'ticker', 'adj_close'] },
date = { 'gte': '2014-1-1', 'lte': '2016-12-31' }, paginate=True)
```date        ticker  adj_close
None
0  2014-01-02  CNP  19.290792
1  2014-01-03  CNP  19.282339
2  2014-01-06  CNP  19.307699
3  2014-01-07  CNP  19.510582
4  2014-01-08  CNP  19.307699```

```clean = data.set_index('date')
table = clean.pivot(columns='ticker')
```adj_close
ticker    CNP    F    GE    TSLA  WMT
date
2014-01-02  19.290792  12.884511  24.266002  150.10  71.343743
2014-01-03  19.282339  12.942926  24.248354  149.56  71.108673
2014-01-06  19.307699  13.001340  24.054226  147.00  70.710863
2014-01-07  19.510582  12.834442  24.080698  149.36  70.927850
2014-01-08  19.307699  12.967960  24.010106  151.28  70.367299```

```port_returns = []
port_volatility = []
stock_weights = []

num_assets = len(selected)
num_portfolios = 50000

for single_portfolio in range(num_portfolios):
weights = np.random.random(num_assets)
weights /= np.sum(weights)
returns = np.dot(weights, returns_annual)
volatility = np.sqrt(np.dot(weights.T, np.dot(cov_annual, weights)))
port_returns.append(returns)
port_volatility.append(volatility)
stock_weights.append(weights)

portfolio = {'Returns': port_returns,
'Volatility': port_volatility}

and weight in the portfolio
for counter,symbol in enumerate(selected):
portfolio[symbol+' weight'] = [weight[counter] for weight in stock_weights]

df = pd.DataFrame(portfolio)

column_order = ['Returns', 'Volatility'] + [stock+' weight' for stock in selected]
df = df[column_order]
```Returns    Volatility  CNP weight  F weight  WMT weight  GE weight  TSLA weight
0  0.051471  0.139810  0.193275  0.144265  0.286315  0.037991  0.338155
1  0.098057  0.205745  0.001220  0.192939  0.271552  0.359363  0.174927
2  0.042783  0.160203  0.281532  0.442986  0.164275  0.022419  0.088788
3  0.090758  0.199514  0.113044  0.344052  0.238166  0.293816  0.010922
4  0.053179  0.159999  0.212643  0.283324  0.015256  0.168772  0.320006```

```import quandl
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

quandl.ApiConfig.api_key = 'INSERT YOUR API KEY HERE'
selected = ['CNP', 'F', 'WMT', 'GE', 'TSLA']
data = quandl.get_table('WIKI/PRICES', ticker = selected,
qopts = { 'columns': ['date', 'ticker', 'adj_close'] },
date = { 'gte': '2014-1-1', 'lte': '2016-12-31' }, paginate=True)

clean = data.set_index('date')
table = clean.pivot(columns='ticker')

returns_daily = table.pct_change()
returns_annual = returns_daily.mean() * 250

cov_daily = returns_daily.cov()
cov_annual = cov_daily * 250

port_returns = []
port_volatility = []
sharpe_ratio = []
stock_weights = []

num_assets = len(selected)
num_portfolios = 50000

np.random.seed(101)

for single_portfolio in range(num_portfolios):
weights = np.random.random(num_assets)
weights /= np.sum(weights)
returns = np.dot(weights, returns_annual)
volatility = np.sqrt(np.dot(weights.T, np.dot(cov_annual, weights)))
sharpe = returns / volatility
sharpe_ratio.append(sharpe)
port_returns.append(returns)
port_volatility.append(volatility)
stock_weights.append(weights)

portfolio = {'Returns': port_returns,
'Volatility': port_volatility,
'Sharpe Ratio': sharpe_ratio}

for counter,symbol in enumerate(selected):
portfolio[symbol+' Weight'] = [Weight[counter] for Weight in stock_weights]

df = pd.DataFrame(portfolio)

column_order = ['Returns', 'Volatility', 'Sharpe Ratio'] + [stock+' Weight' for stock in selected]

df = df[column_order]

plt.style.use('seaborn-dark')
df.plot.scatter(x='Volatility', y='Returns', c='Sharpe Ratio',
cmap='RdYlGn', edgecolors='black', figsize=(10, 8), grid=True)
plt.xlabel('Volatility (Std. Deviation)')
plt.ylabel('Expected Returns')
plt.title('Efficient Frontier')
plt.show()```

```min_volatility = df['Volatility'].min()
max_sharpe = df['Sharpe Ratio'].max()

sharpe_portfolio = df.loc[df['Sharpe Ratio'] == max_sharpe]
min_variance_port = df.loc[df['Volatility'] == min_volatility]

plt.style.use('seaborn-dark')
df.plot.scatter(x='Volatility', y='Returns', c='Sharpe Ratio',
cmap='RdYlGn', edgecolors='black', figsize=(10, 8), grid=True)
plt.scatter(x=sharpe_portfolio['Volatility'], y=sharpe_portfolio['Returns'], c='red', marker='D', s=200)
plt.scatter(x=min_variance_port['Volatility'], y=min_variance_port['Returns'], c='blue', marker='D', s=200 )
plt.xlabel('Volatility (Std. Deviation)')
plt.ylabel('Expected Returns')
plt.title('Efficient Frontier')
plt.show()```

```print(min_variance_port.T)
print(sharpe_portfolio.T)

17879
Returns    0.045828
Volatility  0.138552
Sharpe Ratio  0.330761
CNP Weight  0.240327
F Weight  0.104659
WMT Weight  0.257760
GE Weight  0.001487
TSLA Weight  0.395767

31209
Returns      0.116145
Volatility    0.175045
Sharpe Ratio    0.663514
CNP Weight    0.372890
F Weight    0.008482
WMT Weight    0.404987
GE Weight    0.211450
TSLA Weight    0.002190```

0 条评论

相关文章

605260

安恒信息两篇核心AI异常检测论文入选IEEE DSC国际会议

6月18日-21日，“第三届IEEE网络空间数据科学国际会议”在广州召开。业界代表及专家齐聚一堂，并就网络空间数据科学的科研和前沿发展方向进行交流。而安恒信息的...

22640

麦克阿瑟天才奖得主解码计算机视觉“原罪”：AI 如何认识人类世界

【新智元导读】麦克阿瑟“天才奖”获得者Trevor Paglen训练AI算法，他的展览项目“看不见的图像的研究”（A Study of Invisible Im...

37770

18530

13820

20050

ACL 2016：基于深度学习的 NLP 看点

【新智元导读】计算语言领域顶级会议ACL2016今天公布了10篇优秀论文（outstanding paper）名单。本文介绍 ACL 2016 概况，同时收录清...

53160

以科学的方式赤裸裸地剖析AI

（作者：洪小文，现任微软全球资深副总裁，微软亚太研发集团主席兼微软亚洲研究院院长，全面负责推动微软在亚太地区的科研及产品开发战略，以及与中国及亚太地区学术界的合...

20190

31680