# cvxpy two.

When you invest in stocks you want to get a high return, but a low risk. There's also going to be a few constraints. That sounds like a job for cvxpy.

**Episode Notes**

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();
```

Feedback? See an issue? Feel free to mention it here.

If you want to be kept up to date, consider getting the newsletter.