problem2.zip

  • Tju-wang
    了解作者
  • Perl
    开发工具
  • 2KB
    文件大小
  • zip
    文件格式
  • 0
    收藏次数
  • 1 积分
    下载积分
  • 0
    下载次数
  • 2019-06-27 09:52
    上传日期
基于python实现的Markowitz均值方差理论优化
problem2.zip
  • problem2.py
    6.6KB
内容介绍
# -*- coding: utf-8 -*- """ Created on Sat Jun 15 16:38:01 2019 @author: Hasee """ import numpy as np import pandas as pd import matplotlib.pyplot as plt import scipy.optimize as sco #**************************************obtain the mean- variance optimal************************# #data input data = pd.read_excel('stock_price_return.xlsx') data.index = data['Date'].tolist() data.pop('Date') prices = data.drop(data.columns[range(21,42)], axis=1) prices.drop(prices._stat_axis[range(192,245)], axis=0,inplace=True) #prices is the Adj Close data from 1999,1,1 to 2014,12,1. returns = data.drop(data.columns[range(0,21)], axis=1) returns.drop(returns._stat_axis[range(192,245)], axis=0,inplace=True) #returns is the Return data from 1999,1,1 to 2014,12,1. rate_return = returns #define monthly rate of return assets_num = 21#we have 21 assets #According to the weight, calculate the return rate/volatility/sharpe ratio of the portfolio def calculator(weights): weights = np.array(weights) pret = np.sum(rate_return.mean() * weights) #Portfolio return pvol = np.sqrt(np.dot(weights.T, np.dot(rate_return.cov() , weights))) #Portfolio volatility or standard deviation return np.array([pret, pvol, pret / pvol]) def calculate_variance(weights): #from standard deviation to variance return calculator(weights)[1] ** 2 #find the minimum-variance portfolios weights_y = np.array([1/21]*21) expected_return = calculator(weights_y)[0] #set the expected return of x equal to return of y bnds = tuple((0, 1) for x in range(assets_num)) #each weights is in the range of (0,1) cons = ({'type': 'eq', 'fun': lambda x: calculator(x)[0] - expected_return},{'type': 'eq', 'fun': lambda x: np.sum(x) - 1}) #The target rate of return is the weight multiplied by each return rate. the constraint is the sum of weights is 1. optv = sco.minimize(calculate_variance, assets_num * [1. / assets_num,], method='SLSQP', bounds=bnds, constraints=cons) #deal with minimizing variance #find the efficient frontier def calculate_pvol(weights): return calculator(weights)[1] target_returns = np.linspace(0.004, 0.021, 17) # Target rate of return target_volatilities = [] for tret in target_returns: #to find the efficient frontier, we have to find the minimum varience point under different expected return. cons = ({'type': 'eq', 'fun': lambda x: calculator(x)[0] - tret}, {'type': 'eq', 'fun': lambda x: np.sum(x) - 1}) res = sco.minimize(calculate_pvol, assets_num * [1. / assets_num,], method='SLSQP', bounds=bnds, constraints=cons) target_volatilities.append(res['fun']) #Draw a scatter diagram plt.figure(figsize=(5, 3)) portfolio_returns = [] portfolio_volatilities = [] for p in range (5000):#describe the returns and volatility of 5000 random portfolios by scatter plot weights = np.random.random(assets_num) weights /= np.sum(weights) portfolio_returns.append(np.sum(rate_return.mean() * weights) ) portfolio_volatilities.append(np.sqrt(np.dot(weights.T,np.dot(rate_return.cov() , weights)))) portfolio_returns = np.array(portfolio_returns) portfolio_volatilities = np.array(portfolio_volatilities) plt.scatter(portfolio_volatilities, portfolio_returns, c=portfolio_returns / portfolio_volatilities, marker='o')#The dots are random portfolios plt.scatter(target_volatilities, target_returns, c=target_returns / target_volatilities, marker='x') #The cross is the efficient frontier plt.plot(calculator(optv['x'])[1], calculator(optv['x'])[0],'y*', markersize=15.0) #Yellow star is the portfolio with the minimum variance plt.plot(calculator(weights_y)[1], calculator(weights_y)[0],'yD', markersize=10.0) #Yellow diamond is the portfolio with the equal weight plt.grid(True) plt.axis([0.02,0.10,0.00,0.03]) plt.xlabel('expected volatility') plt.ylabel('expected return') plt.colorbar(label='Sharpe ratio') #*************Compute the mean value and the standard deviation of the monthly returns of portfolios x and y before 2015***************# print('From 1999,1,1 to 2014,12,1, the mean value of x is %lf , the standard deviation of x is %lf' %(calculator(optv['x'])[0],calculator(optv['x'])[1])) print('From 1999,1,1 to 2014,12,1, the mean value of y is %lf , the standard deviation of y is %lf' %(calculator(weights_y)[0],calculator(weights_y)[1])) #*************Compute the mean value and the standard deviation of the 53 monthly returns of portfolios x***************# returns_2 = data.drop(data.columns[range(0,21)], axis=1) returns_2.drop(returns_2._stat_axis[range(0,192)], axis=0,inplace=True) #returns_2 is the Return data from 2015,1,1 to 2019,5,1. return_x = [] for i in range (53): return_x.append(np.sum(returns_2.iloc[i,:] * optv['x'])) return_x = np.array(return_x) return_x_mean = np.mean(return_x) return_x_std = np.std(return_x,ddof=1) print('From 2015,1,1 to 2019,5,1, the mean value of x is %lf , the standard deviation of x is %lf' %(return_x_mean,return_x_std)) #*************Compute the mean value and the standard deviation of the 53 monthly returns of portfolios y***************# weights_y = np.array([1/21]*21) return_y = [] for i in range (53): return_y.append(np.sum(returns_2.iloc[i,:] * weights_y)) return_y = np.array(return_y) return_y_mean = np.mean(return_y) return_y_std = np.std(return_y,ddof=1) print('From 2015,1,1 to 2019,5,1, the mean value of y is %lf , the standard deviation of y is %lf' %(return_y_mean,return_y_std)) #*************Compute the Sharpe ratio of the 53 monthly returns of portfolios x and y***************# rf = 0.05/12 #set the risk_free rate is 5%,so the monthly rate is 5%/12 sharp_x = (return_x_mean -rf)/return_x_std sharp_y = (return_y_mean -rf)/return_y_std print('From 2015,1,1 to 2019,5,1, the sharpe ratio of x is %lf , the sharpe ratio of y is %lf' %(sharp_x,sharp_y)) ''' #*****plot the diagram of x and y to see the performance M= range(1,54) plt.plot(M,return_x,label='return of x') plt.plot(M,return_y,label='return of y') plt.xlabel('month since Jan 2015') plt.ylabel('return') plt.legend(('return of x', 'return of y')) plt.show() ''' ''' #*****plot the present value of x and y to see the performance M= range(1,54) pv_x = [] pv_x.append(1000000*(1+return_x[0])) for i in range (1,53): pv_x.append(pv_x[i-1]*(1+return_x[i])) pv_y = [] pv_y.append(1000000*(1+return_y[0])) for i in range (1,53): pv_y.append(pv_y[i-1]*(1+return_y[i])) plt.plot(M,pv_x,label='present value of x') plt.plot(M,pv_y,label='present value of y') plt.xlabel('month since Jan 2015') plt.ylabel('present value') plt.legend(('present value of x', 'present value of y')) plt.show() '''
评论
    相关推荐
    • StockMarkNetIndicator:“网络几何和市场不稳定”的存储库
      mst_wt.py:Python脚本,用于从互相关值的加权网络中生成加权或未加权的已过滤最小生成树+阈值网络。 当da常数大于1(稀疏状态)时,在pn = d / n方案中,Erdös-Renyi随机图G(n,pn)的分量具有零频谱间隙,即n→...
    • PortOpt:使用Markowitz(1952)均值方差模型的投资组合优化器-开源
      PortOpt [Portfolio Optimizer]是一个C ++程序(具有Python绑定),实现了Markowitz(1952)平均方差模型,该模型具有针对风险的代理线性无差异曲线,以便找到处于风险中的最优资产组合。 您必须提供PortOpt(在文本...
    • Advances in Financial Machine Learning
      Machine learning (ML) is changing virtually every aspect of our lives. Today ML algorithms accomplish tasks that until recently only expert humans could perform. As it relates to finance, this is the ...
    • Advances in Financial Machine Learning
      Advances in Financial Machine Learning By 作者: Marcos Lopez de Prado ISBN-10 书号: 1119482089 ISBN-13 书号: 9781119482086 Edition 版本: 1 出版日期: 2018-02-21 pages 页数: (400) $50 ...
    • MATLAB用拟合出的代码绘图-University-Projects:大学项目
      该项目的这一部分专注于MNIST数据的分类,使用python中的Keras包,使用40000个训练图像和10000个图像进行测试。 该过程涉及使用不同的网络体系结构预处理数据,以及优化超参数以获得最高的测试精度。 使用Tensorflow...
    • markerwitz:COS 583(计算中的伟大时刻)的最终项目
      这是 Dale Markowitz 和 Shubhro Saha 在普林斯顿大学为 COS 583(计算中的伟大时刻)完成的最终项目。 安装 安装 Python/OpenCV 安装并确保websocketd在PATH 用法 运行./markerwitz.sh 监控进程: ps axu | grep...
    • Hands-on-Python-for-Finance:Packt发行的Python实用金融
      以下各章将帮助您了解如何衡量投资组合的可分散和不可分散的安全风险,以及如何通过实施Markowitz投资组合优化来优化您的投资组合。 回归分析方法论部分将帮助您评估资产并了解商品价格与商业库存之间的关系。 除此...
    • portfolio-optimization
      用RL进行实验以建立3只股票的最优投资组合,并将其与基于Markowitz方法的投资组合理论进行比较 请检出中篇以快速浏览。 训练RL模型: python train.py 问题陈述 我将其表达为一个投资组合优化问题:考虑到3种不同...
    • Modelo-para-aloca-o-de-ativos-baseado-na-perda-m-xima-tolerada-t
      Modelo paraalocaçãode ativos baseado na perdamáximatolerada-Trabalho deConclusãode Curso。 在UFRJ校园的Macaé州,最热门的Jugenter记事本(TCC_...在Jupyter Lab实施了无条件的Python开发,使用了Python
    • android从bootloader到launcher启动流程整理
      讲述android 开机流程 从boot rom---bootloader---init--zygote---systemserver---ams 并附上自己整理的每个流程的流程图 ,清晰熟悉android 启动流程