Initializing help system before first use

Folio - Modelling examples from 'Getting started'


Type: Portfolio optimization
Rating: 2 (easy-medium)
Description:
  • Chapter 3 Inputting and Solving a Linear Programming problem
    • foliolp.mos: modeling and solving a small LP problem
    • foliolperr.mos: LP model with syntax errors
    • foliolps.mos: LP model using string indices
  • Chapter 4 Working with data
    • foliodata.mos (data file: folio.dat): data input from file, result output to a file, model parameters
    • folioodbc.mos (data files: folio.xls, folio.mdb, folio.sqlite): data input from a spreadsheet or database, result output to a spreadsheet or database, model parameters
    • folioexcel.mos (data file: folio.xls): same as folioodbc.mos but with Excel-specific data input and output (Windows only)
    • foliosheet.mos (data file: folio.xls): same as folioodbc.mos but with data input and output through generic spreadsheet access
    • foliocsv.mos (data file: folio.csv): same as folioodbc.mos but with data input and output through generic spreadsheet access in CSV format
  • Chapter 5 Drawing user graphs
    • folioloop.mos (data files: folio.dat, foliodev.dat): re-solving with varied parameter settings
    • folioloop_graph.mos (data files: folio.dat, foliodev.dat): re-solving with varied parameter settings, graphical solution display
    • foliolps_graph.mos: same as foliolps, adding graphical solution display
  • Chapter 6 Mixed Integer Programming
    • foliomip1.mos (data file: folio.dat): modeling and solving a small MIP problem (binary variables)
    • foliomip2.mos (data file: folio.dat): modeling and solving a small MIP problem (semi-continuous variables)
  • Chapter 7 Quadratic Programming
    • folioqp.mos (data file: folioqp.dat): modeling and solving a QP and a MIQP problem
    • folioqp_graph.mos (data files: folioqp.dat, folioqpgraph.dat): re-solving a QP problem with varied parameter settings, graphical solution display
    • folioqc.mos (data file: folioqp.dat): modeling and solving a QCQP and
    • foliomiqc.mos (data file: folioqp.dat): modeling and solving a MIQCQP
  • Chapter 8 Heuristics
    • folioheur.mos (data file: folio.dat): heuristic solution of a MIP problem
File(s): foliolp.mos, foliolperr.mos, foliolps.mos, foliolps_graph.mos, foliodata.mos, folioodbc.mos, folioexcel.mos, foliosheet.mos, foliocsv.mos, folioloop.mos, folioloop_graph.mos, foliomip1.mos, foliomip2.mos, folioqp.mos, folioqp_graph.mos, folioqc.mos, foliomiqc.mos, folioheur.mos
Data file(s): folio.dat, folio.csv, foliodev.dat, folioqp.dat, folioqpgraph.dat, folio.xls, folio.mdb, folio.sqlite


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

   file foliolp.mos
   ````````````````
   Modeling a small LP problem 
   to perform portfolio optimization.
   
  (c) 2008 Fair Isaac Corporation
      author: S.Heipcke, Aug. 2003
*******************************************************!)

model "Portfolio optimization with LP"
 uses "mmxprs"

 declarations
  SHARES = 1..10                     ! Set of shares
  RISK = {2,3,4,9,10}                ! Set of high-risk values among shares
  NA = {1,2,3,4}                     ! Set of shares issued in N.-America
  RET: array(SHARES) of real         ! Estimated return in investment

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

 RET:: [5,17,26,12,8,9,7,6,31,21]
 
! 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) <= 1/3

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

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

! Solve the problem
 maximize(Return)

(!
 declarations
  status:array({XPRS_OPT,XPRS_UNF,XPRS_INF,XPRS_UNB,XPRS_OTH}) of string
 end-declarations

 status::([XPRS_OPT,XPRS_UNF,XPRS_INF,XPRS_UNB,XPRS_OTH])[
          "Optimum found","Unfinished","Infeasible","Unbounded","Failed"]
 
 writeln("Problem status: ", status(getprobstat))
!)
 
