Loading...
Searching...
No Matches
Form1.cs
1using System;
2using System.Collections.Generic;
3using System.ComponentModel;
4using System.Data;
5using System.Drawing;
6using System.Linq;
7using System.Text;
8using System.Windows.Forms;
9using GAMS;
10using System.IO;
11using System.Reflection;
12using System.Windows.Forms.DataVisualization.Charting;
13using System.Diagnostics;
14
15namespace Markowitz
16{
24 public partial class Form1 : Form
25 {
26 public Form1()
27 {
29 if (Environment.GetCommandLineArgs().Length > 1)
30 ws = new GAMSWorkspace(systemDirectory: Environment.GetCommandLineArgs()[1]);
31 else
32 ws = new GAMSWorkspace();
33
34 GAMSJob job = ws.AddJobFromString(GetModelText());
35 GAMSOptions opt = ws.AddOptions();
36 opt.AllModelTypes = "conopt";
37 string gdxPath = Path.Combine(ws.SystemDirectory, "apifiles", "Data", "Markowitz.gdx");
38
39 opt.Defines.Add("data", "\"" + Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), gdxPath) + "\"");
40
42 job.Run(opt, cp);
43
45 GAMSParameter l = mi.SyncDB.AddParameter("lambda", 0, "");
46 mi.Instantiate("markowitz use nlp max z", new GAMSModifier(l));
47
48 // a list for collecting the data points
49 List<Tuple<double, double>> dataPoints = new List<Tuple<double, double>>();
50
51 // get minimum and maximum return (lambda=0/1)
52 l.AddRecord().Value = 0;
53 mi.Solve();
54 double minRet = mi.SyncDB.GetVariable("ret").FirstRecord().Level;
55 dataPoints.Add(Tuple.Create(minRet, mi.SyncDB.GetVariable("var").FirstRecord().Level));
56 l.FindRecord().Value = 1;
57 mi.Solve();
58 double maxRet = mi.SyncDB.GetVariable("ret").FirstRecord().Level;
59 dataPoints.Add(Tuple.Create(maxRet, mi.SyncDB.GetVariable("var").FirstRecord().Level));
60
61 // gap that specifies the max distance (return) between two data points
62 double gap = 0.02;
63
64 // a stack of intervals, where an interval is represented by a 2-tuple containing two data points
65 // each represented by a 2-tuple as well (lambda, return)
66 Stack<Tuple<Tuple<double, double>, Tuple<double, double>>> intervals = new Stack<Tuple<Tuple<double, double>, Tuple<double, double>>>();
67 intervals.Push(Tuple.Create(Tuple.Create(0.0, minRet), Tuple.Create(1.0, maxRet)));
68
69 // Algorithm that solves the model instance for multiple lambda values
70 // using a max gap between two data points to achieve a smooth graph.
71 // Lambda is dynamically calculated for an even distribution of data points
72 while(intervals.Count > 0){
73 // pick the first interval and calculate a new value for lambda
74 var i = intervals.Pop();
75 double minL = i.Item1.Item1;
76 minRet = i.Item1.Item2;
77 double maxL = i.Item2.Item1;
78 maxRet = i.Item2.Item2;
79
80 double lVal = (minL+maxL)/2;
81 l.FirstRecord().Value = lVal;
82 // solve the model instance with the new lambda value
83 mi.Solve();
84 // retrieve the return and variance results
85 double curRet = mi.SyncDB.GetVariable("ret").FirstRecord().Level;
86 dataPoints.Add(Tuple.Create(curRet, mi.SyncDB.GetVariable("var").FirstRecord().Level));
87 // add new intervals if the gap is still to big
88 if (curRet - minRet > gap)
89 intervals.Push(Tuple.Create(Tuple.Create(minL, minRet), Tuple.Create(lVal, curRet)));
90 if (Math.Abs(curRet - maxRet) > gap)
91 intervals.Push(Tuple.Create(Tuple.Create(lVal, curRet), Tuple.Create(maxL, maxRet)));
92 }
93
94 // Sort data points
95 dataPoints.Sort((a, b) => a.Item1.CompareTo(b.Item1));
96
97 InitializeComponent();
98 this.chart1.Series.Clear();
99 Series s = this.chart1.Series.Add("s");
100 s.ChartType = SeriesChartType.Line;
101 s.MarkerStyle = MarkerStyle.Circle;
102 s.MarkerSize = 5;
103 this.chart1.ChartAreas[0].AxisX.Title = "return";
104 this.chart1.ChartAreas[0].AxisY.Title = "variance";
105 this.chart1.ChartAreas[0].AxisX.Interval = 0.1;
106 this.chart1.ChartAreas[0].AxisX.Minimum = 0;
107
108 foreach(Tuple<double,double> p in dataPoints)
109 s.Points.AddXY(p.Item1, p.Item2);
110 }
111
112 static String GetModelText()
113 {
114 String model = @"
115$title Standard Markowitz Portfolio Selection Model
116
117set s selected stocks
118 upper(s,s), lower(s,s) parts of covar matrix;
119alias(s,t);
120
121parameter mean(s) mean of daily return
122 covar(s,s) covariance matrix of returns (upper);
123
124$if not set data $abort 'no include file name for data file provided'
125$gdxin %data%
126$load s covar upper lower mean
127
128variables z objective variable
129 ret return
130 var variance
131 x(s) investments;
132
133positive variables x;
134
135equations obj objective
136 budget
137 varcon variance constraint
138 retcon return constraint;
139
140scalar lambda /0/;
141
142obj.. z =e= lambda*ret - (1-lambda)*var;
143budget.. sum(s, x(s)) =e= 1.0;
144varcon.. var =e= sum(upper(s,t), x(s)*covar(s,t)*x(t)) +
145 sum(lower(s,t), x(s)*covar(t,s)*x(t));
146retcon.. ret =e= sum(s, mean(s)*x(s));
147
148model markowitz /all/
149";
150 return model;
151 }
152 }
153}
GAMSModelInstance AddModelInstance(string modelInstanceName=null)
GAMSVariable GetVariable(string variableIdentifier)
GAMSParameter AddParameter(string identifier, int dimension, string explanatoryText="")
void Run(GAMSOptions gamsOptions=null, GAMSCheckpoint checkpoint=null, TextWriter output=null, Boolean createOutDB=true)
void Solve(SymbolUpdateType updateType=SymbolUpdateType.BaseCase, TextWriter output=null, GAMSModelInstanceOpt miOpt=null)
void Instantiate(string modelDefinition, params GAMSModifier[] modifiers)
Dictionary< string, string > Defines
new GAMSParameterRecord FindRecord(params string[] keys)
new GAMSParameterRecord FirstRecord()
new GAMSParameterRecord AddRecord(params string[] keys)
new GAMSVariableRecord FirstRecord()
GAMSJob AddJobFromString(string gamsSource, GAMSCheckpoint checkpoint=null, string jobName=null)
GAMSCheckpoint AddCheckpoint(string checkpointName=null)
GAMSOptions AddOptions(GAMSOptions optFrom=null)
This is a small graphical program that plots the efficient frontier of Markowitz' portfolio selection...
Definition Form1.cs:25