习题4.3

习题4.3代码

import cvxpy as cp
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['Times New Roman + SimSun + WFM Sans SC']
plt.rcParams['mathtext.fontset']='stix'

Times New Roman + SimSun + WFM Sans SC

simsum宋体, times new roman -*, simhei黑体, kaiti楷体,

dengxian等线, fangsong仿宋, Microsoft Yahei微软雅黑

plt.rcParams['axes.unicode_minus']=False
plt.rcParams['figure.dpi'] = 200

plt.rcParams['figure.figsize'] = [4, 3]

plt.rcParams['font.size'] = 12

plt.rcParams['xtick.direction']='in'
plt.rcParams['ytick.direction']='in'
r = np.array([5, 28, 21, 23, 25])/100
q = np.array([0, 2.5, 1.5, 5.5, 2.6])/100
p = np.array([0, 1, 2, 4.5, 6.5])/100
u = np.array([0, 103, 198, 52, 40])
M = 1e4

x = cp.Variable(6, pos=True)
obj = cp.Minimize(x[-1])
k = 0.05
kk = []
P = []
X = []
while k < 0.27:
kk.append(k)
cons = [
cp.multiply(q[1:5], x[1:5]) <= x[-1],
(r-p) @ x[:-1] >= k*M,
(1+p) @ x[:-1] == M
]
prob = cp.Problem(obj, cons)
prob.solve(solver='GLPK_MI')
P.append(prob.value)
X.append(x.value)
k += 0.005
X = np.array(X)
fig = plt.figure(figsize=[6,2.5], dpi=500)
ax = fig.add_subplot(121)
ax.plot(kk, P, 'm', linewidth=3)
ax.grid(linestyle='😂
ax.set_xlabel('Profit degree')
ax.set_ylabel('Risk')
ax1 = fig.add_subplot(122)
for i in range(5):
ax1.plot(kk, (X.T)[i], label=f'$s_{i}$')
ax1.set_xlabel('Profit degree')
ax1.set_ylabel('Investment', labelpad=0)
ax1.legend(fontsize=7)
ax1.grid(linestyle='😂

fig.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0.35, hspace=None)
fig.show()

posted @ 2024-10-22 12:57  等我刷把宗师  阅读(3)  评论(0编辑  收藏  举报