最优投资组合构建问题,Python实现
本文记录在可投资集已知预期收益率和预期协方差矩阵的条件下,使用程序工具求解最优投资组合的方法。
问题描述
构建最优投资组合是一个带约束的优化问题,优化目标是最大化投资组合的夏普比率,而约束是资产权重相加等于1。
Python实现
# construct optimized portfolioimport numpy as npimport pandas as pdimport scipy.optimize as sco
fcst_style_sharpe = pd.read_csv('fcst_style_sharpe.csv')style_cov = pd.read_csv('style_cov.csv')
selected_col = ['mkt','smb','hml','vmg','rmw','gms','pmo','mom']noa = len(selected_col)
style_ret = fcst_style_sharpe['fcst_ret'] #* 100
weights = np.random.random(noa)weights /= np.sum(weights)
def port_ret(weights): return np.sum(style_ret * weights) * 252
def port_vol(weights): return np.sqrt(np.dot(weights.T, np.dot(style_cov * 252, weights)))
def min_func_sharpe(weights): return -port_ret(weights) / port_vol(weights)
# maximize sharpe ratioeweights = np.array(noa * [1. / noa,])#bnds = tuple((0, 1) for x in range(noa))bnds = tuple((-2, 2) for x in range(noa))cons = ({'type': 'eq', 'fun': lambda x: np.sum(x) - 1})
opts = sco.minimize(min_func_sharpe, eweights, method='SLSQP', bounds=bnds, constraints=cons)
opt_weight = opts['x']opt_weight.round(4)
opts_sharpe = port_ret(opt_weight) / port_vol(opt_weight)opts_sharpe
# plot the optimized portfoliofrom lets_plot import *LetsPlot.setup_html()
fzoo = pd.read_csv('data/fzoo.csv')
opt_style = fzoo[['trading_date','mkt']].copy()opt_style.columns = ['trading_date','style']opt_style['style'] = np.dot(fzoo[selected_col],opt_weight)opt_style['style_cum'] = np.log1p(opt_style['style']/100).cumsum()
x = pd.to_datetime(opt_style['trading_date'])[-1000:]y = opt_style['style_cum'][-1000:]/opt_style['style_cum'].iloc[-1000]ggplot({'date': x, 'port': y}, aes(x='date', y='port')) + geom_line()
# minimize volatilityoptv = sco.minimize(port_vol, eweights, method='SLSQP', bounds=bnds, constraints=cons)
bnds = tuple((0, 1) for x in weights)
cons = ({'type': 'eq', 'fun': lambda x: port_ret(x) - tret}, {'type': 'eq', 'fun': lambda x: np.sum(x) - 1})
%timetrets = np.linspace(0.05, 0.5, 100)tvols = []for tret in trets: res = sco.minimize(port_vol, eweights, method='SLSQP', bounds=bnds, constraints=cons) tvols.append(res['fun'])tvols = np.array(tvols)
# plot the frontfrom pylab import mpl, pltplt.style.use('seaborn-v0_8-whitegrid')mpl.rcParams['font.family'] = 'serif'%matplotlib inline
prets = []pvols = []for p in range (5000): weights = np.random.random(noa) weights /= np.sum(weights) prets.append(port_ret(weights)) pvols.append(port_vol(weights))prets = np.array(prets)pvols = np.array(pvols)
plt.figure(figsize=(10, 6))plt.scatter(pvols, prets, c=prets / pvols, marker='o', cmap='coolwarm')plt.xlabel('expected volatility')plt.ylabel('expected return')plt.colorbar(label='Sharpe ratio');
tvols = np.array(tvols)
plt.figure(figsize=(10, 6))plt.scatter(pvols, prets, c=prets / pvols, marker='.', alpha=0.8, cmap='coolwarm')plt.plot(tvols, trets, 'b', lw=4.0)plt.plot(port_vol(opts['x']), port_ret(opts['x']), 'y*', markersize=15.0)plt.plot(port_vol(optv['x']), port_ret(optv['x']), 'r*', markersize=15.0)plt.xlabel('expected volatility')plt.ylabel('expected return')plt.colorbar(label='Sharpe ratio')
本文由 mdnice 多平台发布
最优投资组合构建问题,Python实现相关推荐
- 数学建模债券投资组合_最优投资组合问题的数学模型
最优投资组合问题的数学模型 李成博①LI Cheng -bo :宓颖②MI Ying:衣国洋③YI Guo -xiang :黄小宇 ①HUANG Xiao -yu [摘 要] 摘要:本文研究的是投资者 ...
- 有效前沿和最优投资组合matlab,matlab 实验名称:投资组合分析
实验性质:综合性和研究探索性
实 联合开发网 - pudn.com...
matlab 所属分类:matlab例程 开发工具:matlab 文件大小:5918KB 下载次数:30 上传日期:2017-12-27 13:31:24 上 传 者:waffle 说明: 实验名称 ...
- matlab套利,期现套利-现货组合构建(1)-市值权重法
本帖最后由 faruto 于 2011-12-27 23:58 编辑 期现套利-现货组合构建(1)-市值权重法 最近抽空做的一点东西,常见的期现套利现货构建的方法之1--市值权重法. 一直想把跟踪指数 ...
- 通过前序遍历和中序遍历构建二叉树 python实现
前言 通过前序遍历和中序遍历构建二叉树的原理,主要是找前序遍历根节点在中序遍历中的位置,然后将二叉树而成左子树和右子树,然后依次进行这样的操作,思路还是比较简单的 代码 class Node:def ...
- 文档扫描仪的构建——使用Python,OpenCV应用透视变换来获得图像的自顶向下的“鸟瞰图”
使用Python,OpenCV应用透视变换来获得图像的自顶向下的"鸟瞰图" 1. 效果图 2. 应用透视变换的步骤 3. 优化:矩形角点的获取 4. 源码 参考 这篇博客演示了如何 ...
- python列表两两组合_关于python:两个列表之间的组合?
已经有一段时间了,我很难用我正在尝试的算法来概括我的想法.基本上,我有两个列表,想要得到这两个列表的所有组合. 我可能解释不正确,所以这里举个例子. name = 'a', 'b' number = ...
- 高效构建基于Python的商品评论文本挖掘网页APP
CDA数据分析师 出品 作者:CDALevel Ⅰ持证人 岗位:数据分析师 行业:大数据 背景 电子商务行业在近几年发展得极为迅猛,很多在传统行业就业但是薪资不理想的都在网电子商务行业去转.这种趋势造 ...
- [ LeetCode ] #17. Letter Combinations of a Phone Number(电话按键组合字符 C++ Python)
题目:17. Letter Combinations of a Phone Number Difficulty: Medium Given a string containing digits fro ...
- 如何构建基于Python的星座脚本
您可能已经听说过Python,这是一种交互式编程语言,可轻松处理数据. 如今,它已用于从网站和应用程序到统计,机器学习和AI的所有内容. 使用Python,编写代码很简单,但是创建一个真正有用的程序需 ...
最新文章
- SBB:长期施肥降低了控制土壤微生物群落演替的随机性
- html语义化面试题,前端面试题-HTML结构语义化
- ulimit限制 新系统_系统限制ulimit学习
- 虚基类(c++细节篇七)
- order by + 数字的用意
- extjs 关于dom操作的几个库
- linux+读取初始化文件,Linux 初始化系统 SystemV Upstart
- python随机产生手机号码
- 实用的Chrome插件推荐
- 梅科尔工作室-OpenEuler培训第二讲笔记
- 【模糊回归预测】基于matlab萤火虫算法优化模糊神经网络回归预测【含Matlab源码 2034期】
- 复杂字云简单做,随时做好装逼的准备
- 【实践】haskell、coq基本语法
- C++PTA习题总结(三)
- linux操作系统的7种运行级别的详细说明
- 金鸽BL102,无需编程可直接对接Thingsboard平台
- python爬虫小项目: 爬取百度贴吧帖子
- Perl 脚本运行时提示:Can‘t locate Win32/OLE.pm in @INC
- 超碰网站源码搭建教程超碰在线视频搭建超碰网站搭建教程
- linux cp目录到指定目录,linux复制指定目录下的全部文件到另一个目录中,linux cp 文件夹...