! Solution printing
 writeln("Total return: ", getobjval)
 forall(s in SHARES) writeln(s, ": ", getsol(frac(s))*100, "%")  

end-model 

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

   file foliolperr.mos
   ```````````````````
   Modeling a small LP problem 
   to perform portfolio optimization.
   -- Model with syntax errors --
   
  (c) 2008 Fair Isaac Corporation
      author: S.Heipcke, Aug. 2003
*******************************************************!)

model "Portfolio optimization with LP"

 declarations
  SHARES = 1..10                     ! Set of shares
  RISK = {2,3,4,9,10}                ! Set of high-risk values among shares
  NA = {1,2,3,4}                     ! Set of shares issued in N.-America
  RET: array(SHARES) of real         ! Estimated return in investment

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

 RET:: [5,17,26,12,8,9,7,6,31,21
 
! 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) <= 1/3

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

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

! Solve the problem
 maximize(Return)
 
! Solution printing
 writeln("Total return: ", getobjval)
 forall(s in SHARES) writeln(s, ": ", getsol(frac(s))*100, "%")  

end-model 

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

   file foliolps.mos
   `````````````````
   Modeling a small LP problem 
   to perform portfolio optimization.
   -- Using string indices --
   
  (c) 2008 Fair Isaac Corporation
      author: S.Heipcke, Mar. 2006
*******************************************************!)

model "Portfolio optimization with LP"
 uses "mmxprs"

 declarations
                                     ! Set of shares
  SHARES = {"treasury", "hardware", "theater", "telecom", "brewery", 
            "highways", "cars", "bank", "software", "electronics"}
                                     ! Set of high-risk values among shares
  RISK = {"hardware", "theater", "telecom", "software", "electronics"}
                                     ! Set of shares issued in N.-America
  NA = {"treasury", "hardware", "theater", "telecom"}

  RET: array(SHARES) of real         ! Estimated return in investment

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

 RET::(["treasury", "hardware", "theater", "telecom", "brewery", "highways",
       "cars", "bank", "software", "electronics"])[5,17,26,12,8,9,7,6,31,21] 
 
! 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) <= 1/3

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

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

! Solve the problem
 maximize(Return)
 
! Solution printing
 writeln("Total return: ", getobjval)
 forall(s in SHARES) writeln(s, ": ", getsol(frac(s))*100, "%")  

