Initializing help system before first use

Folio - Embedding examples from 'Getting started'


Type: Portfolio optimization
Rating: 2 (easy-medium)
Description:
  • Chapter 9 Embedding a Mosel model in an application
    • folioexec.bas, folioexec.c, folioexec.java, folioexec.cs (requires foliodata.mos and folio.dat): executing a Mosel model
    • foliorun.bas, foliorun.c, foliorun.java, foliorun.cs (requires foliodata.bim and folio.dat): loading and running a BIM file
    • folioparam.bas, folioparam.c, folioparam.java, folioparam.cs (requires foliodata.mos and folio.dat): parameterized model execution
    • foliomat.c, foliomat.java, foliomat.cs (requires foliodata.mos and folio.dat): matrix output
    • folioobj.c, folioobj.java, folioobj.cs (requires foliodata.mos and folio.dat): accessing model results
    • runfolio.xlsm (requires folioexcel.mos): launching a Mosel model from Excel via VBA marcos (Windows only)
    • folioinsight.zip (contains folioinsight.mos), folioinsightxml.zip (contains folioinsightxml.mos, folio.vdl, foliocompare.vdl, folioinsightxml.xml): Insight apps based on the 'foliodata' model (Windows only)
File(s): foliorun.c, folioexec.c, folioparam.c, foliomat.c, folioobj.c, foliorun.cs, folioexec.cs, folioparam.cs, foliomat.cs, folioobj.cs, foliorun.java, folioexec.java, folioparam.java, foliomat.java, folioobj.java, foliorun.bas, folioexec.bas, folioparam.bas, foliodata.mos, folioexcel.mos, folioinsight.mos, folioinsightxml.mos, folio.vdl, foliocompare.vdl, folioinsightxml.xml
Data file(s): folio.dat, runfolio.xlsm, folioinsight.zip, folioinsightxml.zip

foliorun.c
/********************************************************
  Mosel Library Example Problems
  ==============================

  file foliorun.c
  ```````````````
  Loading and running a BIM file.

  (c) 2008 Fair Isaac Corporation
      author: S.Heipcke, Aug. 2003
********************************************************/

#include <stdio.h>
#include "xprm_rt.h"

int main(int argc, char *argv[])
{
  XPRMmodel model;
  int result;
  
  XPRMinit();                                  /* Initialize Mosel */
  model = XPRMloadmod("foliodata.bim", NULL);  /* Load compiled model */
  XPRMrunmod(model, &result, NULL);
  XPRMunloadmod(model);

  return 0;
}

folioexec.c
/********************************************************
  Mosel Library Example Problems
  ==============================

  file folioexec.c
  ````````````````
  Executing a Mosel model.

  (c) 2008 Fair Isaac Corporation
      author: S.Heipcke, Aug. 2003
********************************************************/

#include <stdio.h>
#include "xprm_mc.h"

int main(int argc, char *argv[])
{
  int result;
  
  XPRMinit();                        /* Initialize Mosel */
                                     /* Execute = compile/load/run a model */
  XPRMexecmod(NULL, "foliodata.mos", NULL, &result, NULL);

  return 0;
}

folioparam.c
/********************************************************
  Mosel Library Example Problems
  ==============================

  file folioparam.c
  `````````````````
  Parameterized model execution.

  (c) 2008 Fair Isaac Corporation
      author: S.Heipcke, Aug. 2003
********************************************************/

#include <stdio.h>
#include "xprm_mc.h"

int main(int argc, char *argv[])
{
  XPRMmodel model;
  int result;
  char params[128];
  
  XPRMinit();                        /* Initialize Mosel */

  sprintf(params, "OUTFILE=result2.dat,MAXRISK=0.4,MAXVAL=0.25");

                                     /* Execute = compile/load/run a model */  
  XPRMexecmod(NULL, "foliodata.mos", params, &result, &model);

  XPRMunloadmod(model);

  return 0;
}

foliomat.c
/********************************************************
  Mosel Library Example Problems
  ==============================

  file foliomat.c
  ```````````````
  Exporting a matrix.

  (c) 2008 Fair Isaac Corporation
      author: S.Heipcke, Aug. 2003
********************************************************/

#include <stdio.h>
#include "xprm_mc.h"

int main(int argc, char *argv[])
{
  int result, type;
  XPRMmodel model;
  XPRMalltypes rvalue;
  XPRMlinctr obj;
  
  XPRMinit();                        /* Initialize Mosel */
                                     /* Execute = compile/load/run a model */
  XPRMexecmod(NULL, "foliodata.mos", NULL, &result, &model);

                                     /* Retrieve a model object by its name */
  type = XPRMfindident(model, "Return", &rvalue);
  if((XPRM_TYP(type)!=XPRM_TYP_LINCTR)||  /* Check the type: */
     (XPRM_STR(type)!=XPRM_STR_REF))      /* it must be a reference to a linear
                                             constraint */
   return 1;
  obj = rvalue.linctr;               /* Store the objective function reference */

  XPRMexportprob(model, "p", "folio", obj);

  return 0;
}

