# 出典: mo-notebooks/09/markowitz_portfolio_with_chance_constraint.ipynb

# %%
# Install AMPL and solvers

SOLVER = "scip"

from amplpy import AMPL, ampl_notebook

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

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

# %%
# we import the inverse CDF or quantile function for the standard normal norm.ppf() from scipy.stats
from scipy.stats import norm

# We set our risk threshold and risk levels (sometimes you may get an infeasible problem if the chance
# constraint becomes too tight!)
alpha = 0.6
beta = 0.3

# We specify the initial capital, the risk-free return the number of risky assets, their expected returns, and their covariance matrix.
C = 1
R = 1.05
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]])

# Check how dramatically the optimal solution changes if we assume i.i.d. deviations for the returns.
# Sigma = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])

# If you want to change covariance matrix, make sure 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_chanceconstraints(alpha, beta, mu, Sigma):
    m = AMPL()
    m.read("markowitz_chanceconstraints.mod")

    Sigma_df = pd.DataFrame(Sigma, index=range(n), columns=range(n))
    phi_val = norm.ppf(1 - beta)

    m.set["N"] = range(n)

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

    m.solve(solver=SOLVER)
    return m.solve_result, m


solve_result, model = markowitz_chanceconstraints(alpha, beta, mu, Sigma)
assert solve_result == "solved", solve_result

x_tilde = model.var["x_tilde"].value()
x = model.var["x"].to_dict()

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