end-model 

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

   file foliolps_graph.mos
   ```````````````````````
   Modeling a small LP problem 
   to perform portfolio optimization.
   -- Using string indices --
   -- Graphical representation of the solution --
   
  (c) 2017 Fair Isaac Corporation
      author: S.Heipcke, June 2017, rev. Sep. 2017
*******************************************************!)

model "Portfolio optimization with LP - graph"
 uses "mmxprs"                       ! Use Xpress Optimizer
 uses "mmsvg"

 declarations
                                     ! Set of shares
  SHARES = {"treasury", "hardware", "theater", "telecom", "brewery", 
            "highways", "cars", "bank", "software", "electronics"}
                                     ! Set of high-risk values among shares
  RISK = {"hardware", "theater", "telecom", "software", "electronics"}
                                     ! Set of shares issued in N.-America
  NA = {"treasury", "hardware", "theater", "telecom"}
  RET: array(SHARES) of real         ! Estimated return in investment

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

 RET::(["treasury", "hardware", "theater", "telecom", "brewery", "highways",
       "cars", "bank", "software", "electronics"])[5,17,26,12,8,9,7,6,31,21] 
 
! 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) <= 1/3

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

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

! Solve the problem
 maximize(Return)

! Solution printing
 writeln("Total return: ", getobjval)
 forall(s in SHARES) writeln(s, ": ", getsol(frac(s))*100, "%")  

! Solution drawing
 forall(s in SHARES) svgaddgroup("gr"+s,s)
 ttl:=0.0
 forall(s in SHARES | frac(s).sol>0) do
   svgaddpie("gr"+s, 200,200, 150, ttl, ttl+frac(s).sol)
   svgsetstyle(svggetlastobj, SVG_STROKE, SVG_GRAY)
   ttl+=frac(s).sol
 end-do

! Optionally save graphic to file
 svgsave("foliolps.svg")
 
! Set graph size 
 svgsetgraphviewbox(0,0,500,500)

! Display the graph and wait for window to be closed by the user  
 svgrefresh
 svgwaitclose("Close browser window to terminate model execution.", 1)

end-model 

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 

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

   file folioodbc.mos
   ``````````````````

   Modeling a small LP problem 
   to perform portfolio optimization.
   -- Parameters, data input through ODBC, 
      result output through ODBC --
   
   IMPORTANT: 
   If this example is run more than once,
   you need to delete the solution data from the
   previous run in the database/spreasheet.

  (c) 2008 Fair Isaac Corporation
      author: S.Heipcke, Mar. 2006, rev. Sep. 2014
*******************************************************!)

model "Portfolio optimization with LP (ODBC)"
 uses "mmxprs", "mmodbc"

 parameters
  DATAFILE = "folio.mdb"             ! Access database with problem data
!  DATAFILE = "folio.sqlite"          ! SQLite database with problem data
  
  DBDATA = "folio"                   ! Database table with problem data
  DBSOL = "foliosol"                 ! Table 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 database
 initializations from "mmodbc.odbc:" + 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 database
 declarations
  Solfrac: array(SHARES) of real      ! Solution values
 end-declarations

 forall(s in SHARES) Solfrac(s):= getsol(frac(s))*100

! Optional: Clean up previous results (works only for databases, cannot 
! be used with spreadsheets). 
! Alternatively, delete data (by hand) directly in the database. 
 SQLconnect(DATAFILE)
 SQLexecute("delete from " + DBSOL)   
 SQLdisconnect

! Data output to database 
 initializations to "mmodbc.odbc:" + DATAFILE
   Solfrac as DBSOL
 end-initializations

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 

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

   file foliosheet.mos
   ```````````````````
   Modeling a small LP problem 
   to perform portfolio optimization.
   -- Parameters, data input from Excel, 
      result output to Excel using
      generic worksheet access --
   
  (c) 2012 Fair Isaac Corporation
      author: S.Heipcke, Nov. 2012
*******************************************************!)

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.xls:" + 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.xls:" + DATAFILE
   Solfrac as "grow;"+DBSOL
 end-initializations