folioobj.c
/********************************************************
  Mosel Library Example Problems
  ==============================

  file folioobj.c
  ```````````````
  Accessing model results.

  (c) 2008 Fair Isaac Corporation
      author: S.Heipcke, Aug. 2003
********************************************************/

#include <stdio.h>
#include "xprm_mc.h"

int main(int argc, char *argv[])
{
  XPRMmodel model;
  XPRMalltypes rvalue, itemname;
  XPRMarray varr;
  XPRMmpvar x;
  XPRMset set;
  int result, indices[1], type;
  
  XPRMinit();                          /* Initialize Mosel */
                                       /* Execute = compile/load/run a model */
  XPRMexecmod(NULL, "foliodata.mos", NULL, &result, &model);

                                       /* Test whether a solution is found 
				          and print the objective value */
  if((XPRMgetprobstat(model)&XPRM_PBRES)==XPRM_PBOPT)
    printf("Objective value: %g\n", XPRMgetobjval(model));


                                       /* Retrieve the decision variables */
  type=XPRMfindident(model,"frac",&rvalue);   /* Get model object 'frac' */
  if((XPRM_TYP(type)!=XPRM_TYP_MPVAR)||       /* Check the type: */
    (XPRM_STR(type)!=XPRM_STR_ARR))           /* it must be an `mpvar' array */
    return 1;
  varr = rvalue.array;

                                       /* Retrieve the index names */
  type = XPRMfindident(model,"SHARES",&rvalue); /* Get model object 'SHARES'*/
  if((XPRM_TYP(type)!=XPRM_TYP_STRING)||      /* Check the type: */
     (XPRM_STR(type)!=XPRM_STR_SET))          /* it must be a set of strings */
    return 2;
  set = rvalue.set;

  XPRMgetfirstarrentry(varr, indices); /* Get the first entry of array varr
                                          (we know that the array is dense 
                                          and has a single dimension) */
  do                                   /* Print out the solution */
  {
   XPRMgetarrval(varr,indices,&x);            /* Get a variable from varr */
   printf("%s:\t%g%%\n", XPRMgetelsetval(set, indices[0], &itemname)->string,
          XPRMgetvsol(model,x)*100);          /* Print the solution value */
  } while(!XPRMgetnextarrentry(varr, indices));  /* Get the next index */

  return 0;
}

foliorun.cs
/********************************************************
  Mosel Library Example Problems
  ==============================

  file foliorun.cs
  ````````````````
  Loading and running a BIM file.

  (c) 2009 Fair Isaac Corporation
      author: J.Farmer, Jun. 2009
********************************************************/

using System;
using Mosel;

namespace mosel_getting_started {
 public class foliorun
 {
  public static void Main(string[] args)
  {
   XPRM mosel;
   XPRMModel mod;
 
   mosel = XPRM.Init();                        // Initialize Mosel
 
   mod = mosel.LoadModel("foliodata.bim");     // Load compiled model
   mod.Run();
   
   Console.WriteLine("`foliodata' returned: " + mod.Result);
  }
 }
}

folioexec.cs
/********************************************************
  Mosel Library Example Problems
  ==============================

  file folioexec.cs
  `````````````````
  Compiling, loading and running a model file.

  (c) 2009 Fair Isaac Corporation
      author: J.Farmer,  Jun. 2009
********************************************************/

using Mosel;
using System;

namespace mosel_getting_started {
 public class folioexec
 {
  public static void Main(string[] args)
  {
   XPRM mosel;
   XPRMModel mod;
 
   mosel = XPRM.Init();                       // Initialize Mosel
 
   mosel.Compile("foliodata.mos");            // Compile the model
   mod = mosel.LoadModel("foliodata.bim");    // Load compiled model
   mod.Run();                                 // Run the model
   
   Console.WriteLine("`foliodata' returned: " + mod.Result);
  }
 }

}

folioparam.cs
/********************************************************
  Mosel Library Example Problems
  ==============================

  file folioparam.cs
  ``````````````````
  Parameterized model execution.

  (c) 2009 Fair Isaac Corporation
      author: J.Farmer, Jun. 2009
********************************************************/

using System;
using Mosel;

