logo

... 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

from tqdm import tqdm

def make_dataf_generator(dataf, window=90, step=5):
    i = 0
    while i*step+window < len(dataf):
        subset = dataf.iloc[0 + i*step:window+i*step]
        yield subset.index[-1], subset
        i += 1

df = pd.read_csv("stocks.csv").assign(Date = lambda d: pd.to_datetime(d['Date']))

subset_df = (df
            .loc[lambda d: d['Date'] < pd.to_datetime('2010-01-01')]
            .set_index('Date'))
groups = make_dataf_generator(subset_df)


x_vals = []
profit = []
timestamps = []
for ts, g in tqdm(groups):
    # this is where you can change the risk preference
    p, xs = solve_problem(g, risk_pref=1.5)
    timestamps.append(ts)
    x_vals.append(xs)
    profit.append(p)

Chart One

plt.figure(figsize=(12, 3))
plt.plot(timestamps, profit);

Chart Two

plt.figure(figsize=(12, 3))
x_vals = np.array(x_vals)
for idx, stock in enumerate(tickers):
    plt.plot(timestamps, x_vals[:, idx], label=stock)
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.