Заболотников_9373_ПР3
.pdfПРИЛОЖЕНИЕ А.
КОД ПРОГРАММЫ (PYTHON)
import pandas as pd import numpy as np from math import sqrt
from cvxopt import matrix from cvxopt.blas import dot from cvxopt.solvers import qp
from matplotlib import pyplot as plt stocks = ['GAZP_210101_211231.csv',
'RASP_210101_211231.csv', 'SBER_210101_211231.csv', 'SNGS_210101_211231.csv', 'YNDX_210101_211231.csv']
variations = []
total_g = [0, 0, 0, 0, 0] total_r = [0, 0, 0, 0, 0] i = 0
for filename in stocks:
df = pd.read_csv(filename)
Dm_i = (df['<CLOSE>'].shift(-1) / df['<CLOSE>'] - 1).dropna() for j in range(253):
total_g[i] += Dm_i.iloc[j] total_g[i] *= 100
total_r[i] = np.var(Dm_i) i += 1
variations.append((df['<CLOSE>'].shift(-1) / df['<CLOSE>'] - 1).dropna().values.reshape(1, -1))
variations = np.concatenate(variations, axis = 0) C = np.cov(variations)
A = matrix([[1.0, 1.0, 1.0, 1.0, 1.0],
[total_g[0], total_g[1], total_g[2], total_g[3], total_g[4]]]) G = matrix([[1.0, 0.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0, 1.0],
11
[-1.0, 0.0, 0.0, 0.0, 0.0], [0.0, -1.0, 0.0, 0.0, 0.0], [0.0, 0.0, -1.0, 0.0, 0.0], [0.0, 0.0, 0.0, -1.0, 0.0], [0.0, 0.0, 0.0, 0.0, -1.0]])
h = matrix([[0.5], [0.5], [0.5], [0.5], [0.5], [0.0], [0.0], [0.0], [0.0], [0.0]])
P = matrix(C)
Ps = np.zeros((5, 5)) j = 0
for k in range(5):
for l in range(5): Ps[k][l] = P[j] j += 1
ttl = matrix([0.0, 0.0, 0.0, 0.0, 0.0], tc = 'd') profits = matrix(0.0, (1, 99))
risks = matrix(0.0, (1, 99)) ports = np.zeros((99, 5)) for i in range(99):
profits[i] = profits[i] + (17 + 0.05 * i) for i in range(99):
b = matrix([[1.0], [profits[i]]])
portfolios = qp(2 * P, ttl, G.T, h.T, A.T, b.T)['x'] for j in range(5):
ports[i][j] = portfolios[j] for m in range(5):
for n in range(5):
prod = Ps[m][n] * portfolios[m] * portfolios[n] risks[i] += prod
for i in range(99):
12
print("Портфель: ", ports[i][:]) print("Доходность: ", profits[i])
X = np.zeros(99)
Y = np.zeros(99)
for i in range(99): X[i] = profits[i] Y[i] = risks[i]
plt.figure(figsize = (10, 8)) plt.scatter(X, Y)
plt.show()
13