14import matplotlib.pyplot
as plt
15from gams
import GamsModifier, GamsWorkspace
21 upper(s,s)
'parts of covar matrix'
22 lower(s,s)
'parts of covar matrix';
27 mean(s)
'mean of daily return'
28 covar(s,s)
'covariance matrix of returns (upper)';
30$
if not set data $abort
'no include file name for data file provided'
32$load s covar upper lower mean
36 z
'objective variable'
46 varcon
'variance constraint'
47 retcon
'return constraint';
51obj.. z =e=
lambda*ret - (1-
lambda)*var;
53budget.. sum(s, x(s)) =e= 1.0;
55varcon.. var =e= sum(upper(s,t), x(s)*covar(s,t)*x(t)) +
56 sum(lower(s,t), x(s)*covar(t,s)*x(t));
58retcon.. ret =e= sum(s, mean(s)*x(s));
60Model markowitz / all /;
63if __name__ == "__main__":
64 sys_dir = sys.argv[1] if len(sys.argv) > 1
else None
65 ws = GamsWorkspace(system_directory=sys_dir)
67 job = ws.add_job_from_string(GAMS_MODEL)
68 opt = ws.add_options()
69 opt.all_model_types =
"conopt"
70 opt.defines[
"data"] = os.path.join(
71 ws.system_directory,
"apifiles",
"Data",
"markowitz.gdx"
74 cp = ws.add_checkpoint()
76 mi = cp.add_modelinstance()
77 l = mi.sync_db.add_parameter(
"lambda", 0,
"")
78 mi.instantiate(
"markowitz use nlp max z", GamsModifier(l))
84 l.add_record().value = 0
86 min_ret = mi.sync_db[
"ret"].first_record().level
87 data_points.append((min_ret, mi.sync_db[
"var"].first_record().level))
88 l.first_record().value = 1
90 max_ret = mi.sync_db[
"ret"].first_record().level
91 data_points.append((max_ret, mi.sync_db[
"var"].first_record().level))
98 intervals = [((0.0, min_ret), (1.0, max_ret))]
106 min_l, min_ret = i[0][0], i[0][1]
107 max_l, max_ret = i[1][0], i[1][1]
109 l_val = (min_l + max_l) / 2
110 l.first_record().value = l_val
116 cur_ret = mi.sync_db[
"ret"].first_record().level
117 data_points.append((cur_ret, mi.sync_db[
"var"].first_record().level))
120 if fabs(cur_ret - min_ret) > gap:
121 intervals.append(((min_l, min_ret), (l_val, cur_ret)))
122 if fabs(cur_ret - max_ret) > gap:
123 intervals.append(((l_val, cur_ret), (max_l, max_ret)))
126 data_points.sort(key=
lambda tup: tup[0])
127 ret = [x[0]
for x
in data_points]
128 var = [x[1]
for x
in data_points]
129 plt.plot(ret, var, marker=
".", markersize=10)
131 plt.ylabel(
"variance")