# 出典: mo-notebooks/06/markowitz_portfolio_revisited.ipynb

# %%
# install dependencies and select solver

SOLVER_CONIC = "mosek"  # ipopt, mosek, gurobi, knitro

from amplpy import AMPL, ampl_notebook

ampl = ampl_notebook(
    modules=["coin", "mosek"],  # modules to install
    license_uuid="default",  # license to use
)  # instantiate AMPL object and register notebook magics

# %%
from IPython.display import Markdown, HTML
import numpy as np
import matplotlib.pyplot as plt

# %%
# Specify the initial capital, the risk tolerance, and the guaranteed return rate.
C = 1
alpha = 0.1
R = 1.05

# Specify the number of assets, their expected return, and their covariance matrix.
n = 3
mu = np.array([1.25, 1.15, 1.35])
Sigma = np.array([[1.5, 0.5, 2], [0.5, 2, 0], [2, 0, 5]])

# If you want to change the covariance matrix Sigma, ensure you input a semi-definite positive one.
# The easiest way to generate a random covariance matrix is first generating a random m x m matrix A
# and then taking the matrix A^T A (which is always semi-definite positive)
# m = 3
# A = np.random.rand(m, m)
# Sigma = A.T @ A
#
# Moreover, in practive such a matrix A, called factor, can be low-rank,
# see https://docs.mosek.com/modeling-cookbook/qcqo.html#example-factor-model.
# This would provide better numerical properties for the proper conic formulation
#        y=Ax, |y|^2 <= s,
# corresponding to the mathematical formulation above.


def markowitz_revisited(alpha, mu, Sigma):
    ampl = AMPL()
    ampl.read("markowitz_portfolio_revisited.mod")

    ampl.param["C"] = C
    ampl.param["alpha"] = alpha
    ampl.param["R"] = R

    ampl.param["n"] = n
    ampl.param["mu"] = mu
    ampl.param["Sigma"] = {
        (i + 1, j + 1): Sigma[i][j] for i in range(n) for j in range(n)
    }

    ampl.solve(solver=SOLVER_CONIC)
    assert ampl.solve_result == "solved", ampl.solve_result

    return ampl


ampl = markowitz_revisited(alpha, mu, Sigma)
xtilde = ampl.get_variable("xtilde").value()
x = ampl.get_variable("x").to_dict()

display(Markdown(f"**Solver status:** *{ampl.solve_result}*"))
display(
    Markdown(
        f"**Solution:** $\\tilde x = {xtilde:.3f}$"
        f"              $x_1 = {x[1]:.3f}$,  $x_2 = {x[2]:.3f}$,  $x_3 = {x[3]:.3f}$"
    )
)
display(
    Markdown(
        f"**Maximizes objective value to:**"
        f" ${ampl.get_objective('Objective').value():.2f}$"
    )
)

# %%
alpha_values = [
    0.005,
    0.01,
    0.02,
    0.03,
    0.04,
    0.05,
    0.06,
    0.07,
    0.08,
    0.09,
    0.1,
    0.11,
    0.12,
    0.13,
    0.14,
    0.15,
    0.16,
    0.17,
    0.18,
    0.19,
    0.20,
    0.25,
    0.5,
]
objective = []

for alpha in alpha_values:
    ampl = markowitz_revisited(alpha, mu, Sigma)
    objective.append(round(ampl.get_objective("Objective").value(), 3))

plt.plot(alpha_values, objective)
plt.xlabel(r"Risk tolerance $\alpha$")
plt.ylabel("Optimal objective value")
plt.show()
