# 出典: mo-notebooks/05/markowitz_portfolio.ipynb

# %%
# Install AMPL and solvers

SOLVER_QO = "ipopt"

from amplpy import AMPL, ampl_notebook

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

# %%
from IPython.display import Markdown, HTML
import numpy as np
import pandas as pd

# %%
# Specify the initial capital, the risk threshold, and the guaranteed return rate.
C = 1
gamma = 1
R = 1.01

# Specify the number of assets, their expected return, and their covariance matrix.
n = 3
mu = np.array([1.2, 1.1, 1.3])
Sigma = np.matrix([[1.5, 0.5, 2], [0.5, 2, 0], [2, 0, 5]])
Sigma_df = pd.DataFrame(Sigma, index=range(n), columns=range(n))

# 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


def markowitz(gamma, mu, Sigma):
    m = AMPL()
    m.eval(
        """
      reset;
      # Assets
      set A;
      
      param Sigma{A, A};
      param mu{A};
      param C;
      param R;
      param gamma;

      var xtilde >= 0;
      var x{A} >= 0;

      maximize objective:
        sum{i in A} mu[i]*x[i] + R*xtilde;
      
      subject to bounded_variance:
        sum{i in A, j in A} x[i] * Sigma[i,j] * x[j] <= gamma**2;

      subject to total_assets:
        sum{i in A} x[i] + xtilde = C;
    """
    )

    m.set["A"] = list(range(n))

    m.param["C"] = C
    m.param["R"] = R
    m.param["mu"] = mu
    m.param["gamma"] = gamma
    m.param["Sigma"] = Sigma_df

    m.solve(solver=SOLVER_QO, verbose=False)
    assert m.solve_result == "solved", m.solve_result

    return m


model = markowitz(gamma, mu, Sigma)

x = model.var["x"]
display(
    Markdown(
        f"**Solution:** $\\tilde x = {model.var['xtilde'].value():.3f}$, $x_1 = {x[0].value():.3f}$,  $x_2 = {x[1].value():.3f}$,  $x_3 = {x[2].value():.3f}$"
    )
)
display(
    Markdown(
        f"**Maximizes objective value to:** ${model.obj['objective'].value():.2f}$"
    )
)