namespace mosel_getting_started {
 public class folioparam
 {
  public static void Main(string[] args)
  {
   XPRM mosel;
   XPRMModel mod;
 
   mosel = XPRM.Init();                       // Initialize Mosel
 
   mosel.Compile("foliodata.mos");            // Compile the model
   mod = mosel.LoadModel("foliodata.bim");    // Load compiled model
                                              // Set the run-time parameters
   mod.ExecParams = "OUTFILE=result2.dat,MAXRISK=0.4,MAXVAL=0.25";
   mod.Run();                                 // Run the model
   
   Console.WriteLine("`foliodata' returned: " + mod.Result);
  }
 }
}

foliomat.cs
/********************************************************
  Mosel Library Example Problems
  ==============================

  file foliomat.cs
  ````````````````
  Exporting a matrix.

  (c) 2009 Fair Isaac Corporation
      author: J.Farmer,  Jun. 2009
********************************************************/

using Mosel;

namespace mosel_getting_started {
 public class foliomat
 {
  public static void Main(string[] args)
  {
   XPRM mosel;
   XPRMModel mod;

   mosel = XPRM.Init();                       // Initialize Mosel

   mosel.Compile("foliodata.mos");            // Compile the model
   mod = mosel.LoadModel("foliodata.bim");    // Load compiled model
   mod.Run();                                 // Run the model

   mod.ExportProblem("p", "folio");
  }
 }
}

folioobj.cs
/********************************************************
  Mosel Library Example Problems
  ==============================

  file folioobj.cs
  ````````````````
  Accessing model results.

  (c) 2009 Fair Isaac Corporation
      author: J.Farmer,  Jun. 2009
********************************************************/

using Mosel;
using System;

namespace mosel_getting_started {
 public class folioobj
 {
  public static void Main(string[] args)
  {
   XPRM mosel;
   XPRMModel model;
   XPRMArray varr;
   XPRMMPVar x;
   XPRMSet shares;
   int[] indices;
 
   mosel = XPRM.Init();                       // Initialize Mosel
 
   mosel.Compile("foliodata.mos");            // Compile the model
   model = mosel.LoadModel("foliodata.bim");  // Load compiled model
   model.Run();                               // Run the model
   
                                       // Test whether a solution is found 
                                       // and print the objective value 
   if(model.ProblemStatus==XPRMProblemStatus.PB_OPTIMAL)
     Console.WriteLine("Objective value: " + model.ObjectiveValue);
 
                                       // Retrieve the decision variables 
   varr=(XPRMArray)model.FindIdentifier("frac"); // Get model object 'frac',
                                                 // it must be an array
 
                                       // Retrieve the index names 
   shares=(XPRMSet)model.FindIdentifier("SHARES");  // Get model object 'SHARES',
                                                 // it must be a set
 
   indices = varr.FirstIndex;         // Get the first entry of array varr
                                       // (we know that the array is dense)
   do
   {
    x = varr.Get(indices).AsMPVar();   // Get a variable from varr
    Console.WriteLine(shares.Get(indices[0]) + ":\t" + x.Solution*100 + "%");
              // Print the solution value
   } while(varr.NextIndex(indices));   // Get the next index
 
  }
 }
}

foliorun.java
/********************************************************
  Mosel Library Example Problems
  ==============================

  file foliorun.java
  ``````````````````
  Loading and running a BIM file.

  (c) 2008 Fair Isaac Corporation
      author: S.Heipcke, Mar. 2006
********************************************************/

import com.dashoptimization.*;

public class foliorun
{
 public static void main(String[] args) throws Exception
 {
  XPRM mosel;
  XPRMModel mod;

  mosel = new XPRM();                        // Initialize Mosel

  mod = mosel.loadModel("foliodata.bim");    // Load compiled model
  mod.run();
  
  System.out.println("`foliodata' returned: " + mod.getResult());
 }
}

folioexec.java
/********************************************************
  Mosel Library Example Problems
  ==============================

  file folioexec.java
  ```````````````````
  Compiling, loading and running a model file.

  (c) 2008 Fair Isaac Corporation
      author: S.Heipcke, Mar. 2006
********************************************************/

import com.dashoptimization.*;

public class folioexec
{
 public static void main(String[] args) throws Exception
 {
  XPRM mosel;
  XPRMModel mod;

  mosel = new XPRM();                        // Initialize Mosel

  mosel.compile("foliodata.mos");            // Compile the model
  mod = mosel.loadModel("foliodata.bim");    // Load compiled model
  mod.run();                                 // Run the model
  
  System.out.println("`foliodata' returned: " + mod.getResult());
 }
}

folioparam.java
/********************************************************
  Mosel Library Example Problems
  ==============================

  file folioparam.java
  ````````````````````
  Parameterized model execution.

  (c) 2008 Fair Isaac Corporation
      author: S.Heipcke, Mar. 2006
********************************************************/

