portfolio.py


# !/usr/bin/env python3.7版权2023,Gurobi Optim狗万app足彩ization, LLC #投资组合选择:给定一笔资金进行投资,一个人必须决定如何在金融证券投资组合中使用它。我们的方法是由于马科维茨(1959),并寻求在实现目标预期回报的同时最小化与投资相关的风险。通过改变目标,人们可以计算出一个“有效边界”,它定义了给定预期收益的最佳投资组合。注意,这个例子从逗号分隔的#文件(../data/portfolio.csv)中读取历史返回数据。因此,它必须在Gurobi # examples/python目录下运行。这个例子需要pandas(>= 0.20.3)、NumPy和Matplotlib # Python包,它们是用于#数学、科学和工程(http://scipy.org)的SciPy生态系统的一部分。这些#包并不包含在所有的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导入(归一化)历史收益数据。列#计算个股的基本汇总统计stock_volatility = data.std() stock_return = data.mean() #创建一个空模型m = gp.Model('portfolio') #为每只股票添加一个变量vars = pd.Series(m.d addvars(股票),index=股票)#目标是最小化风险(平方)。 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(dtype=np.float64) 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'")