# 出典: mo-notebooks/06/optimal-growth-portfolios.ipynb

# %%
# install dependencies and select solver

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

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 magic

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

import pandas as pd
import datetime
import yfinance as yf

# symbols as used by Yahoo Finance
symbols = {
    # selected indices
    "^GSPC": "S&P 500",
    "^IXIC": "Nasdaq",
    "^DJI": "Dow Jones Industrial",
    "^RUT": "Russell 2000",
    # selected stocks
    "AXP": "American Express",
    "AMGN": "Amgen",
    "AAPL": "Apple",
    "BA": "Boeing",
    "CAT": "Caterpillar",
    "CVX": "Chevron",
    "JPM": "JPMorgan Chase",
    "MCD": "McDonald's",
    "MMM": "3 M",
    "MSFT": "Microsoft",
    "PG": "Proctor & Gamble",
    "XOM": "ExxonMobil",
}

# years of testing and training data
n_test = 1
n_train = 2

# get today's date
today = datetime.datetime.today().date()

# Fix the day for consistent output and testing
today = datetime.datetime(2023, 6, 6).date()

# training data dates
end = today - datetime.timedelta(int(n_test * 365))
start = end - datetime.timedelta(int((n_test + n_train) * 365))

# get training data
S = yf.download(list(symbols.keys()), start=start, end=end, auto_adjust=True)["Close"]

# compute gross returns
R = S / S.shift(1)
R.dropna(inplace=True)

# %%
# plot
fig, ax = plt.subplots(2, 1, figsize=(8, 6), sharex=True)

S.divide(S.iloc[0] / 100).plot(ax=ax[0], grid=True, title="Normalized Prices")
ax[0].legend(loc="center left", bbox_to_anchor=(1.0, 0.5), prop={"size": 8})

R.plot(ax=ax[1], grid=True, title="Gross Returns", alpha=0.5).legend([])

fig.tight_layout()

# %%
def kelly_portfolio(R, Rf=1, EM=1, lambd=0):
    ampl = AMPL()
    ampl.read("kelly_portfolio.mod")

    ampl.param["Rf"] = Rf
    ampl.param["EM"] = EM
    ampl.param["lambd"] = lambd

    # index lists
    ampl.set["T"] = [str(t) for t in R.index]
    ampl.set["N"] = [str(n) for n in R.columns]
    ampl.param["Rloc"] = {
        (str(t), str(n)): R.at[t, n]
        for i, t in enumerate(R.index)
        for j, n in enumerate(R.columns)
    }

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

    return ampl

# %%
def kelly_report(ampl):
    # print report
    s = f"""
Risk Free Return = {100*(np.exp(252*np.log(ampl.get_value('Rf'))) - 1):0.2f}
Equity Multiplier Limit = {ampl.get_value('EM'):0.5f}
Risk Aversion = {ampl.get_value('lambd'):0.5f}

Portfolio
"""
    w = ampl.get_variable("w").to_dict()
    Rvar = ampl.get_variable("R").to_dict()

    s += "\n".join([f"{n:8s} {symbols[n]:30s}  {100*w[n]:8.2f} %" for n in w.keys()])
    s += f"""
{'':8s} {'Risk Free':30s}  {100*(1 - sum(w[n] for n in w.keys())):8.2f} %

Annualized return = {100*(np.exp(252*ampl.get_value('ElogR')) - 1):0.2f} %
"""
    print(s)

    df = pd.DataFrame(
        pd.Series([Rvar[str(t)] for t in R.index]), columns=["Kelly Portfolio"]
    )
    df.index = R.index  ## original index are the DateTimeStamps

    fix, ax = plt.subplots(1, 1, figsize=(8, 8))
    S.divide(S.iloc[0] / 100).plot(
        ax=ax,
        logy=True,
        grid=True,
        title="Normalized Prices",
        alpha=0.6,
        lw=0.4,
        ls="--",
    )
    df.cumprod().multiply(100).plot(ax=ax, lw=3, grid=True)
    ax.legend(
        [symbols[n] for n in R.columns] + ["Kelly Portfolio"],
        bbox_to_anchor=(1.05, 1.05),
    )

    d = S.index[-1]
    print(d)

    for n in w.keys():
        y = 100 * S[n].iloc[-1] / S[n].iloc[0]
        print(n, 100 * S[n].iloc[-1] / S[n].iloc[0])
        ax.text(d, y, n)