import com.dashoptimization.*;

public class folioparam
{
 public static void main(String[] args) throws Exception
 {
  XPRM mosel;
  XPRMModel mod;

  mosel = new XPRM();                        // Initialize Mosel

  mosel.compile("foliodata.mos");            // Compile the model
  mod = mosel.loadModel("foliodata.bim");    // Load compiled model
                                             // Set the run-time parameters
  mod.execParams = "OUTFILE=result2.dat,MAXRISK=0.4,MAXVAL=0.25";
  mod.run();                                 // Run the model
  
  System.out.println("`foliodata' returned: " + mod.getResult());
 }
}

foliomat.java
/********************************************************
  Mosel Library Example Problems
  ==============================

  file foliomat.java
  ``````````````````
  Exporting a matrix.

  (c) 2008 Fair Isaac Corporation
      author: S.Heipcke, Mar. 2006
********************************************************/

import com.dashoptimization.*;

public class foliomat
{
 public static void main(String[] args) throws Exception
 {
  XPRM mosel;
  XPRMModel mod;

  mosel = new XPRM();                        // Initialize Mosel

  mosel.compile("foliodata.mos");            // Compile the model
  mod = mosel.loadModel("foliodata.bim");    // Load compiled model
  mod.run();                                 // Run the model
  
  mod.exportProblem("p", "folio");
 }
}

folioobj.java
/********************************************************
  Mosel Library Example Problems
  ==============================

  file folioobj.java
  ``````````````````
  Accessing model results.

  (c) 2008 Fair Isaac Corporation
      author: S.Heipcke, Mar. 2006
********************************************************/

import com.dashoptimization.*;

public class folioobj
{
 public static void main(String[] args) throws Exception
 {
  XPRM mosel;
  XPRMModel model;
  XPRMArray varr, darr;
  XPRMMPVar x;
  XPRMSet set;
  int[] indices;

  mosel = new XPRM();                        // Initialize Mosel

  mosel.compile("foliodata.mos");            // Compile the model
  model = mosel.loadModel("foliodata.bim");  // Load compiled model
  model.run();                               // Run the model
  
                                      // Test whether a solution is found 
				      // and print the objective value 
  if(model.getProblemStatus()==XPRMModel.PB_OPTIMAL)
    System.out.println("Objective value: " + model.getObjectiveValue());

                                      // Retrieve the decision variables 
  varr=(XPRMArray)model.findIdentifier("frac"); // Get model object 'frac',
                                                // it must be an array

                                      // Retrieve the index names 
  set=(XPRMSet)model.findIdentifier("SHARES");  // Get model object 'SHARES',
                                                // it must be a set

  indices = varr.getFirstIndex();     // Get the first entry of array varr
                                      // (we know that the array is dense)
  do
  {
   x = varr.get(indices).asMPVar();   // Get a variable from varr
   System.out.println(set.get(indices[0]) + ":\t" + x.getSolution()*100 + "%");
				      // Print the solution value
  } while(varr.nextIndex(indices));   // Get the next index

 }
}

foliorun.bas
Attribute VB_Name = "Module1"
Option Explicit
' ********************************************************
'  Mosel Library Example Problems
'  ==============================
'  file foliorun.bas
'  `````````````````
'  Loading and running a BIM file.
'
'  (c) 2008 Fair Isaac Corporation
'      author: S.Heipcke, Aug. 2003
' ********************************************************

Sub Main()
 Dim result As Long
 Dim model

' Initialize Mosel
 XPRMinit

' Load compiled model
 model = XPRMloadmod("foliodata.bim", "")

 XPRMrunmod model, result, ""
 XPRMunloadmod (model)
 model = XPRM_NULL
End Sub

folioexec.bas
Attribute VB_Name = "Module1"
Option Explicit
' ********************************************************
'  Mosel Library Example Problems
'  ==============================
'  file folioexec.bas
'  ``````````````````
'  Executing a Mosel model.
'
'  (c) 2008 Fair Isaac Corporation
'      author: S.Heipcke, Aug. 2003
' ********************************************************

Sub Main()
 Dim result As Long
 Dim model

' Initialize Mosel
 XPRMinit

' Execute = compile/load/run a model
 XPRMexecmod "", "foliodata.mos", "", result, model

 XPRMunloadmod (model)
 model = XPRM_NULL
End Sub

folioparam.bas
Attribute VB_Name = "Module1"
Option Explicit
' ********************************************************
'  Mosel Library Example Problems
'  ==============================
'  file folioparam.bas
'  ```````````````````
'  Parameterized model execution.
'
'  (c) 2008 Fair Isaac Corporation
'      author: S.Heipcke, Aug. 2003
' ********************************************************

