# 出典: mo-notebooks/06/investment-wheel.ipynb

# %%
# install dependencies and select solver

SOLVER_CONIC = "mosek"  ## ipopt, mosek, 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

# %%
# specify the investment wheel
wheel = {
    "A": {"p": 1 / 2, "b": 3},
    "B": {"p": 1 / 3, "b": 2},
    "C": {"p": 1 / 6, "b": 6},
}

# %%
import numpy as np
import matplotlib.pyplot as plt
import bisect

import ipywidgets as widgets


def wheel_sim(w, T, N):
    # set of wheel sectors
    S = list(wheel.keys())

    # odds, probability, and quantiles
    b = {s: wheel[s]["b"] for s in S}
    p = {s: wheel[s]["p"] for s in S}
    q = np.cumsum(list(p.values()))

    # gross return for each sector
    R = {s: 1 + w[s] * b[s] - sum(w.values()) for s in S}

    # set up plot and colors
    _, ax = plt.subplots(1, 1, figsize=(8, 3))
    colors = {s: ax.semilogy(0, 1, ".", ms=10)[0].get_color() for s in S}

    # repeat the simulation N times
    for _ in range(N):
        wealth = 1.0
        for k in range(T):
            # spin the wheel
            spin = np.random.uniform()
            s = S[bisect.bisect_left(q, spin)]
            wealth_next = wealth * R[s]

            # add to plot
            ax.semilogy([k, k + 1], [wealth, wealth_next], c=colors[s], alpha=0.4)
            ax.semilogy(k + 1, wealth_next, ".", ms=4, c=colors[s], alpha=0.4)
            wealth = wealth_next

    # compute expected log return
    ElogR = sum(p[s] * np.log(R[s]) for s in S)
    ax.plot(np.exp(ElogR * np.linspace(0, T, T + 1)), lw=5, alpha=0.5)
    ax.set_title(f"E[log(R)] = {ElogR:0.5f}")
    ax.legend([f"$w_{s}$ = {w[s]:0.3f}" for s in S])
    ax.set_xlim(0, T)
    ax.set_ylim(0.01, 1000.0)
    ax.set_ylabel("Wealth")
    ax.set_xlabel("Stages")
    ax.grid(True)
    return ax


wheel_sim({"A": 0.33, "B": 0.33, "C": 0.33}, 40, 20)


@widgets.interact_manual(
    wA=widgets.FloatSlider(min=0.0, max=1.0, step=0.01, value=0.333),
    wB=widgets.FloatSlider(min=0.0, max=1.0, step=0.01, value=0.333),
    wC=widgets.FloatSlider(min=0.0, max=1.0, step=0.01, value=0.333),
)
def wheel_interact1(wA, wB, wC):
    w = {"A": wA, "B": wB, "C": wC}
    wheel_sim(w, 40, 20)

# %%
def wheel_model(wheel):
    ampl = AMPL()
    ampl.read("wheel.mod")

    ampl.set["S"] = list(wheel.keys())
    ampl.param["p"] = {s: wheel[s]["p"] for s in wheel.keys()}
    ampl.param["b"] = {s: wheel[s]["b"] for s in wheel.keys()}

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

    return ampl


m = wheel_model(wheel)
w = m.get_variable("w").to_dict()

print(f"Expected Log Return = {m.get_objective('ElogR').value(): 0.5f}\n")
for s in wheel.keys():
    print(
        f"Sector {s}:  p = {wheel[s]['p']:0.3f}   b = {wheel[s]['b']:0.2f}   w = {w[s]:0.3f}"
    )

wheel_sim(w, 40, 20)

# %%
def wheel_rc_model(wheel, lambd=0):
    ampl = AMPL()
    ampl.read("wheel_risk_averse.mod")

    ampl.set["S"] = list(wheel.keys())
    ampl.param["p"] = {s: wheel[s]["p"] for s in wheel.keys()}
    ampl.param["b"] = {s: wheel[s]["b"] for s in wheel.keys()}
    ampl.param["lambd"] = lambd

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

    return (
        ampl.get_variable("w").to_dict(),
        ampl.get_objective("ElogR").value(),
    )


lambd = 2
w, obj = wheel_rc_model(wheel, lambd)

print(f"Risk-aversion lambda = {lambd:0.3f}")
print(f"Expected Log Gross Return = {obj:0.5f}\n")
for s in wheel.keys():
    print(
        f"Sector {s}:  p = {wheel[s]['p']:0.4f}   b = {wheel[s]['b']:0.2f}   w = {w[s]:0.5f}"
    )

wheel_sim(w, 40, 20)

# %%
@widgets.interact_manual(
    lambd=widgets.FloatSlider(min=0.0, max=20.0, step=0.1, value=2),
)
def wheel_interact2(lambd):
    w, _ = wheel_rc_model(wheel, lambd)
    wheel_sim(w, 40, 20)

# %%
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(2, 1, figsize=(10, 4))

v = np.linspace(-1, 5)
lambd = np.exp(v)
results = [wheel_rc_model(wheel, _) for _ in lambd]

ax[0].semilogx(lambd, [np.exp(obj) for _, obj in results])
ax[0].set_title("investment wheel return / spin")
ax[0].grid(True)

ax[1].semilogx(lambd, [[w[s] for s in wheel.keys()] for w, _ in results])
ax[1].set_title("investment weights")
ax[1].set_xlabel("risk aversion $\lambda$")
ax[1].legend(
    [f"(p, b) = ({wheel[s]['p']:0.3f}, {wheel[s]['b']:0.1f})" for s in wheel.keys()],
    bbox_to_anchor=(1.05, 1.05),
)
ax[1].grid(True)
ax[1].set_ylim(0, 0.6)

fig.tight_layout()