end-model 

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

   file foliocsv.mos
   `````````````````
   Modeling a small LP problem 
   to perform portfolio optimization.
   -- Parameters, data input from CSV, 
      result output to CSV format --
   
  (c) 2012 Fair Isaac Corporation
      author: S.Heipcke, Nov. 2012
*******************************************************!)

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

 parameters
  DATAFILE = "folio.csv"             ! CSV spreadsheet with problem data
  DBDATA = "[C6:F15]"                ! Spreadsheet range with problem data
  DBSOL = "[H6:I6]"                  ! 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.csv:" + 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.csv:" + DATAFILE
   Solfrac as "grow;"+DBSOL
 end-initializations

end-model 

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

   file folioloop.mos
   ``````````````````
   Modeling a small LP problem 
   to perform portfolio optimization.
   -- Re-solving with varied parameter settings --
   
  (c) 2008 Fair Isaac Corporation
      author: S.Heipcke, Aug. 2003
*******************************************************!)

model "Portfolio optimization with LP"
 uses "mmxprs"

 parameters
  DATAFILE= "folio.dat"              ! File with problem data
  DEVDATA= "foliodev.dat"            ! File with deviation data
  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
  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
  DEV: array(SHARES) of real         ! Standard deviation
  SOLRET: array(range) of real       ! Solution values (total return)
  SOLDEV: array(range) of real       ! Solution values (average deviation)
 end-declarations

 initializations from DATAFILE
  RISK RET NA
 end-initializations

 initializations from DEVDATA
  DEV
 end-initializations

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

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

! 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 for different limits on high-risk shares
 ct:=0
 forall(r in 0..20) do
  ! Limit the percentage of high-risk values
   Risk:= sum(s in RISK) frac(s) <= r/20

   maximize(Return)                  ! Solve the problem
   
   if (getprobstat = XPRS_OPT) then  ! Save the optimal solution value
    ct+=1
    SOLRET(ct):= getobjval
    SOLDEV(ct):= getsol(sum(s in SHARES) DEV(s)*frac(s))
    writeln(r/20, "%: ret ", SOLRET(ct), " dev ", SOLDEV(ct))
   else
    writeln("No solution for high-risk values <= ", 100*r/20, "%")
   end-if
 end-do

! Print the data 
 writeln("Low risk shares:")
 forall (s in SHARES - RISK) writeln(s, ": ret ", RET(s), " dev ", DEV(s))
 
 writeln("High risk shares:")
 forall (s in RISK) writeln(s, ": ret ", RET(s), " dev ", DEV(s))
  
end-model 

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

   file folioloop_graph.mos
   ````````````````````````
   Modeling a small LP problem 
   to perform portfolio optimization.
   -- Re-solving with varied parameter settings,
      graphical solution display --
   
  (c) 2008 Fair Isaac Corporation
      author: S.Heipcke, Aug. 2003, rev. Sep. 2017
*******************************************************!)

model "Portfolio optimization with LP"
 uses "mmxprs", "mmsvg"             ! Use Xpress Optimizer with SVG graphing

 parameters
  DATAFILE= "folio.dat"             ! File with problem data
  DEVDATA= "foliodev.dat"           ! File with deviation data
  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
  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
  DEV: array(SHARES) of real        ! Standard deviation
  SOLRET: array(range) of real      ! Solution values (total return)
  SOLDEV: array(range) of real      ! Solution values (average deviation)
 end-declarations

 initializations from DATAFILE
  RISK RET NA
 end-initializations

 initializations from DEVDATA
  DEV
 end-initializations

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

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

! 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 for different limits on high-risk shares
 ct:=0
 forall(r in 0..20) do
  ! Limit the percentage of high-risk values
   Risk:= sum(s in RISK) frac(s) <= r/20

   maximize(Return)                  ! Solve the problem
   
   if (getprobstat = XPRS_OPT) then  ! Save the optimal solution value
    ct+=1
    SOLRET(ct):= getobjval
    SOLDEV(ct):= getsol(sum(s in SHARES) DEV(s)*frac(s))
   else
    writeln("No solution for high-risk values <= ", 100*r/20, "%")
   end-if
 end-do

! Drawing a graph to represent results (`GrS') and data (`GrL' & `GrH') 

 svgaddgroup("GrS", "Solution values", SVG_GREY)
 svgaddgroup("GrL", "Low risk", SVG_GREEN)
 svgaddgroup("GrH", "High risk", SVG_RED)
 
 forall(r in 1..ct) svgaddpoint("GrS", SOLRET(r), SOLDEV(r))
 svgaddline("GrS", sum(r in 1..ct) [SOLRET(r), SOLDEV(r)])
    
 forall(s in SHARES - RISK) do
  svgaddpoint("GrL", RET(s), DEV(s))
  svgaddtext("GrL", RET(s)+1, 1.3*(DEV(s)-1), s)
 end-do

 forall(s in RISK) do
  svgaddpoint("GrH", RET(s), DEV(s))
  svgaddtext("GrH", RET(s)-2.5, DEV(s)-1, s)
 end-do

! Scale the size of the displayed graph
 svgsetgraphscale(10)
 svgsetgraphpointsize(2)
 svgsetgraphlabels("Expected return", "Standard deviation")

! Optionally save graphic to file
 svgsave("foliograph.svg")

! Display the graph and wait for window to be closed by the user 
 svgrefresh
 svgwaitclose("Close browser window to terminate model execution.", 1)

end-model 

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

   file foliomip1.mos
   ``````````````````
   Modeling a small MIP problem 
   to perform portfolio optimization.
   -- Limiting the total number of assets --
   
  (c) 2008 Fair Isaac Corporation
      author: S.Heipcke, Aug. 2003, rev. Oct. 2011
*******************************************************!)

model "Portfolio optimization with MIP"
 uses "mmxprs"

 parameters
  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
  MAXNUM = 4                        ! Max. number of different assets
 end-parameters

 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 "folio.dat"
  RISK RET NA
 end-initializations

 declarations
  frac: array(SHARES) of mpvar      ! Fraction of capital used per share
  buy: array(SHARES) of mpvar       ! 1 if asset is in portfolio, 0 otherwise
 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

! Limit the total number of assets
 sum(s in SHARES) buy(s) <= MAXNUM

 forall(s in SHARES) do
  buy(s) is_binary                  ! Turn variables into binaries
  frac(s) <= buy(s)                 ! Linking the variables
 end-do

! Uncomment this line to see the Optimizer log
 setparam("XPRS_VERBOSE",true)      ! Enable logging output

! Uncomment the following lines to obtain a branch-and-bound tree
(!
 setparam("XPRS_CUTSTRATEGY",0)     ! Disable automatic cut generation
 setparam("XPRS_HEURSTRATEGY",0)    ! Disable MIP heuristics
 setparam("XPRS_PRESOLVE",0)        ! Disable presolve
!)

! Solve the problem
 maximize(Return)

! Solution printing
 writeln("Total return: ", getobjval)
 forall(s in SHARES)
  writeln(s, ": ", getsol(frac(s))*100, "% (", getsol(buy(s)), ")")
 
end-model 

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

   file foliomip2.mos
   ``````````````````
   Modeling a small MIP problem 
   to perform portfolio optimization.
   -- Imposing a minimum investment per share --
   
  (c) 2008 Fair Isaac Corporation
      author: S.Heipcke, Aug. 2003
*******************************************************!)

model "Portfolio optimization with MIP"
 uses "mmxprs"

 parameters
  MAXRISK = 1/3                     ! Max. investment into high-risk values
  MINAM = 0.5                       ! Min. investment into N.-American values
  MAXVAL = 0.3                      ! Max. investment per share
  MINVAL = 0.1                      ! Min. investment per share
 end-parameters

 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 "folio.dat"
  RISK RET NA
 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 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 and lower bounds on the investment per share
 forall(s in SHARES) do
  frac(s) <= MAXVAL
  frac(s) is_semcont MINVAL
 end-do

! Solve the problem
 maximize(Return)

! Solution printing
 writeln("Total return: ", getobjval)
 forall(s in SHARES) writeln(s, ": ", getsol(frac(s))*100, "%")  
 
end-model 

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

   file folioqp.mos
   ````````````````
   Modeling a small QP problem 
   to perform portfolio optimization.
   -- 1. QP: minimize variance
      2. MIQP: limited number of assets ---
   
  (c) 2008 Fair Isaac Corporation
      author: S.Heipcke, Aug. 2003, rev. Sep. 2017
*******************************************************!)

model "Portfolio optimization with QP/MIQP"
 uses "mmxprs", "mmnl"

 parameters
  MAXVAL = 0.3                      ! Max. investment per share
  MINAM = 0.5                       ! Min. investment into N.-American values
  MAXNUM = 4                        ! Max. number of different assets
  TARGET = 9.0                      ! Minimum target yield
 end-parameters

 declarations
  SHARES = 1..10                    ! Set of shares
  RISK: set of integer              ! Set of high-risk values among shares
  NA: set of integer                ! Set of shares issued in N.-America
  RET: array(SHARES) of real        ! Estimated return in investment
  VAR: array(SHARES,SHARES) of real ! Variance/covariance matrix of
                                    ! estimated returns
 end-declarations

 initializations from "folioqp.dat"
  RISK RET NA VAR
 end-initializations

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

! **** First problem: unlimited number of assets ****

! Objective: mean variance
 Variance:= sum(s,t in SHARES) VAR(s,t)*frac(s)*frac(t) 

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

! Spend all the capital
 sum(s in SHARES) frac(s) = 1
 
! Target yield
 sum(s in SHARES) RET(s)*frac(s) >=  TARGET

! Upper bounds on the investment per share
 forall(s in SHARES) frac(s) <= MAXVAL

! Solve the problem
 minimize(Variance)

! Solution printing
 writeln("With a target of ", TARGET, " minimum variance is ", getobjval)
 forall(s in SHARES) writeln(s, ": ", getsol(frac(s))*100, "%")  

! **** Second problem: limit total number of assets ****

 declarations
  buy: array(SHARES) of mpvar       ! 1 if asset is in portfolio, 0 otherwise
 end-declarations

! Limit the total number of assets
 sum(s in SHARES) buy(s) <= MAXNUM

 forall(s in SHARES) do
  buy(s) is_binary
  frac(s) <= buy(s)
 end-do

! Solve the problem
 minimize(Variance)

 writeln("With a target of ", TARGET," and at most ", MAXNUM,
          " assets,\n minimum variance is ", getobjval)
 forall(s in SHARES) writeln(s, ": ", getsol(frac(s))*100, "%") 
 
end-model 

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

   file folioqp_graph.mos
   ``````````````````````
   Modeling a small QP problem 
   to perform portfolio optimization.
   Minimize variance subject to different target return.
   Graphical output.
   
  (c) 2008 Fair Isaac Corporation
      author: S.Heipcke, Aug. 2003, rev. Sep. 2017
*******************************************************!)

model "Portfolio optimization with QP, graphical output"
 uses "mmxprs", "mmnl", "mmsvg"      ! Use Xpress Optimizer with QP solver

 parameters
  MAXVAL = 0.3                       ! Max. investment per share
  MINAM = 0.5                        ! Min. investment into N.-American values
 end-parameters

 declarations
  SHARES = 1..10                     ! Set of shares
  RISK: set of integer               ! Set of high-risk values among shares
  NA: set of integer                 ! Set of shares issued in N.-America
  RET: array(SHARES) of real         ! Estimated return in investment
  VAR: array(SHARES,SHARES) of real  ! Variance/covariance matrix of
                                     ! estimated returns
  SOLRET: array(range) of real       ! Solution values (total return)
  SOLDEV: array(range) of real       ! Solution values (average deviation)
 end-declarations

 initializations from "folioqp.dat"
  RISK RET NA VAR
 end-initializations

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

! Objective: mean variance
 Variance:= sum(s,t in SHARES) VAR(s,t)*frac(s)*frac(t) 

! 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 for a range of returns: this is the efficient frontier
 target:= min(s in SHARES) RET(s)
 RMAX:= max(s in SHARES) RET(s)

 while(target < RMAX) do
   Return:= sum(s in SHARES) RET(s)*frac(s) >= target    ! Target yield
   minimize(Variance)                ! Solve the problem
   
   if (getprobstat = XPRS_OPT) then  ! Save the optimal solution value
    ct+=1
    SOLDEV(ct):= getobjval
    SOLRET(ct):= target
   else
    writeln("No solution for target return >= ", ct, "%")
    break
   end-if
   target += 1
 end-do

! Drawing a graph to represent results (`GrS') and data (`GrL' & `GrH') 
 declarations
  DEV: array(SHARES) of real         ! Standard deviation
  NAMES: array(SHARES) of string     ! Names of shares
 end-declarations

 initializations from "folioqpgraph.dat"
  DEV NAMES
 end-initializations
	
 svgaddgroup("GrS", "Solution values", SVG_GREY)
 svgaddgroup("GrL", "Low risk", SVG_GREEN)
 svgaddgroup("GrH", "High risk", SVG_RED)
 
 forall(r in 1..ct) svgaddpoint("GrS", SOLRET(r), SOLDEV(r));

 svgaddline("GrS", sum(r in 1..ct) [SOLRET(r), SOLDEV(r)])
    
 forall (s in SHARES-RISK) do
  svgaddpoint("GrL", RET(s), DEV(s))
  svgaddtext("GrL", RET(s)+1, 1.3*(DEV(s)-1), NAMES(s))
 end-do

 forall (s in RISK) do
  svgaddpoint("GrH", RET(s), DEV(s))
  svgaddtext("GrH", RET(s)-2.5, DEV(s)-1, NAMES(s))
 end-do

! Scale the size of the displayed graph
 svgsetgraphscale(10)
 svgsetgraphpointsize(2)
 svgsetgraphlabels("Expected return", "Standard deviation")

! Optionally save graphic to file
 svgsave("folioqpgraph.svg")

! Display the graph and wait for window to be closed by the user 
 svgrefresh
 svgwaitclose("Close browser window to terminate model execution.", 1)

end-model 

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

   file folioqc.mos
   ````````````````
   Modeling a small QCQP problem 
   to perform portfolio optimization.
   -- Maximize return with limit on variance ---
   
  (c) 2008 Fair Isaac Corporation
      author: S.Heipcke, July 2008
*******************************************************!)

model "Portfolio optimization with QCQP"
 uses "mmxprs", "mmnl"

 parameters
  MAXVAL = 0.3                      ! Max. investment per share
  MINAM = 0.5                       ! Min. investment into N.-American values
  MAXVAR = 0.55                     ! Max. allowed variance
 end-parameters

 declarations
  SHARES = 1..10                    ! Set of shares
  NA: set of integer                ! Set of shares issued in N.-America
  RET: array(SHARES) of real        ! Estimated return in investment
  VAR: array(SHARES,SHARES) of real ! Variance/covariance matrix of
                                    ! estimated returns
 end-declarations

 initializations from "folioqp.dat"
  RET NA VAR
 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) 

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

! Spend all the capital
 sum(s in SHARES) frac(s) = 1
 
! Limit variance
 sum(s,t in SHARES) VAR(s,t)*frac(s)*frac(t) <= MAXVAR

! Upper bounds on the investment per share
 forall(s in SHARES) frac(s) <= MAXVAL

! Solve the problem
 maximize(Return)

! Solution printing
 writeln("With a max. variance of ", MAXVAR, " total return is ", getobjval)
 forall(s in SHARES) writeln(s, ": ", getsol(frac(s))*100, "%")  

end-model 

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

   file foliomiqc.mos
   ``````````````````
   Modeling a small MIQCQP problem 
   to perform portfolio optimization.
   -- Maximize return with limit on variance
      and limited number of assets ---
   
  (c) 2008 Fair Isaac Corporation
      author: S.Heipcke, July 2008, rev. Mar. 2013
*******************************************************!)

model "Portfolio optimization with MIQCQP"
 uses "mmxnlp"

 parameters
  MAXVAL = 0.3                      ! Max. investment per share
  MINAM = 0.5                       ! Min. investment into N.-American values
  MAXNUM = 4                        ! Max. number of different assets
  MAXVAR = 1.25                     ! Max. allowed variance
 end-parameters

 declarations
  SHARES = 1..10                    ! Set of shares
  NA: set of integer                ! Set of shares issued in N.-America
  RET: array(SHARES) of real        ! Estimated return in investment
  VAR: array(SHARES,SHARES) of real ! Variance/covariance matrix of
                                    ! estimated returns
 end-declarations

 initializations from "folioqp.dat"
  RET NA VAR
 end-initializations

 declarations
  frac: array(SHARES) of mpvar      ! Fraction of capital used per share
  buy: array(SHARES) of mpvar       ! 1 if asset is in portfolio, 0 otherwise
 end-declarations

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

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

! Spend all the capital
 sum(s in SHARES) frac(s) = 1
 
! Limit variance
 sum(s,t in SHARES) VAR(s,t)*frac(s)*frac(t) <= MAXVAR

! Upper bounds on the investment per share
 forall(s in SHARES) frac(s) <= MAXVAL

! Limit the total number of assets
 sum(s in SHARES) buy(s) <= MAXNUM

 forall(s in SHARES) do
  buy(s) is_binary
  frac(s) <= buy(s)
 end-do
 
 setparam("XPRS_verbose", true)
! Solve the problem
 maximize(Return)

! Solution printing
 writeln("With a max. variance of ", MAXVAR, " and at most ", MAXNUM,
          " assets,\n total return is ", getsol(Return))
 forall(s in SHARES) writeln(s, ": ", getsol(frac(s))*100, "%")  

end-model 

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

   file folioheur.mos
   ``````````````````
   Modeling a small MIP problem 
   to perform portfolio optimization.
   -- Heuristic solution --
   
  (c) 2008 Fair Isaac Corporation
      author: S.Heipcke, Aug. 2003, rev. June 2010
*******************************************************!)

model "Portfolio optimization solved heuristically"
 uses "mmxprs"

 parameters
  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
  MAXNUM = 4                        ! Max. number of assets
 end-parameters

 forward procedure solve_heur       ! Binary variable fixing heuristic

 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 "folio.dat"
  RISK RET NA
 end-initializations

 declarations
  frac: array(SHARES) of mpvar      ! Fraction of capital used per share
  buy: array(SHARES) of mpvar       ! 1 if asset is in portfolio, 0 otherwise
 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

! Limit the total number of assets
 sum(s in SHARES) buy(s) <= MAXNUM

 forall(s in SHARES) do
  buy(s) is_binary
  frac(s) <= buy(s)
 end-do

! Solve problem heuristically
 solve_heur

! Solve the problem
 maximize(Return)

! Solution printing
 if getprobstat=XPRS_OPT then
  writeln("Exact solution: Total return: ", getobjval)
  forall(s in SHARES) writeln(s, ": ", getsol(frac(s))*100, "%")  
 else
  writeln("Heuristic solution is optimal.")
 end-if

!-----------------------------------------------------------------

 procedure solve_heur
  declarations
   TOL: real                       ! Solution feasibility tolerance
   fsol: array(SHARES) of real     ! Solution values for `frac' variables
   bas: basis                      ! LP basis
  end-declarations

  setparam("XPRS_VERBOSE",true)    ! Enable message printing in mmxprs
  setparam("XPRS_CUTSTRATEGY",0)   ! Disable automatic cuts (optional)
  setparam("XPRS_HEURSTRATEGY",0)  ! Disable MIP heuristics (optional)
  setparam("XPRS_PRESOLVE",0)      ! Switch off presolve (required)
  TOL:=getparam("XPRS_FEASTOL")    ! Get feasibility tolerance
  setparam("ZEROTOL",TOL)          ! Set comparison tolerance
  
  maximize(XPRS_LPSTOP,Return)     ! Solve the LP problem
  savebasis(bas)                   ! Save the current basis 

 ! Fix all variables `buy' for which `frac' is at 0 or at a relatively 
 ! large value  
  forall(s in SHARES) do
   fsol(s):= getsol(frac(s))
   if (fsol(s) = 0) then 
    setub(buy(s), 0)
   elif (fsol(s) >= 0.2) then
    setlb(buy(s), 1)
   end-if
  end-do 

  maximize(XPRS_CONT,Return)       ! Solve the MIP problem
  ifgsol:=false
  if getprobstat=XPRS_OPT then     ! If an integer feas. solution was found 
   ifgsol:=true
   solval:=getobjval               ! Get the value of the best solution 
   writeln("Heuristic solution: Total return: ", solval)
   forall(s in SHARES) writeln(s, ": ", getsol(frac(s))*100, "%")
  end-if

 ! Reset variables to their original bounds 
  forall(s in SHARES)
   if ((fsol(s) = 0) or (fsol(s) >= 0.2)) then
    setlb(buy(s), 0)
    setub(buy(s), 1)
   end-if

  loadbasis(bas)                   ! Load the saved basis: bound changes are
                                   ! immediately passed on to the optimizer 
                                   ! if the problem has not been modified
                                   ! in any other way, so that there is no 
                                   ! need to reload the matrix 
  if ifgsol then                   ! Set cutoff to the best known solution 
   setparam("XPRS_MIPABSCUTOFF", solval+TOL)
  end-if

 end-procedure
 
end-model