Sub Main()
 Dim result As Long
 Dim model

' Initialize Mosel
 XPRMinit

' Execute = compile/load/run a model
 XPRMexecmod "", "foliodata.mos", "OUTFILE=result2.dat,MAXRISK=0.4,MAXVAL=0.25", result, model

 XPRMunloadmod (model)
 model = XPRM_NULL
End Sub

foliodata.mos
(!******************************************************
   Mosel Example Problems
   ======================

   file foliodata.mos
   ``````````````````
   Modeling a small LP problem 
   to perform portfolio optimization.
   -- Parameters, data input from file, 
      result output to file --
   
  (c) 2008 Fair Isaac Corporation
      author: S.Heipcke, Aug. 2003, rev. June 2018
*******************************************************!)

model "Portfolio optimization with LP"
 uses "mmxprs"

 parameters
  DATAFILE= "folio.dat"              ! File with problem data
  OUTFILE= "result.dat"              ! Output file 
  MAXRISK = 1/3                      ! Max. investment into high-risk values
  MAXVAL = 0.3                       ! Max. investment per share
  MINAM = 0.5                        ! Min. investment into N.-American values
 end-parameters

 public declarations
  SHARES: set of string              ! Set of shares
  RISK: set of string                ! Set of high-risk values among shares
  NA: set of string                  ! Set of shares issued in N.-America
  RET: array(SHARES) of real         ! Estimated return in investment
 end-declarations

 initializations from DATAFILE
  RISK RET NA
 end-initializations

 public declarations
  frac: array(SHARES) of mpvar       ! Fraction of capital used per share
  Return: linctr                     ! Objective function
 end-declarations

! Objective: total return
 Return:= sum(s in SHARES) RET(s)*frac(s) 

! Limit the percentage of high-risk values
 sum(s in RISK) frac(s) <= MAXRISK

! Minimum amount of North-American values
 sum(s in NA) frac(s) >= MINAM

! Spend all the capital
 sum(s in SHARES) frac(s) = 1
 
! Upper bounds on the investment per share
 forall(s in SHARES) frac(s) <= MAXVAL

! Solve the problem
 maximize(Return)

! Solution printing to a file
 fopen(OUTFILE, F_OUTPUT)
 writeln("Total return: ", getobjval)
 forall(s in SHARES) 
  writeln(strfmt(s,-12), ": \t", strfmt(getsol(frac(s))*100,5,2), "%")
 fclose(F_OUTPUT) 
 
end-model 

folioexcel.mos
(!******************************************************
   Mosel Example Problems
   ======================

   file folioexcel.mos
   ```````````````````
   Modeling a small LP problem 
   to perform portfolio optimization.
   -- Parameters, data input from Excel, 
      result output to Excel --
   
  (c) 2008 Fair Isaac Corporation
      author: S.Heipcke, Feb. 2007
*******************************************************!)

model "Portfolio optimization with LP (Excel)"
 uses "mmxprs", "mmsheet"

 parameters
  DATAFILE = "folio.xls"             ! Spreadsheet with problem data
  DBDATA = "foliodata"               ! Spreadsheet range with problem data
  DBSOL = "folioresult"              ! Range for solution data 
  
  MAXRISK = 1/3                      ! Max. investment into high-risk values
  MAXVAL = 0.3                       ! Max. investment per share
  MINAM = 0.5                        ! Min. investment into N.-American values
 end-parameters

 declarations
  SHARES: set of string              ! Set of shares
  RET: array(SHARES) of real         ! Estimated return in investment
  RISK: array(SHARES) of boolean     ! List of high-risk values among shares
  NA: array(SHARES) of boolean       ! List of shares issued in N.-America
 end-declarations

! Data input from spreadsheet  
 initializations from "mmsheet.excel:" + DATAFILE
   [RET,RISK,NA] as DBDATA
 end-initializations

 declarations
  frac: array(SHARES) of mpvar       ! Fraction of capital used per share
 end-declarations

! Objective: total return
 Return:= sum(s in SHARES) RET(s)*frac(s) 

! Limit the percentage of high-risk values
 sum(s in SHARES | RISK(s)) frac(s) <= MAXRISK

! Minimum amount of North-American values
 sum(s in SHARES | NA(s)) frac(s) >= MINAM

! Spend all the capital
 sum(s in SHARES) frac(s) = 1
 
! Upper bounds on the investment per share
 forall(s in SHARES) frac(s) <= MAXVAL

! Solve the problem
 maximize(Return)

! Solution printing
 writeln("Total return: ", getobjval)
 forall(s in SHARES) 
  writeln(strfmt(s,-12), ": \t", strfmt(getsol(frac(s))*100,5,2), "%")

! Solution output to spreadsheet
 declarations
  Solfrac: array(SHARES) of real      ! Solution values
 end-declarations

 forall(s in SHARES) Solfrac(s):= getsol(frac(s))*100
 
 initializations to "mmsheet.excel:" + DATAFILE
   Solfrac as "grow;"+DBSOL
 end-initializations

end-model 

folioinsight.mos
(!******************************************************
   Mosel Example Problems
   ======================

   file folioinsight.mos
   `````````````````````
   Modeling a small LP problem 
   to perform portfolio optimization.
   -- Insight deployment version of foliodata.mos --
   
  (c) 2012 Fair Isaac Corporation
      author: S.Heipcke, Oct. 2012, rev. Nov. 2016
*******************************************************!)

