PyPortfolioOpt入门

来源:https://pypi.org/project/pyportfolioopt/

PyPortfolioOpt是一个实现投资组合优化方法的库,其中包括经典的均值方差优化技术和Black-Litterman资产配置模型,以及该领域的最新进展,例如收缩率shrinkage和层次风险平价模型Hierarchical Risk Parity,以及一些新颖的实验功能,例如指数加权协方差矩阵。

它既广泛又易于扩展,对于临时投资者和认真的从业者都可能有用。无论您是发现了一些被低估的精选期权的基础知识型投资者,还是拥有一篮子策略的算法交易者,PyPortfolioOpt都可以帮助您以风险有效的方式构建自己的Alpha组合。

安装


pip安装

pip install PyPortfolioOpt

源码安装

git clone https://github.com/robertmartin8/PyPortfolioOpt
python setup.py install

例子


这是一个关于现实中的股票数据的示例,通过最大化夏普比率(衡量风险调整后回报)构建多头投资组合。


import pandas as pd
from pypfopt import EfficientFrontier
from pypfopt import risk_models
from pypfopt import expected_returns

# Read in price data
df = pd.read_csv("tests/resources/stock_prices.csv", parse_dates=True, index_col="date")
# Calculate expected returns收益率 and sample covariance样本协方差
mu = expected_returns.mean_historical_return(df)
S = risk_models.sample_cov(df)

# Optimize for maximal Sharpe ratio
ef = EfficientFrontier(mu, S)
raw_weights = ef.max_sharpe()
cleaned_weights = ef.clean_weights()
ef.save_weights_to_file("weights.csv")  

# saves to file
print(cleaned_weights)
ef.portfolio_performance(verbose=True)

输出结果:

{'GOOG': 0.01269,
 'AAPL': 0.09202,
 'FB': 0.19856,
 'BABA': 0.09642,
 'AMZN': 0.07158,
 'GE': 0.0,
 'AMD': 0.0,
 'WMT': 0.0,
 'BAC': 0.0,
 'GM': 0.0,
 'T': 0.0,
 'UAA': 0.0,
 'SHLD': 0.0,
 'XOM': 0.0,
 'RRC': 0.0,
 'BBY': 0.06129,
 'MA': 0.24562,
 'PFE': 0.18413,
 'JPM': 0.0,
 'SBUX': 0.03769}

Expected annual return: 33.0%
Annual volatility: 21.7%
Sharpe Ratio: 1.43

这里最大夏普对应的点实际上就是无风险收益点与有效前沿的切线的切点位置:


image.png

同时,我们也可以将上面的权重配比兑换为实际的购买金额:

from pypfopt.discrete_allocation import DiscreteAllocation, get_latest_prices


latest_prices = get_latest_prices(df)

da = DiscreteAllocation(weights, latest_prices, total_portfolio_value=10000)
allocation, leftover = da.lp_portfolio()
print("Discrete allocation:", allocation)
print("Funds remaining: ${:.2f}".format(leftover))
11 out of 20 tickers were removed
Discrete allocation: {'GOOG': 0, 'AAPL': 5, 'FB': 11, 'BABA': 5, 'AMZN': 1,
                      'BBY': 7, 'MA': 14, 'PFE': 50, 'SBUX': 5}
Funds remaining: $8.42

*免责声明:关于该项目的任何内容均不构成投资建议,作者对您的后续投资决定不承担任何责任。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容