# %%
# parameter values
Rf = np.exp(np.log(1.0) / 252)
EM = 1
lambd = 10

m = kelly_portfolio(R, Rf, EM, lambd)
kelly_report(m)

# %%
S.head()

# %%
lambd = 10 ** np.linspace(0, 3)

results = [kelly_portfolio(R, Rf=1, EM=1, lambd=_) for _ in lambd]

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

fig, ax = plt.subplots(2, 1, figsize=(8, 4), sharex=True)

ax[0].semilogx(
    [m.get_value("lambd") for m in results],
    [100 * (np.exp(252 * m.get_value("ElogR")) - 1) for m in results],
)
ax[0].set_title("Portfolio Return vs Risk Aversion")
ax[0].set_ylabel("annual %")
ax[0].grid(True)

ax[1].semilogx(
    [m.get_value("lambd") for m in results],
    [
        [w[str(n)] for n in R.columns]
        for m in results
        for w in [m.get_variable("w").to_dict()]
    ],
)
ax[1].set_ylabel("weights")
ax[1].set_xlabel("risk aversion $\lambda$")
ax[1].legend([symbols[n] for n in R.columns], bbox_to_anchor=(1.05, 1.05))
ax[1].grid(True)
ax[1].set_ylim(0, EM)

fig.tight_layout()

# %%
EM = np.linspace(0.0 + 1e-1, 2.0)

results = [kelly_portfolio(R, Rf=1, EM=_, lambd=10) for _ in EM]

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

fig, ax = plt.subplots(2, 1, figsize=(8, 4), sharex=True)

ax[0].plot(
    [m.get_value("EM") for m in results],
    [100 * (np.exp(252 * m.get_value("ElogR")) - 1) for m in results],
)
ax[0].set_title("Portfolio Return vs Equity Multiplier")
ax[0].set_ylabel("annual return %")
ax[0].grid(True)

ax[1].plot(
    [m.get_value("EM") for m in results],
    [
        [w[str(n)] for n in R.columns]
        for m in results
        for w in [m.get_variable("w").to_dict()]
    ],
)
ax[1].set_ylabel("weights")
ax[1].set_xlabel("Equity Multiplier")
ax[1].legend([symbols[n] for n in R.columns], bbox_to_anchor=(1.05, 1.05))
ax[1].grid(True)
ax[1].set_ylim(
    0,
)

fig.tight_layout()

# %%
Rf = np.exp(np.log(1 + np.linspace(0, 0.20)) / 252)

results = [kelly_portfolio(R, Rf=_, EM=1, lambd=10) for _ in Rf]

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

fig, ax = plt.subplots(2, 1, figsize=(8, 4), sharex=True)

Rf = np.exp(252 * np.log(np.array([_.get_value("Rf") for _ in results])))
ax[0].plot(Rf, [100 * (np.exp(252 * m.get_value("ElogR")) - 1) for m in results])
ax[0].set_title("Portfolio Return vs Risk-free Rate")
ax[0].set_ylabel("annual return %")
ax[0].grid(True)

ax[1].plot(
    Rf,
    [
        [w[str(n)] for n in R.columns]
        for m in results
        for w in [m.get_variable("w").to_dict()]
    ],
)
ax[1].set_ylabel("weights")
ax[1].set_xlabel("Risk-free Rate")
ax[1].legend([symbols[n] for n in R.columns], bbox_to_anchor=(1.05, 1.05))
ax[1].grid(True)
ax[1].set_ylim(
    0,
)

fig.tight_layout()