model "Portfolio optimization"
 uses "mmxprs"                       ! Use Xpress Optimizer
 uses "mminsight"                    ! Use Xpress Insight

 version 1.0.0

 parameters
  DATAFILE= "folio.dat"              ! File with problem data
  MAXRISK = 1/3                      ! Max. investment into high-risk values
  MAXVAL = 0.3                       ! Max. investment per share
  MINAM = 0.5                        ! Min. investment into N.-American values
 end-parameters

 public declarations
  SHARES: set of string              ! Set of shares
  RISK: set of string                ! Set of high-risk values among shares
  NA: set of string                  ! Set of shares issued in N.-America
  RET: array(SHARES) of real         ! Estimated return in investment
 end-declarations

 procedure readdata
  initializations from DATAFILE
    RISK RET NA
  end-initializations
 end-procedure

 case insightgetmode of
  INSIGHT_MODE_RUN: 
      insightpopulate                ! Inject scenario data
  INSIGHT_MODE_NONE:                 ! Read in data for baseline
      readdata
  INSIGHT_MODE_LOAD: do
      readdata
      exit(0)                        ! Stop here in 'load data' mode
      end-do
  else
      writeln_("Unknown run mode")
      exit(1)
 end-case

 public declarations
  frac: array(SHARES) of mpvar       ! Fraction of capital used per share
  Return, LimitRisk, LimitAM, TotalOne: linctr   ! Constraints
 end-declarations

! Objective: total return
 Return:= sum(s in SHARES) RET(s)*frac(s) 

! Limit the percentage of high-risk values
 LimitRisk:= sum(s in RISK) frac(s) <= MAXRISK

! Minimum amount of North-American values
 LimitAM:= sum(s in NA) frac(s) >= MINAM

! Spend all the capital
 TotalOne:= sum(s in SHARES) frac(s) = 1
 
! Upper bounds on the investment per share
 forall(s in SHARES) frac(s) <= MAXVAL

! Solve the problem through Insight
 insightmaximize(Return)

! Solution printing
 writeln("Total return: ", getobjval)

end-model 

folioinsightxml.mos
(!******************************************************
   Mosel Example Problems
   ======================

   file folioinsightxml.mos
   ````````````````````````
   Modeling a small LP problem 
   to perform portfolio optimization.
   -- Insight deployment version of foliodata.mos,
      saving solution values into a Mosel array --
   
  (c) 2012 Fair Isaac Corporation
      author: S.Heipcke, Oct. 2012, rev. July 2017
*******************************************************!)

model "Portfolio optimization"
 uses "mmxprs"                       ! Use Xpress Optimizer
 uses "mminsight"                    ! Use Xpress Insight

 version 1.0.0

 parameters
  DATAFILE= "folio.dat"              ! File with problem data
  MAXRISK = 1/3                      ! Max. investment into high-risk values
  MAXVAL = 0.3                       ! Max. investment per share
  MINAM = 0.5                        ! Min. investment into N.-American values
 end-parameters

 forward procedure readdata

 !@insight.manage=input
 public declarations
  !@insight.alias Shares
  SHARES: set of string              ! Set of shares
  !@insight.alias High-risk values
  RISK: set of string                ! Set of high-risk values among shares
  !@insight.alias Shares issued in N.-America
  NA: set of string                  ! Set of shares issued in N.-America
  !@insight.alias Estimated return in investment
  RET: array(SHARES) of real         ! Estimated return in investment
 end-declarations

 !@insight.resultdata.delete=on-queue

 case insightgetmode of
  INSIGHT_MODE_RUN: 
      insightpopulate                ! Inject scenario data
  INSIGHT_MODE_NONE:                 ! Read in data for baseline
      readdata
  INSIGHT_MODE_LOAD: do
      readdata
      exit(0)                        ! Stop here in 'load data' mode
      end-do
  else
      writeln_("Unknown run mode")
      exit(1)
 end-case

 procedure readdata
  initializations from DATAFILE
    RISK RET NA
  end-initializations
 end-procedure

 !@insight.manage=result
 public declarations
  !@insight.alias Fraction used
  frac: array(SHARES) of mpvar       ! Fraction of capital used per share
  Return: linctr           !@insight.alias Total return
  LimitRisk: linctr        !@insight.alias Max. percentage of high-risk values
  LimitAM: linctr          !@insight.alias Min. percentage of North-American values
  !@insight.hidden=true
  TotalOne: linctr         !@insight.alias Spend all the capital
  !@insight.alias Constraints
  CTRS: set of string                            ! Constraint names
  !@insight.alias Value
  CTRINFO: set of string                         ! Constraint info type
  !@insight.alias Evaluation of constraints and bounds
  CtrSol: dynamic array(CTRS,CTRINFO) of real    ! Solution values 
  !@insight.alias Summary constraint activity
  CtrSolSum: dynamic array(CTRS) of real
