manbet体育手机客户端


portfolio.py


# !/usr/bin/env python3.7 #版权所有2019,Gurobi O狗万app足彩ptimization, LLC我们的方法源于Markowitz(1959),在实现预期收益目标的同时最小化与投资相关的风险。通过改变目标,#可以计算出“有效边界”,它定义了给定预期收益的最佳投资组合#。# #注意这个例子从一个以逗号分隔的#文件(../data/portfolio.csv)读取历史数据。因此,它必须在Gurobi # examples/python目录下运行。# #这个例子需要pandas (>= 0.20.3), NumPy和Matplotlib # Python包,它们是# mathematics, science, and engineering的SciPy生态系统的一部分(http://scipy.org)。这些#包并不包含在所有Python发行版中,但是默认情况下在Anaconda Python中包含了#包。import gurobipy as gp from gurobipy import GRB from math import sqrt import pandas as pd import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib。使用pandas data = pd.read_csv('../data/portfolio.csv', index_col=0) stocks = data. csv('../data/portfolio.csv', index_col=0)列#计算个人股票的基本汇总统计信息stock_volatility = data.std() stock_return = data.mean() #创建一个空模型m = gp.Model('portfolio') #为每个股票添加一个变量vars = pd.Series(m.d addvars (stocks), index=stocks) #目标是最小化风险(平方)。 This is modeled using the # covariance matrix, which measures the historical correlation between stocks. sigma = data.cov() portfolio_risk = sigma.dot(vars).dot(vars) m.setObjective(portfolio_risk, GRB.MINIMIZE) # Fix budget with a constraint m.addConstr(vars.sum() == 1, 'budget') # Optimize model to find the minimum risk portfolio m.setParam('OutputFlag', 0) m.optimize() # Create an expression representing the expected return for the portfolio portfolio_return = stock_return.dot(vars) # Display minimum risk portfolio print('Minimum Risk Portfolio:\n') for v in vars: if v.x > 0: print('\t%s\t: %g' % (v.varname, v.x)) minrisk_volatility = sqrt(portfolio_risk.getValue()) print('\nVolatility = %g' % minrisk_volatility) minrisk_return = portfolio_return.getValue() print('Expected Return = %g' % minrisk_return) # Add (redundant) target return constraint target = m.addConstr(portfolio_return == minrisk_return, 'target') # Solve for efficient frontier by varying target return frontier = pd.Series() for r in np.linspace(stock_return.min(), stock_return.max(), 100): target.rhs = r m.optimize() frontier.loc[sqrt(portfolio_risk.getValue())] = r # Plot volatility versus expected return for individual stocks ax = plt.gca() ax.scatter(x=stock_volatility, y=stock_return, color='Blue', label='Individual Stocks') for i, stock in enumerate(stocks): ax.annotate(stock, (stock_volatility[i], stock_return[i])) # Plot volatility versus expected return for minimum risk portfolio ax.scatter(x=minrisk_volatility, y=minrisk_return, color='DarkGreen') ax.annotate('Minimum\nRisk\nPortfolio', (minrisk_volatility, minrisk_return), horizontalalignment='right') # Plot efficient frontier frontier.plot(color='DarkGreen', label='Efficient Frontier', ax=ax) # Format and display the final plot ax.axis([0.005, 0.06, -0.02, 0.025]) ax.set_xlabel('Volatility (standard deviation)') ax.set_ylabel('Expected Return') ax.legend() ax.grid() plt.savefig('portfolio.png') print("Plotted efficient frontier to 'portfolio.png'")