Calmcode - cvxpy two: risk preference

Risk Preference

1 2 3 4 5 6 7 8

The code is not listed in the video, but if you want to repeat this yourself, you can use the following code to make the same charts.

Data Prep

def solve_problem(dataf, risk_pref=0.1):
    mean_stock = dataf.diff().mean().values
    cov_stock = dataf.diff().cov().values

    x = cp.Variable(len(mean_stock))

    stock_return = mean_stock.T * x
    stock_risk = cp.quad_form(x, cov_stock)

    objective = cp.Maximize(stock_return - risk_pref * stock_risk)
    constraints = [cp.sum(x) == 1, x >= 0]
    prob = cp.Problem(objective=objective, constraints=constraints)
    return prob.solve(), x.value

import numpy as np
import matplotlib.pylab as plt

steps = np.linspace(0.01, 2, 100)
x_vals = np.zeros((steps.shape[0], 4))
profit = np.zeros(steps.shape[0])
for i, r in enumerate(steps):
    p, xs = solve_problem(df_stocks.set_index('Date'), risk_pref=r)
    x_vals[i, :] = xs
    profit[i] = p

Chart One

plt.figure(figsize=(12, 4))
plt.plot(steps, profit)
plt.xlabel("risk avoidance")
plt.ylabel("1 day ahead expected return");

Chart Two

plt.figure(figsize=(12, 4))
tickers = ["MSFT", "KLM", "ING", "MOS"]
for idx, stock in enumerate(tickers):
    plt.plot(steps, x_vals[:, idx], label=stock)
plt.xlabel("risk avoidance")
plt.ylabel("proportion of investment")
plt.legend();