!  TotalReturn: array(range) of real
 end-declarations

! Objective: total return
 Return:= sum(s in SHARES) RET(s)*frac(s) 

! Limit the percentage of high-risk values
 LimitRisk:= sum(s in RISK) frac(s) <= MAXRISK

! Minimum amount of North-American values
 LimitAM:= sum(s in NA) frac(s) >= MINAM

! Spend all the capital
 TotalOne:= sum(s in SHARES) frac(s) = 1
 
! Upper bounds on the investment per share
 forall(s in SHARES) frac(s) <= MAXVAL

! Solve the problem through Insight
 insightmaximize(Return)

! Save solution values for GUI display
 CtrSol::("Limit high risk shares", ["Activity","Lower limit","Upper limit"])
          [LimitRisk.act,0,MAXRISK]
 CtrSol::("Limit North-American", ["Activity","Lower limit","Upper limit"])
          [LimitAM.act,MINAM,1]
 forall(s in SHARES | frac(s).sol>0) do
  CtrSol("Limit per value: "+s,"Activity"):= frac(s).sol
  CtrSol("Limit per value: "+s,"Upper limit"):= MAXVAL
  CtrSol("Limit per value: "+s,"Lower limit"):= 0
 end-do

 CtrSolSum("Total return"):=getsol(Return)
 CtrSolSum("Total high risk shares"):=LimitRisk.act
 CtrSolSum("Total North-American"):=LimitAM.act
 CtrSolSum("Largest position"):=max(s in SHARES) frac(s).sol

end-model 

folio.vdl
<vdl version="4.7">
    <!-- Optional: number formatting function -->
    <script>
        function formatRender(data) {
            return insight.Formatter.formatNumber(data, '0.#%');
        }
    </script>
    <vdl-page class="compact">
    <!-- 'vdl' and 'vdl-page' tags must always be present -->

        <!-- 'header' element: container for any vdl elements that are not part 
             of the page layout -->
        <vdl-header>
            <vdl-action-group name="runModel">
                <vdl-action-execute mode="RUN"></vdl-action-execute>
            </vdl-action-group>
        </vdl-header>

        <!-- Structural element 'section': print header text for a section -->
        <vdl-section heading="Configuration">
            <vdl-row>
                <vdl-column size="5">
                    <vdl-form>
                        <vdl-field label="Maximum investment into high-risk values" size="3" label-size="9" parameter="MAXRISK" type="number"></vdl-field>
                        <vdl-field label="Maximum investment per share" type="number" size="3" label-size="9" parameter="MAXVAL"></vdl-field>
                        <vdl-field label="Minimum investment into North-American values" type="number" size="3" label-size="9" parameter="MINAM"></vdl-field>
                    </vdl-form>
                </vdl-column>
                <vdl-column size="4">
                    <vdl-table>
                        <vdl-table-column entity="RET" editable="true"></vdl-table-column>
                    </vdl-table>
                </vdl-column>
                <vdl-column size="3">
                    <vdl-form>
                        <!-- 'Run' button to launch optimization -->
                        <vdl-button vdl-event="click:actions.runModel" label="Run optimization"></vdl-button>
                    </vdl-form>
                </vdl-column>
            </vdl-row>
        </vdl-section>
        <vdl-section heading="Results">
            <!-- Display inline text element with objective value -->
            <vdl-row>
                <vdl-column><span vdl-text="= 'Total expected return: &#163;' +
            insight.Formatter.formatNumber(scenario.entities.Return.value, '##.00')"></span></vdl-column>
            </vdl-row>
            <vdl-row>
                <vdl-column size="4" heading="Portfolio composition">
                    <vdl-table>
                        <vdl-table-column entity="frac" render="=formatRender"></vdl-table-column>
                    </vdl-table>
                </vdl-column>
                <vdl-column size="8" heading="Evaluation of constraints">
                    <vdl-table>
                        <vdl-table-column entity="CtrSol" heading="=t.label" vdl-repeat="=t in scenario.entities.CTRINFO">
                            <vdl-index-filter set="CTRINFO" value="=t.value"></vdl-index-filter>
                        </vdl-table-column>
                    </vdl-table>
                </vdl-column>
            </vdl-row>
            <vdl-row>
                <vdl-column size="4" >
                    <vdl-chart style="width:350px;">
                        <!-- Filtering out 0-valued entries -->
                        <script>
                            function getFracData(frac, shares) {
                                if (!shares.length || !(frac && frac.toObjectArray && frac.toObjectArray().length)) {
                                    return [];
                                }
                                var result = shares
                                    .filter(function(share) {
                                        return frac(share.value).value > 0;
                                    })
                                    .map(function(share) {
                                        return [share.label, frac(share.value).value];
                                    });
                                return result;
                            }
                        </script>
                        <vdl-chart-series type="pie" data="=getFracData(scenario.entities.frac, scenario.entities.SHARES)"></vdl-chart-series>
                        <!-- Simple pie chart:-->
                        <!--    <vdl-chart-series entity="frac" type="pie"></vdl-chart-series>--></vdl-chart>
                </vdl-column>
                <vdl-column size="8">
                    <vdl-chart modifier="=function(config) {config.layout.xaxis.tickangle = 5; return config; }" style="width:700px;">
                        <vdl-chart-series entity="CtrSol" type="line" series-set="CTRINFO" heading="=t.label"></vdl-chart-series>
                        <vdl-chart-axis axis="x" type="category"></vdl-chart-axis>
                    </vdl-chart>
                </vdl-column>
            </vdl-row>
        </vdl-section>
    </vdl-page>
