<jupyter_start><jupyter_text>Basic portfolio optimization problem using `CVXPY` Dr. <NAME>  Fremont, CA, May 2019<jupyter_code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from cvxpy import *<jupyter_output><empty_output><jupyter_text>Read the data (please make sure that the CSV data file is in the same directory as this Notebook)<jupyter_code>mp = pd.read_csv("monthly_prices.csv",index_col=0)
mr = pd.DataFrame()
mp.head()<jupyter_output><empty_output><jupyter_text>Plot the data<jupyter_code>plt.figure(figsize=(10,5))
plt.plot([i for i in range(1,25)],mp['MSFT'],lw=3,marker='o',markersize=12)
plt.plot([i for i in range(1,25)],mp['V'],lw=3,c='red',marker='^',markersize=12)
plt.plot([i for i in range(1,25)],mp['WMT'],lw=3,marker='*',markersize=12)
plt.legend(mp.columns,fontsize=16)
plt.xlabel("Months",fontsize=18)
plt.ylabel("Stock price (Monthly average)",fontsize=18)
plt.xticks(fontsize=16)
plt.yticks(fontsize=16)
plt.grid(True)
plt.show()<jupyter_output><empty_output><jupyter_text>Compute monthly returns<jupyter_code># compute monthly returns
for s in mp.columns:
    date = mp.index[0]
    pr0 = mp[s][date] 
    for t in range(1,len(mp.index)):
        date = mp.index[t]
        pr1 = mp[s][date]
        ret = (pr1-pr0)/pr0
        mr.set_value(date,s,ret)
        pr0 = pr1
mr.head()<jupyter_output><empty_output><jupyter_text>Get symbol names<jupyter_code># get symbol names
symbols = mr.columns<jupyter_output><empty_output><jupyter_text>Convert monthly return data frame to a numpy matrix<jupyter_code>return_data = mr.as_matrix().T
plt.figure(figsize=(10,5))
plt.plot([i for i in range(1,24)],100*mr['MSFT'],lw=3,marker='o',markersize=12)
plt.plot([i for i in range(1,24)],100*mr['V'],lw=3,c='red',marker='^',markersize=12)
plt.plot([i for i in range(1,24)],100*mr['WMT'],lw=3,marker='*',markersize=12)
plt.legend(mp.columns,fontsize=16)
plt.xlabel("Months",fontsize=18)
plt.ylabel("Monthly return (%))",fontsize=18)
plt.xticks(fontsize=16)
plt.yticks(fontsize=16)
plt.grid(True)
plt.show()<jupyter_output><empty_output><jupyter_text>Mean return<jupyter_code>r = np.asarray(np.mean(return_data, axis=1))<jupyter_output><empty_output><jupyter_text>Covariance matrix<jupyter_code>C = np.asmatrix(np.cov(return_data))
C<jupyter_output><empty_output><jupyter_text>Print expected returns and risk<jupyter_code>for j in range(len(symbols)):
    print ('%s: Exp ret = %f, Risk = %f' %(symbols[j],r[j], C[j,j]**0.5))<jupyter_output>MSFT: Exp ret = 0.024611, Risk = 0.058040
V: Exp ret = 0.018237, Risk = 0.042807
WMT: Exp ret = 0.009066, Risk = 0.044461<jupyter_text>Set up the optimization model<jupyter_code># Number of variables
n = len(symbols)

# The variables vector
x = Variable(n)

# The minimum return
req_return = 0.02

# The return
ret = r.T*x

# The risk in xT.Q.x format
risk = quad_form(x, C)

# The core problem definition with the Problem class from CVXPY
prob = Problem(Minimize(risk), [sum(x)==1, ret >= req_return, x >= 0])<jupyter_output><empty_output><jupyter_text>Try solving the problem (within a `try/except` loop)<jupyter_code>try:
    prob.solve()
    print ("Optimal portfolio")
    print ("----------------------")
    for s in range(len(symbols)):
       print (" Investment in {} : {}% of the portfolio".format(symbols[s],round(100*x.value[s],2)))
    print ("----------------------")
    print ("Exp ret = {}%".format(round(100*ret.value,2)))
    print ("Expected risk    = {}%".format(round(100*risk.value**0.5,2)))
except:
    print ("Error")
prob.status
x.value<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.17792098627066405, 'fraction_numerical': 0.04174838890445503, 'mean_word_length': 5.812977099236641, 'pattern_counts': {'":': 0, '<': 45, '<?xml version=': 0, '>': 47, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '11', 'dir': 'jupyter-structured-clean-dedup', 'id': '110934', 'license': 'Apache-2.0', 'n_tokens_mistral': 1514, 'n_tokens_neox': 1392, 'n_words': 267, 'path': 'Portfolio_optimization.ipynb', 'repo_name': 'matteoaurelio/Optimization-Python', 'size': '3581'}