</vdl>

foliocompare.vdl
<vdl version="4.7">
    <vdl-page>    <!-- 'vdl' and 'vdl-page' must always be present -->
        <!-- Structural element 'section': print header text for a section -->
        <vdl-section heading="Comparison of scenario results">
            <vdl-row>
                <vdl-column>
                    <p><span vdl-text="Viewing "></span><span vdl-text="=scenarios.length"></span><span vdl-text=" scenario(s)."></span></p>
                </vdl-column>
            </vdl-row>
            <vdl-row>
                <!-- Display the solution values of constraints -->
                <vdl-column heading="Constraints and objective" size="6">
                    <vdl-table>
                        <vdl-table-column set="CTRS"></vdl-table-column>
                        <vdl-table-column entity="CtrSolSum" heading="='Results ' + s.props.name" vdl-repeat="=s,i in scenarios" scenario="=i"></vdl-table-column>
                    </vdl-table>
                </vdl-column>
		<!-- Display the 'frac' solution values -->
                <vdl-column heading="Portfolio composition" size="6">
                    <vdl-table>
                        <vdl-table-column entity="frac" heading="=s.props.name" vdl-repeat="=s,i in scenarios" scenario="=i"></vdl-table-column>
                    </vdl-table>
                </vdl-column>

            </vdl-row>
            <vdl-row>
                <!-- Display the objective values in a bar chart -->
                <vdl-column heading="Expected total return" size="6">
                    <vdl-chart>
                        <vdl-preload entities="CtrSolSum" scenarios="all"></vdl-preload>
                        <script>
                            function getData(scenarios) {
                                return scenarios.map(function(s) {
                                    return [s.props().name, s.entities.CtrSolSum()('Total return').value];
                                });
                            }
                        </script>
                        <vdl-chart-series data="=getData(scenarios)"></vdl-chart-series>
<!-- Alternative formulation using a new array 'TotalReturn'        
          <vdl-preload entities="TotalReturn" scenarios="all"></vdl-preload>
          <script>
          function getData(scenarios) {
            return scenarios.map(function (s) {
              return [s.props().name, s.entities.TotalReturn().value];
            });
          }
          </script>
          <vdl-chart-series data="=getData(scenarios)"></vdl-chart-series>
-->
                    </vdl-chart>
                </vdl-column>
            </vdl-row>
        </vdl-section>
    </vdl-page>
</vdl>

folioinsightxml.xml
<?xml version="1.0" encoding="iso-8859-1"?>
<model-companion xmlns="http://www.fico.com/xpress/optimization-modeler/model-companion" version="3.0">

  <client>
    <view-group title="Main">
      <vdl-view title="Portfolio data" default="true" path="folio.vdl" />
      <vdl-view title="Scenario comparison" default="false" path="foliocompare.vdl"/>
    </view-group>
  </client>

</model-companion>