Folio - Examples from 'Getting Started'
|
|
Type: | Portfolio optimization |
Rating: | 3 (intermediate) |
Description: | Different versions of a portfolio optimization problem. Basic modelling and solving tasks:
|
File(s): | foliolp.cs, foliolp.csproj, folioinit.cs, folioinit.csproj, foliodata.cs, foliodata.csproj, foliomip1.cs, foliomip1.csproj, foliomip2.cs, foliomip2.csproj, folioqp.cs, folioqp.csproj, folioheur.cs, folioheur.csproj, foliomip3.cs, foliomip3.csproj, folioiis.cs, folioiis.csproj |
Data file(s): | foliocpplp.dat, folio10.cdat |
|
foliolp.cs |
/******************************************************** Xpress-BCL C# Example Problems ============================== file foliolp.cs ``````````````` Modeling a small LP problem to perform portfolio optimization. (c) 2008-2024 Fair Isaac Corporation authors: S.Heipcke, D.Brett. ********************************************************/ using System; using System.Text; using System.IO; using BCL; namespace Examples { public class TestUGFolioLP { const int NSHARES = 10; // Number of shares const int NRISK = 5; // Number of high-risk shares const int NNA = 4; // Number of North-American shares double[] RET = {5,17,26,12,8,9,7,6,31,21}; // Estimated return in investment int[] RISK = {1,2,3,8,9}; // High-risk values among shares int[] NA = {0,1,2,3}; // Shares issued in N.-America public static void Main() { XPRB.init(); int s; XPRBprob p = new XPRBprob("FolioLP"); // Initialize a new problem in BCL XPRBexpr Risk,Na,Return,Cap; XPRBvar[] frac = new XPRBvar[NSHARES]; // Fraction of capital used per share TestUGFolioLP TestInstance = new TestUGFolioLP(); // Create the decision variables for(s=0;s<NSHARES;s++) frac[s] = p.newVar("frac"); //, XPRB_PL, 0, 0.3); // Objective: total return Return = new XPRBexpr(); for (s = 0; s < NSHARES; s++) Return += TestInstance.RET[s] * frac[s]; p.setObj(p.newCtr("Objective", Return)); // Set the objective function // Limit the percentage of high-risk values Risk = new XPRBexpr(); for (s = 0; s < NRISK; s++) Risk += frac[TestInstance.RISK[s]]; p.newCtr("Risk", Risk <= 1.0/3); /* Equivalent: XPRBctr CRisk; CRisk = p.newCtr("Risk"); for(s=0;s<NRISK;s++) CRisk.addTerm(frac[RISK[s]], 1); CRisk.setType(XPRB_L); CRisk.addTerm(1.0/3); */ // Minimum amount of North-American values Na = new XPRBexpr(); for (s = 0; s < NNA; s++) Na += frac[TestInstance.NA[s]]; p.newCtr("NA", Na >= 0.5); // Spend all the capital Cap = new XPRBexpr(); for(s=0;s<NSHARES;s++) Cap += frac[s]; p.newCtr("Cap", Cap == 1); // Upper bounds on the investment per share for(s=0;s<NSHARES;s++) frac[s].setUB(0.3); // Export matrix to a file /* p.exportProb(XPRB_MPS, "Folio"); p.setSense(XPRB_MAXIM); p.exportProb(XPRB_LP, "Folio"); */ // Disable all BCL and Optimizer message printing, except error messages // p.setMsgLevel(1); // Solve the problem p.setSense(BCLconstant.XPRB_MAXIM); p.lpOptimize(); /* Solve the LP-problem */ string[] LPSTATUS = {"not loaded", "optimal", "infeasible", "worse than cutoff", "unfinished", "unbounded", "cutoff in dual"}; System.Console.WriteLine("Problem status: " + LPSTATUS[p.getLPStat()]); // Solution printing System.Console.WriteLine("Total return: " + p.getObjVal()); for(s=0;s<NSHARES;s++) System.Console.WriteLine(s + ": " + frac[s].getSol()*100 + "%"); return; } } } |
foliolp.csproj |
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net5.0</TargetFramework> <IsPackable>false</IsPackable> </PropertyGroup> <ItemGroup> <PackageReference Include="FICO.Xpress.XPRBdn" Version="4.14.0" /> <!-- Version 4.14.0 or later --> </ItemGroup> </Project> |
folioinit.cs |
/******************************************************** Xpress-BCL C# Example Problems ============================== file folioinit.cs ````````````````` Modeling a small LP problem to perform portfolio optimization. Explicit initialization. (c) 2008-2024 Fair Isaac Corporation authors: S.Heipcke, D.Brett. ********************************************************/ using System; using System.Text; using System.IO; using BCL; namespace Examples { public class TestUGFolioInit { const int NSHARES = 10; // Number of shares const int NRISK = 5; // Number of high-risk shares const int NNA = 4; // Number of North-American shares double[] RET = {5,17,26,12,8,9,7,6,31,21}; // Estimated return in investment int[] RISK = {1,2,3,8,9}; // High-risk values among shares int[] NA = {0,1,2,3}; // Shares issued in N.-America public void solveProb() { XPRB.init(); int s; XPRBprob p = new XPRBprob("FolioLP"); // Initialize a new problem in BCL XPRBexpr Risk,Na,Return,Cap; XPRBvar[] frac = new XPRBvar[NSHARES]; // Fraction of capital used per share // Create the decision variables for(s=0;s<NSHARES;s++) frac[s] = p.newVar("frac"); // Objective: total return Return = new XPRBexpr(); for(s=0;s<NSHARES;s++) Return += RET[s]*frac[s]; p.setObj(p.newCtr("Objective", Return)); // Set the objective function // Limit the percentage of high-risk values Risk = new XPRBexpr(); for(s=0;s<NRISK;s++) Risk += frac[RISK[s]]; p.newCtr("Risk", Risk <= 1.0/3); // Minimum amount of North-American values Na = new XPRBexpr(); for(s=0;s<NNA;s++) Na += frac[NA[s]]; p.newCtr("NA", Na >= 0.5); // Spend all the capital Cap = new XPRBexpr(); for(s=0;s<NSHARES;s++) Cap += frac[s]; p.newCtr("Cap", Cap == 1); // Upper bounds on the investment per share for(s=0;s<NSHARES;s++) frac[s].setUB(0.3); // Solve the problem p.setSense(BCLconstant.XPRB_MAXIM); p.lpOptimize(); /* Solve the LP-problem */ string[] LPSTATUS = {"not loaded", "optimal", "infeasible", "worse than cutoff", "unfinished", "unbounded", "cutoff in dual"}; System.Console.WriteLine("Problem status: " + LPSTATUS[p.getLPStat()]); // Solution printing System.Console.WriteLine("Total return: " + p.getObjVal()); for(s=0;s<NSHARES;s++) System.Console.WriteLine(s + ": " + frac[s].getSol()*100 + "%"); } public static void Main() { TestUGFolioInit TestInstance = new TestUGFolioInit(); if(XPRB.init() != 0) { System.Console.WriteLine("Initialization failed."); return; } TestInstance.solveProb(); return; } } } |
folioinit.csproj |
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net5.0</TargetFramework> <IsPackable>false</IsPackable> </PropertyGroup> <ItemGroup> <PackageReference Include="FICO.Xpress.XPRBdn" Version="4.14.0" /> <!-- Version 4.14.0 or later --> </ItemGroup> </Project> |
foliodata.cs |
/******************************************************** Xpress-BCL C# Example Problems ============================== file foliodata.cs ````````````````` Modeling a small LP problem to perform portfolio optimization. -- Data input from file -- (c) 2008-2024 Fair Isaac Corporation authors: S.Heipcke, D.Brett. ********************************************************/ using System; using System.Text; using System.IO; using BCL; namespace Examples { public class TestUGFolioData { //Define XPRBDATAPATH to wherever you have placed the data folder; here we expect it to be same directory as compiled example. static string XPRBDATAPATH = Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location).FullName + "/Data"; static string DATAFILE = XPRBDATAPATH + "/GS/foliocpplp.dat"; const int NSHARES = 10; // Number of shares const int NRISK = 5; // Number of high-risk shares const int NNA = 4; // Number of North-American shares // Estimated return in investment double[] RET = new double[NSHARES]; // High-risk values among shares string[] RISK = {"hardware", "theater", "telecom", "software", "electronics"}; // Shares issued in N.-America string[] NA = {"treasury", "hardware", "theater", "telecom"}; // Set of shares XPRBindexSet SHARES; // Initialize a new problem in BCL XPRBprob p = new XPRBprob("FolioLP"); public void readData() { double value; int s; string name; FileStream file; StreamReader fileStreamIn; // Create the `SHARES' index set SHARES=p.newIndexSet("Shares",NSHARES); // Read `RET' data from file file = new FileStream(DATAFILE, FileMode.Open, FileAccess.Read); fileStreamIn = new StreamReader(file); object[] outdata = new object[2]; for (s = 0; s < NSHARES; s++) { p.XPRBreadline(fileStreamIn, 200, "{S} {g}", out outdata); name = (string)outdata[0]; value = (double)outdata[1]; RET[SHARES + name] = value; } fileStreamIn.Close(); file.Close(); SHARES.print(); // Print out the set contents } public static void Main() { XPRB.init(); int s; XPRBexpr Risk,Na,Return,Cap; // Fraction of capital used per share XPRBvar[] frac = new XPRBvar[NSHARES]; TestUGFolioData TestInstance = new TestUGFolioData(); // Read data from file TestInstance.readData(); // Create the decision variables for (s = 0; s < NSHARES; s++) frac[s] = TestInstance.p.newVar("frac"); // Objective: total return Return = new XPRBexpr(); for (s = 0; s < NSHARES; s++) Return += TestInstance.RET[s] * frac[s]; // Set the objective function TestInstance.p.setObj(TestInstance.p.newCtr("Objective", Return)); // Limit the percentage of high-risk values Risk = new XPRBexpr(); for (s = 0; s < NRISK; s++) Risk+=frac[TestInstance.SHARES.getIndex(TestInstance.RISK[s])]; TestInstance.p.newCtr("Risk", Risk <= 1.0 / 3); // Minimum amount of North-American values Na = new XPRBexpr(); for (s = 0; s < NNA; s++) Na += frac[TestInstance.SHARES.getIndex(TestInstance.NA[s])]; TestInstance.p.newCtr("NA", Na >= 0.5); // Spend all the capital Cap = new XPRBexpr(); for(s=0;s<NSHARES;s++) Cap += frac[s]; TestInstance.p.newCtr("Cap", Cap == 1); // Upper bounds on the investment per share for(s=0;s<NSHARES;s++) frac[s].setUB(0.3); // Solve the problem TestInstance.p.setSense(BCLconstant.XPRB_MAXIM); TestInstance.p.lpOptimize(); /* Solve the LP-problem */ // Solution printing System.Console.WriteLine("Total return: " + TestInstance.p.getObjVal()); for(s=0;s<NSHARES;s++) System.Console.WriteLine(TestInstance.SHARES.getIndexName(s) + ": " + frac[s].getSol() * 100 + "%"); return; } } } |
foliodata.csproj |
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net5.0</TargetFramework> <IsPackable>false</IsPackable> </PropertyGroup> <ItemGroup> <Content Include="../../../Data/GS/foliocpplp.dat"> <CopyToOutputDirectory>Always</CopyToOutputDirectory> <LinkBase>Data/GS</LinkBase> </Content> </ItemGroup> <ItemGroup> <PackageReference Include="FICO.Xpress.XPRBdn" Version="4.14.0" /> <!-- Version 4.14.0 or later --> </ItemGroup> </Project> |
foliomip1.cs |
/******************************************************** Xpress-BCL C# Example Problems ============================== file foliomip1.cs ````````````````` Modeling a small MIP problem to perform portfolio optimization. -- Limiting the total number of assets -- (c) 2008-2024 Fair Isaac Corporation authors: S.Heipcke, D.Brett. ********************************************************/ using System; using System.Text; using System.IO; using BCL; namespace Examples { public class TestUGFolioMip1 { const int MAXNUM = 4; // Max. number of different assets const int NSHARES = 10; // Number of shares const int NRISK = 5; // Number of high-risk shares const int NNA = 4; // Number of North-American shares double[] RET = {5,17,26,12,8,9,7,6,31,21}; // Estimated return in investment int[] RISK = {1,2,3,8,9}; // High-risk values among shares int[] NA = {0,1,2,3}; // Shares issued in N.-America public static void Main() { XPRB.init(); int s; XPRBprob p = new XPRBprob("FolioMIP1"); // Initialize a new problem in BCL XPRBexpr Risk,Na,Return,Cap,Num; XPRBvar[] frac = new XPRBvar[NSHARES]; // Fraction of capital used per share XPRBvar[] buy = new XPRBvar[NSHARES]; // 1 if asset is in portfolio, 0 otherwise TestUGFolioMip1 TestInstance = new TestUGFolioMip1(); // Create the decision variables (including upper bounds for `frac') for(s=0;s<NSHARES;s++) { frac[s] = p.newVar("frac", BCLconstant.XPRB_PL, 0, 0.3); buy[s] = p.newVar("buy", BCLconstant.XPRB_BV); } // Objective: total return Return = new XPRBexpr(); for (s = 0; s < NSHARES; s++) Return += TestInstance.RET[s] * frac[s]; p.setObj(p.newCtr("Objective", Return)); // Set the objective function // Limit the percentage of high-risk values Risk = new XPRBexpr(); for (s = 0; s < NRISK; s++) Risk += frac[TestInstance.RISK[s]]; p.newCtr(Risk <= 1.0/3); // Minimum amount of North-American values Na = new XPRBexpr(); for (s = 0; s < NNA; s++) Na += frac[TestInstance.NA[s]]; p.newCtr(Na >= 0.5); // Spend all the capital Cap = new XPRBexpr(); for(s=0;s<NSHARES;s++) Cap += frac[s]; p.newCtr(Cap == 1); // Limit the total number of assets Num = new XPRBexpr(); for(s=0;s<NSHARES;s++) Num += buy[s]; p.newCtr(Num <= MAXNUM); // Linking the variables for(s=0;s<NSHARES;s++) p.newCtr(frac[s] <= buy[s]); // Solve the problem p.setSense(BCLconstant.XPRB_MAXIM); p.mipOptimize(); /* Solve the LP-problem */ string[] MIPSTATUS = {"not loaded", "not optimized", "LP optimized", "unfinished (no solution)", "unfinished (solution found)", "infeasible", "optimal"}; System.Console.WriteLine("Problem status: " + MIPSTATUS[p.getMIPStat()]); // Solution printing System.Console.WriteLine("Total return: " + p.getObjVal()); for(s=0;s<NSHARES;s++) System.Console.WriteLine(s + ": " + frac[s].getSol()*100 + "% (" + buy[s].getSol() + ")"); return; } } } |
foliomip1.csproj |
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net5.0</TargetFramework> <IsPackable>false</IsPackable> </PropertyGroup> <ItemGroup> <PackageReference Include="FICO.Xpress.XPRBdn" Version="4.14.0" /> <!-- Version 4.14.0 or later --> </ItemGroup> </Project> |
foliomip2.cs |
/******************************************************** Xpress-BCL C# Example Problems ============================== file foliomip2.cs ````````````````` Modeling a small MIP problem to perform portfolio optimization. -- Imposing a minimum investment per share -- (c) 2008-2024 Fair Isaac Corporation authors: S.Heipcke, D.Brett. ********************************************************/ using System; using System.Text; using System.IO; using BCL; namespace Examples { public class TestUGFolioMip2 { const int NSHARES = 10; // Number of shares const int NRISK = 5; // Number of high-risk shares const int NNA = 4; // Number of North-American shares double[] RET = {5,17,26,12,8,9,7,6,31,21}; // Estimated return in investment int[] RISK = {1,2,3,8,9}; // High-risk values among shares int[] NA = {0,1,2,3}; // Shares issued in N.-America public static void Main() { XPRB.init(); int s; XPRBprob p = new XPRBprob("FolioSC"); // Initialize a new problem in BCL XPRBexpr Risk,Na,Return,Cap; XPRBvar[] frac = new XPRBvar[NSHARES]; // Fraction of capital used per share TestUGFolioMip2 TestInstance = new TestUGFolioMip2(); // Create the decision variables for(s=0;s<NSHARES;s++) { frac[s] = p.newVar("frac", BCLconstant.XPRB_SC, 0, 0.3); frac[s].setLim(0.1); } // Objective: total return Return = new XPRBexpr(); for (s = 0; s < NSHARES; s++) Return += TestInstance.RET[s] * frac[s]; p.setObj(p.newCtr("Objective", Return)); // Set the objective function // Limit the percentage of high-risk values Risk = new XPRBexpr(); for (s = 0; s < NRISK; s++) Risk += frac[TestInstance.RISK[s]]; p.newCtr(Risk <= 1.0/3); // Minimum amount of North-American values Na = new XPRBexpr(); for (s = 0; s < NNA; s++) Na += frac[TestInstance.NA[s]]; p.newCtr(Na >= 0.5); // Spend all the capital Cap = new XPRBexpr(); for(s=0;s<NSHARES;s++) Cap += frac[s]; p.newCtr(Cap == 1); // Solve the problem p.setSense(BCLconstant.XPRB_MAXIM); p.mipOptimize(); // Solution printing System.Console.WriteLine("Total return: " + p.getObjVal()); for(s=0;s<NSHARES;s++) System.Console.WriteLine(s + ": " + frac[s].getSol()*100 + "%"); return; } } } |
foliomip2.csproj |
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net5.0</TargetFramework> <IsPackable>false</IsPackable> </PropertyGroup> <ItemGroup> <PackageReference Include="FICO.Xpress.XPRBdn" Version="4.14.0" /> <!-- Version 4.14.0 or later --> </ItemGroup> </Project> |
folioqp.cs |
/******************************************************** Xpress-BCL C# Example Problems ============================== file folioqp.cs ``````````````` Modeling a small QP problem to perform portfolio optimization. -- 1. QP: minimize variance 2. MIQP: limited number of assets --- (c) 2008-2024 Fair Isaac Corporation authors: S.Heipcke, D.Brett. ********************************************************/ using System; using System.Text; using System.IO; using BCL; namespace Examples { public class TestUGFolioQp { //Define XPRBDATAPATH to wherever you have placed the data folder; here we expect it to be same directory as compiled example. static string XPRBDATAPATH = Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location).FullName + "/Data"; static string DATAFILE = XPRBDATAPATH + "/GS/foliocppqp.dat"; const int TARGET = 9; // Target yield const int MAXNUM = 4; // Max. number of different assets const int NSHARES = 10; // Number of shares const int NNA = 4; // Number of North-American shares double[] RET = {5,17,26,12,8,9,7,6,31,21}; // Estimated return in investment int[] NA = {0,1,2,3}; // Shares issued in N.-America double[,] VAR = new double[NSHARES,NSHARES]; // Variance/covariance matrix of // estimated returns public static void Main() { XPRB.init(); int s,t; XPRBprob p = new XPRBprob("FolioQP"); // Initialize a new problem in BCL XPRBexpr Na,Return,Cap,Num; XPRBexpr Variance; XPRBvar[] frac = new XPRBvar[NSHARES]; // Fraction of capital used per share XPRBvar[] buy = new XPRBvar[NSHARES]; // 1 if asset is in portfolio, 0 otherwise FileStream file; StreamReader fileStreamIn; TestUGFolioQp TestInstance = new TestUGFolioQp(); // Read `VAR' data from file file = new FileStream(DATAFILE, FileMode.Open, FileAccess.Read); fileStreamIn = new StreamReader(file); object[] outdata = new object[NSHARES]; for (s = 0; s < NSHARES; s++) { p.XPRBreadarrline(fileStreamIn, 200, "{g} ", out outdata, NSHARES); for(t=0; t<NSHARES; t++) TestInstance.VAR[s, t] = (double)outdata[t]; } fileStreamIn.Close(); file.Close(); // **** First problem: unlimited number of assets **** // Create the decision variables for(s=0;s<NSHARES;s++) frac[s] = p.newVar("frac(" + (s+1) + ")", BCLconstant.XPRB_PL, 0, 0.3); // Objective: mean variance // A note about using operators to build expressions as in // Variance += TestInstance.VAR[s,t] * (frac[s] * frac[t]); // These operators make it very clear what the expression looks like // but they also incur some overhead: each operator has to create // a temporary object that holds the operator's result. // While the overhead for binary operators is usually negligible, // operator+= must be used with care. By the C# language // specification, an expression like // a += b // will always be evaluated as // a = a + b // The right side of this statement usually involves creating a // *deep* copy of `a`. If `a` is a very big object (for example // a large expression) then creation of this deep copy can take // significant time. // In cases like this it is better to build expressions using // the `add()` or `addTerm()` member function: // Variance.add(TestInstance.VAR[s,t] * frac[s] * frac[t]) // Variance.addTerm(TestInstance.VAR[s,t], frac[s], frac[t]) // Either of them will modify the expression object directly and // will avoid the deep copy. Variance = new XPRBexpr(); for(s=0;s<NSHARES;s++) for (t = 0; t < NSHARES; t++) Variance += TestInstance.VAR[s,t] * (frac[s] * frac[t]); p.setObj(Variance); // Set the objective function // Minimum amount of North-American values Na = new XPRBexpr(); for (s = 0; s < NNA; s++) Na += frac[TestInstance.NA[s]]; p.newCtr(Na >= 0.5); // Spend all the capital Cap = new XPRBexpr(); for(s=0;s<NSHARES;s++) Cap += frac[s]; p.newCtr(Cap == 1); // Target yield Return = new XPRBexpr(); for (s = 0; s < NSHARES; s++) Return += TestInstance.RET[s] * frac[s]; p.newCtr(Return >= TARGET); // Solve the problem p.setSense(BCLconstant.XPRB_MINIM); p.lpOptimize(); /* Solve the LP-problem */ // Solution printing System.Console.WriteLine("With a target of " + TARGET + " minimum variance is " + p.getObjVal()); for(s=0;s<NSHARES;s++) System.Console.WriteLine(s + ": " + frac[s].getSol()*100 + "%"); // **** Second problem: limit total number of assets **** // Create the decision variables for(s=0;s<NSHARES;s++) buy[s] = p.newVar("buy(" + (s+1) + ")", BCLconstant.XPRB_BV); // Limit the total number of assets Num = new XPRBexpr(); for(s=0;s<NSHARES;s++) Num += buy[s]; p.newCtr(Num <= MAXNUM); // Linking the variables for(s=0;s<NSHARES;s++) p.newCtr(frac[s] <= buy[s]); // Solve the problem p.mipOptimize(); // Solution printing System.Console.WriteLine("With a target of " + TARGET + " and at most " + MAXNUM + " assets, minimum variance is " + p.getObjVal()); for(s=0;s<NSHARES;s++) System.Console.WriteLine(s + ": " + frac[s].getSol()*100 + "% (" + buy[s].getSol() + ")"); return; } } } |
folioqp.csproj |
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net5.0</TargetFramework> <IsPackable>false</IsPackable> </PropertyGroup> <ItemGroup> <Content Include="../../../Data/GS/foliocppqp.dat"> <CopyToOutputDirectory>Always</CopyToOutputDirectory> <LinkBase>Data/GS</LinkBase> </Content> </ItemGroup> <ItemGroup> <PackageReference Include="FICO.Xpress.XPRBdn" Version="4.14.0" /> <!-- Version 4.14.0 or later --> </ItemGroup> </Project> |
folioheur.cs |
/******************************************************** Xpress-BCL C# Example Problems ============================== file folioheur.cs ````````````````` Modeling a small MIP problem to perform portfolio optimization. -- Heuristic solution -- (c) 2008-2024 Fair Isaac Corporation authors: S.Heipcke, D.Brett. ********************************************************/ using System; using System.Text; using System.IO; using Optimizer; using BCL; namespace Examples { public class TestUGFolioHeur { const int MAXNUM = 4; // Max. number of shares to be selected const int NSHARES = 10; // Number of shares const int NRISK = 5; // Number of high-risk shares const int NNA = 4; // Number of North-American shares // Estimated return in investment double[] RET = {5,17,26,12,8,9,7,6,31,21}; // High-risk values among shares int[] RISK = {1,2,3,8,9}; // Shares issued in N.-America int[] NA = {0,1,2,3}; // Initialize a new problem in BCL XPRBprob p = new XPRBprob("FolioMIPHeur"); // Fraction of capital used per share XPRBvar[] frac = new XPRBvar[NSHARES]; // 1 if asset is in portfolio, 0 otherwise XPRBvar[] buy = new XPRBvar[NSHARES]; public static void Main() { XPRB.init(); int s; XPRBexpr Risk,Na,Return,Cap,Num; TestUGFolioHeur TestInstance = new TestUGFolioHeur(); // Create decision variables (including upper bounds for `frac') for(s=0;s<NSHARES;s++) { TestInstance.frac[s] = TestInstance.p.newVar("frac", BCLconstant.XPRB_PL, 0, 0.3); TestInstance.buy[s] = TestInstance.p.newVar("buy", BCLconstant.XPRB_BV); } // Objective: total return Return = new XPRBexpr(); for (s = 0; s < NSHARES; s++) Return += TestInstance.RET[s] * TestInstance.frac[s]; // Set the objective function TestInstance.p.setObj(TestInstance.p.newCtr("Objective", Return)); // Limit the percentage of high-risk values Risk = new XPRBexpr(); for (s = 0; s < NRISK; s++) Risk += TestInstance.frac[TestInstance.RISK[s]]; TestInstance.p.newCtr(Risk <= 1.0 / 3); // Minimum amount of North-American values Na = new XPRBexpr(); for (s = 0; s < NNA; s++) Na += TestInstance.frac[TestInstance.NA[s]]; TestInstance.p.newCtr(Na >= 0.5); // Spend all the capital Cap = new XPRBexpr(); for (s = 0; s < NSHARES; s++) Cap += TestInstance.frac[s]; TestInstance.p.newCtr(Cap == 1); // Limit the total number of assets Num = new XPRBexpr(); for (s = 0; s < NSHARES; s++) Num += TestInstance.buy[s]; TestInstance.p.newCtr(Num <= MAXNUM); // Linking the variables for (s = 0; s < NSHARES; s++) TestInstance.p.newCtr(TestInstance.frac[s] <= TestInstance.buy[s]); // Solve problem heuristically TestInstance.solveHeur(); // Solve the problem TestInstance.p.setSense(BCLconstant.XPRB_MAXIM); TestInstance.p.mipOptimize(); /* Solve the LP-problem */ // Solution printing if (TestInstance.p.getMIPStat() == 4 || TestInstance.p.getMIPStat() == 6) { System.Console.WriteLine("Exact solution: Total return: " + TestInstance.p.getObjVal()); for(s=0;s<NSHARES;s++) System.Console.WriteLine(s + ": " + TestInstance.frac[s].getSol() * 100 + "%"); } else System.Console.WriteLine("Heuristic solution is optimal."); return; } void solveHeur() { XPRBbasis basis; int s, ifmipsol; double solval=0, TOL; double[] fsol = new double[NSHARES]; XPRSprob xprsp = p.getXPRSprob(); xprsp.CutStrategy = 0; // Disable automatic cuts xprsp.Presolve = 0; // Switch presolve off TOL = xprsp.FeasTol; // Get feasibility tolerance p.setSense(BCLconstant.XPRB_MAXIM); p.lpOptimize(); /* Solve the LP-problem */ basis=p.saveBasis(); // Save the current basis // Fix all variables `buy' for which `frac' is at 0 or at a // relatively large value for(s=0;s<NSHARES;s++) { // Get the solution values of `frac' fsol[s]=frac[s].getSol(); if(fsol[s] < TOL) buy[s].setUB(0); else if(fsol[s] > 0.2-TOL) buy[s].setLB(1); } p.mipOptimize(); // Solve the MIP-problem // If an integer feas. solution was found... ifmipsol=0; if(p.getMIPStat()==4 || p.getMIPStat()==6) { ifmipsol=1; // ...get the value of the best solution solval=p.getObjVal(); System.Console.WriteLine("Heuristic solution: Total return: " + p.getObjVal()); for(s=0;s<NSHARES;s++) System.Console.WriteLine(s + ": " + frac[s].getSol()*100 + "%"); } xprsp.PostSolve();// Re-initialize the MIP search // Reset variables to their original bounds for(s=0;s<NSHARES;s++) if((fsol[s] < TOL) || (fsol[s] > 0.2-TOL)) { buy[s].setLB(0); buy[s].setUB(1); } /* Load the saved basis: bound changes are immediately passed on from BCL to the Optimizer if the problem has not been modified in any other way, so that there is no need to reload the matrix */ p.loadBasis(basis); // No need to store the saved basis any longer basis.reset(); // Set the cutoff to the best known solution if (ifmipsol == 1) xprsp.MIPAbsCutoff = solval + TOL; } } } |
folioheur.csproj |
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net5.0</TargetFramework> <IsPackable>false</IsPackable> </PropertyGroup> <ItemGroup> <PackageReference Include="FICO.Xpress.XPRBdn" Version="4.14.0" /> <!-- Version 4.14.0 or later --> </ItemGroup> </Project> |
foliomip3.cs |
/******************************************************** Xpress-BCL Java Example Problems ================================ file foliomip3.java ``````````````````` Modeling a MIP problem to perform portfolio optimization. -- Extending the problem with constraints on the geographical and sectorial distributions -- -- Working with a larger data set -- (c) 2009-2024 Fair Isaac Corporation author: S.Heipcke, Y.Colombani, rev. Mar. 2011 ********************************************************/ using System; using System.Collections; using System.Text; using System.IO; using BCL; namespace Examples { public class TestUGFolioMip2 { const String DATAFILE = "folio10.cdat"; const int MAXNUM = 7; /* Max. number of different assets */ const double MAXRISK = 1.0/3; /* Max. investment into high-risk values */ const double MINREG = 0.2; /* Min. investment per geogr. region */ const double MAXREG = 0.5; /* Max. investment per geogr. region */ const double MAXSEC = 0.25; /* Max. investment per ind. sector */ const double MAXVAL = 0.2; /* Max. investment per share */ const double MINVAL = 0.1; /* Min. investment per share */ static double[] RET; /* Estimated return in investment */ static int[] RISK; /* High-risk values among shares */ static bool[][] LOC; /* Geogr. region of shares */ static bool[][] SEC; /* Industry sector of shares */ static String[] SHARES_n; static String[] REGIONS_n; static String[] TYPES_n; static readonly String[] MIPSTATUS = {"not loaded", "not optimized", "LP optimized", "unfinished (no solution)", "unfinished (solution found)", "infeasible", "optimal", "unbounded"}; public static void Main() { try { readData(); /* Read data from file */ } catch (Exception exc){ Console.Error.WriteLine(exc); Console.Error.WriteLine(Environment.StackTrace); return; } XPRB.init(); /* Initialize BCL */ XPRBprob p = new XPRBprob("FolioMIP3"); /* Create a new problem in BCL */ /* Create the decision variables */ XPRBvar[] frac = new XPRBvar[SHARES_n.Length]; /* Fraction of capital used per share */ XPRBvar[] buy = new XPRBvar[SHARES_n.Length]; /* 1 if asset is in portfolio, 0 otherwise */ for(int s=0; s<SHARES_n.Length; s++) { frac[s] = p.newVar("frac", BCLconstant.XPRB_PL, 0, MAXVAL); buy[s] = p.newVar("buy", BCLconstant.XPRB_BV); } /* Objective: total return */ XPRBexpr Return = new XPRBexpr(); for(int s=0;s<SHARES_n.Length;s++) Return.add(frac[s] * RET[s]); p.setObj(Return); /* Set the objective function */ /* Limit the percentage of high-risk values */ XPRBexpr Risk = new XPRBexpr(); for(int s=0;s<RISK.Length;s++) Risk.add(frac[RISK[s]]); p.newCtr(Risk <= MAXRISK); /* Limits on geographical distribution */ XPRBexpr[] MinReg = new XPRBexpr[REGIONS_n.Length]; XPRBexpr[] MaxReg = new XPRBexpr[REGIONS_n.Length]; for(int r=0;r<REGIONS_n.Length;r++) { MinReg[r] = new XPRBexpr(); MaxReg[r] = new XPRBexpr(); for(int s=0;s<SHARES_n.Length;s++) if(LOC[r][s]) { MinReg[r].add(frac[s]); MaxReg[r].add(frac[s]); } p.newCtr(MinReg[r] >= MINREG); p.newCtr(MaxReg[r] <= MAXREG); } /* Diversification across industry sectors */ XPRBexpr[] LimSec = new XPRBexpr[TYPES_n.Length]; for(int t=0;t<TYPES_n.Length;t++) { LimSec[t] = new XPRBexpr(); for(int s=0;s<SHARES_n.Length;s++) if(SEC[t][s]) LimSec[t].add(frac[s]); p.newCtr(LimSec[t] <= MAXSEC); } /* Spend all the capital */ XPRBexpr Cap = new XPRBexpr(); for(int s=0;s<SHARES_n.Length;s++) Cap.add(frac[s]); p.newCtr(Cap == 1.0); /* Limit the total number of assets */ XPRBexpr Num = new XPRBexpr(); for(int s=0;s<SHARES_n.Length;s++) Num.add(buy[s]); p.newCtr(Num <= MAXNUM); /* Linking the variables */ for(int s=0;s<SHARES_n.Length;s++) p.newCtr(frac[s] <= buy[s] * MAXVAL); for(int s=0;s<SHARES_n.Length;s++) p.newCtr(frac[s] >= buy[s] * MINVAL); p.exportProb(BCLconstant.XPRB_LP, "dnetmat.lp"); /* Solve the problem */ p.setSense(BCLconstant.XPRB_MAXIM); p.mipOptimize(); Console.WriteLine("Problem status: " + MIPSTATUS[p.getMIPStat()]); /* Solution printing */ Console.WriteLine("Total return: " + p.getObjVal()); for(int s=0;s<SHARES_n.Length;s++) if(buy[s].getSol()>0.5) Console.WriteLine(" " + s + ": " + frac[s].getSol()*100 + "% (" + buy[s].getSol() + ")"); } /***********************Data input routines***************************/ /***************************/ /* Input a list of strings */ /***************************/ private static String[] read_str_list(String data) { return data.Split(); } private static Array read_list(String data, Type ty) { ArrayList li = new ArrayList(); foreach(String s in data.Split()) { if (s == null || s == "") { continue; } Object value = Convert.ChangeType(s, ty); li.Add(value); } return li.ToArray(ty); } /************************/ /* Input a list of ints */ /************************/ private static int[] read_int_list(String data) { return (int[])read_list(data, typeof(int)); } /****************************/ /* Input a table of doubles */ /****************************/ private static double[] read_dbl_list(String data) { return (double[])read_list(data, typeof(double)); } private static bool[] read_bool_list(String data, int len) { bool[] bools = new bool[len]; int[] trues = read_int_list(data); foreach(int t in trues) { bools[t] = true; } return bools; } /************************************/ /* Input a sparse table of bools */ /************************************/ private static bool[][] read_bool_table(StreamReader r, int nrows, int ncols) { bool[][] lists = new bool[nrows][]; for (int i = 0; i < nrows; i++) { lists[i] = new bool[ncols]; } for (int i = 0; i < nrows; i++) { String line = r.ReadLine(); if (line == null) { break; } LineData ld = new LineData(line); if (ld.data == "") { break; } bool[] row = read_bool_list(ld.data, ncols); lists[i] = row; } return lists; } private class LineData { internal String name; internal String data; internal LineData(String line) { name = ""; data = ""; line = line.Trim(); String[] split = line.Split(new char[] {'!'}, 2); // the comment char if (split.Length == 0) { return; } line = split[0].Trim(); // chop into name:data pair split = line.Split(new char[]{':'}, 2); if (split.Length == 0) { return; } if (split.Length > 1) { name = split[0].Trim(); } // lose trailing ';' data = split[split.Length - 1].Trim().TrimEnd(';').Trim(); } } private static void readData() { using (StreamReader r = new StreamReader(DATAFILE)) { for(;;) { String line = r.ReadLine(); if (line == null) { break; } LineData ld = new LineData(line); if (ld.name == "SHARES" && SHARES_n == null) { SHARES_n = read_str_list(ld.data); } else if (ld.name == "REGIONS" && REGIONS_n == null) { REGIONS_n = read_str_list(ld.data); } else if (ld.name == "TYPES" && TYPES_n == null) { TYPES_n = read_str_list(ld.data); } else if (ld.name == "RISK" && RISK == null) { RISK = read_int_list(ld.data); } else if (ld.name == "RET" && RET == null) { RET = read_dbl_list(ld.data); } else if (ld.name == "LOC" && SHARES_n != null && REGIONS_n != null) { LOC = read_bool_table(r, REGIONS_n.Length, SHARES_n.Length); } else if (ld.name == "SEC" && SHARES_n != null && REGIONS_n != null) { SEC = read_bool_table(r, TYPES_n.Length, SHARES_n.Length); } } } } } } |
foliomip3.csproj |
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net5.0</TargetFramework> <IsPackable>false</IsPackable> </PropertyGroup> <ItemGroup> <Content Include="folio10.cdat"> <CopyToOutputDirectory>Always</CopyToOutputDirectory> </Content> </ItemGroup> <ItemGroup> <PackageReference Include="FICO.Xpress.XPRBdn" Version="4.14.0" /> <!-- Version 4.14.0 or later --> </ItemGroup> </Project> |
folioiis.cs |
/******************************************************** Xpress-BCL Java Example Problems ================================ file folioiis.cs ``````````````````` Modeling a MIP problem to perform portfolio optimization. Same model as in foliomip3.cs. -- Infeasible model parameter values -- -- Retrieving IIS -- (c) 2014-2024 Fair Isaac Corporation author: L.Bertacco, September 2014 ********************************************************/ using System; using System.Collections; using System.Text; using System.IO; using BCL; namespace Examples { public class TestUGFolioIIS { const String DATAFILE = "folio10.cdat"; const int MAXNUM = 5; /* Max. number of different assets */ const double MAXRISK = 1.0/3; /* Max. investment into high-risk values */ const double MINREG = 0.1; /* Min. investment per geogr. region */ const double MAXREG = 0.2; /* Max. investment per geogr. region */ const double MAXSEC = 0.1; /* Max. investment per ind. sector */ const double MAXVAL = 0.2; /* Max. investment per share */ const double MINVAL = 0.1; /* Min. investment per share */ static double[] RET; /* Estimated return in investment */ static int[] RISK; /* High-risk values among shares */ static bool[][] LOC; /* Geogr. region of shares */ static bool[][] SEC; /* Industry sector of shares */ static String[] SHARES_n; static String[] REGIONS_n; static String[] TYPES_n; static readonly String[] MIPSTATUS = {"not loaded", "not optimized", "LP optimized", "unfinished (no solution)", "unfinished (solution found)", "infeasible", "optimal", "unbounded"}; public static void Main() { try { readData(); /* Read data from file */ } catch (Exception exc) { Console.Error.WriteLine(exc); Console.Error.WriteLine(Environment.StackTrace); return; } XPRB.init(); /* Initialize BCL */ using (XPRBprob p = new XPRBprob("FolioMIP3inf")) { /* Create a new problem in BCL */ using XPRBexprContext context = new XPRBexprContext(); /* Create the decision variables */ XPRBvar[] frac = new XPRBvar[SHARES_n.Length]; /* Fraction of capital used per share */ XPRBvar[] buy = new XPRBvar[SHARES_n.Length]; /* 1 if asset is in portfolio, 0 otherwise */ for (int s = 0; s < SHARES_n.Length; s++) { frac[s] = p.newVar("frac", BCLconstant.XPRB_PL, 0, MAXVAL); buy[s] = p.newVar("buy", BCLconstant.XPRB_BV); } /* Objective: total return */ XPRBexpr Return = new XPRBexpr(); for (int s = 0; s < SHARES_n.Length; s++) Return.add(frac[s] * RET[s]); p.setObj(Return); /* Set the objective function */ /* Limit the percentage of high-risk values */ XPRBexpr Risk = new XPRBexpr(); for (int s = 0; s < RISK.Length; s++) Risk.add(frac[RISK[s]]); p.newCtr(Risk <= MAXRISK); /* Limits on geographical distribution */ XPRBexpr[] MinReg = new XPRBexpr[REGIONS_n.Length]; XPRBexpr[] MaxReg = new XPRBexpr[REGIONS_n.Length]; for (int r = 0; r < REGIONS_n.Length; r++) { MinReg[r] = new XPRBexpr(); MaxReg[r] = new XPRBexpr(); for (int s = 0; s < SHARES_n.Length; s++) if (LOC[r][s]) { MinReg[r].add(frac[s]); MaxReg[r].add(frac[s]); } p.newCtr(MinReg[r] >= MINREG); p.newCtr(MaxReg[r] <= MAXREG); } /* Diversification across industry sectors */ XPRBexpr[] LimSec = new XPRBexpr[TYPES_n.Length]; for (int t = 0; t < TYPES_n.Length; t++) { LimSec[t] = new XPRBexpr(); for (int s = 0; s < SHARES_n.Length; s++) if (SEC[t][s]) LimSec[t].add(frac[s]); p.newCtr(LimSec[t] <= MAXSEC); } /* Spend all the capital */ XPRBexpr Cap = new XPRBexpr(); for (int s = 0; s < SHARES_n.Length; s++) Cap.add(frac[s]); p.newCtr(Cap == 1.0); /* Limit the total number of assets */ XPRBexpr Num = new XPRBexpr(); for (int s = 0; s < SHARES_n.Length; s++) Num.add(buy[s]); p.newCtr(Num <= MAXNUM); /* Linking the variables */ for (int s = 0; s < SHARES_n.Length; s++) p.newCtr(frac[s] <= buy[s] * MAXVAL); for (int s = 0; s < SHARES_n.Length; s++) p.newCtr(frac[s] >= buy[s] * MINVAL); p.exportProb(BCLconstant.XPRB_LP, "dnetmat.lp"); /* Solve the problem */ p.setSense(BCLconstant.XPRB_MAXIM); p.lpOptimize(); Console.WriteLine("Problem status: " + p.getLPStat()); if (p.getLPStat() == BCLconstant.XPRB_LP_INFEAS) { Console.WriteLine("LP infeasible. Retrieving IIS."); int numiis = p.getNumIIS(); /* Get the number of independent IIS */ Console.WriteLine("Number of IIS: " + numiis); for(int s=1; s<=numiis; s++) { ArrayList iisctr = new ArrayList(); ArrayList iisvar = new ArrayList(); p.getIIS(iisvar, iisctr, s); Console.WriteLine("IIS {0}: {1} variables, {2} constraints", s, iisvar.Count, iisctr.Count); if (iisvar.Count > 0) { /* Print all variables in the IIS */ Console.Write(" Variables: "); foreach(XPRBvar v in iisvar) Console.Write("{0} ", v.getName()); Console.WriteLine(); } if (iisctr.Count>0) { /* Print all constraints in the IIS */ Console.Write(" Constraints: "); foreach (XPRBctr c in iisctr) Console.Write("{0} ", c.getName()); Console.WriteLine(); } } } else { /* Solution printing */ Console.WriteLine("Total return: " + p.getObjVal()); for (int s = 0; s < SHARES_n.Length; s++) if (buy[s].getSol() > 0.5) Console.WriteLine(" " + s + ": " + frac[s].getSol() * 100 + "% (" + buy[s].getSol() + ")"); } } } /***********************Data input routines***************************/ /***************************/ /* Input a list of strings */ /***************************/ private static String[] read_str_list(String data) { return data.Split(); } private static Array read_list(String data, Type ty) { ArrayList li = new ArrayList(); foreach (String s in data.Split()) { if (s == null || s == "") { continue; } Object value = Convert.ChangeType(s, ty); li.Add(value); } return li.ToArray(ty); } /************************/ /* Input a list of ints */ /************************/ private static int[] read_int_list(String data) { return (int[])read_list(data, typeof(int)); } /****************************/ /* Input a table of doubles */ /****************************/ private static double[] read_dbl_list(String data) { return (double[])read_list(data, typeof(double)); } private static bool[] read_bool_list(String data, int len) { bool[] bools = new bool[len]; int[] trues = read_int_list(data); foreach (int t in trues) bools[t] = true; return bools; } /************************************/ /* Input a sparse table of bools */ /************************************/ private static bool[][] read_bool_table(StreamReader r, int nrows, int ncols) { bool[][] lists = new bool[nrows][]; for (int i = 0; i < nrows; i++) { lists[i] = new bool[ncols]; } for (int i = 0; i < nrows; i++) { String line = r.ReadLine(); if (line == null) { break; } LineData ld = new LineData(line); if (ld.data == "") { break; } bool[] row = read_bool_list(ld.data, ncols); lists[i] = row; } return lists; } private class LineData { internal String name; internal String data; internal LineData(String line) { name = ""; data = ""; line = line.Trim(); String[] split = line.Split(new char[] { '!' }, 2); // the comment char if (split.Length == 0) { return; } line = split[0].Trim(); // chop into name:data pair split = line.Split(new char[] { ':' }, 2); if (split.Length == 0) { return; } if (split.Length > 1) name = split[0].Trim(); // lose trailing ';' data = split[split.Length - 1].Trim().TrimEnd(';').Trim(); } } private static void readData() { using (StreamReader r = new StreamReader(DATAFILE)) { for (; ; ) { String line = r.ReadLine(); if (line == null) { break; } LineData ld = new LineData(line); if (ld.name == "SHARES" && SHARES_n == null) SHARES_n = read_str_list(ld.data); else if (ld.name == "REGIONS" && REGIONS_n == null) REGIONS_n = read_str_list(ld.data); else if (ld.name == "TYPES" && TYPES_n == null) TYPES_n = read_str_list(ld.data); else if (ld.name == "RISK" && RISK == null) RISK = read_int_list(ld.data); else if (ld.name == "RET" && RET == null) RET = read_dbl_list(ld.data); else if (ld.name == "LOC" && SHARES_n != null && REGIONS_n != null) LOC = read_bool_table(r, REGIONS_n.Length, SHARES_n.Length); else if (ld.name == "SEC" && SHARES_n != null && REGIONS_n != null) SEC = read_bool_table(r, TYPES_n.Length, SHARES_n.Length); } } } } } |
folioiis.csproj |
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net5.0</TargetFramework> <IsPackable>false</IsPackable> </PropertyGroup> <ItemGroup> <Content Include="folio10.cdat"> <CopyToOutputDirectory>Always</CopyToOutputDirectory> </Content> </ItemGroup> <ItemGroup> <PackageReference Include="FICO.Xpress.XPRBdn" Version="4.14.0" /> <!-- Version 4.14.0 or later --> </ItemGroup> </Project> |
© 2001-2024 Fair Isaac Corporation. All rights reserved. This documentation is the property of Fair Isaac Corporation (“FICO”). Receipt or possession of this documentation does not convey rights to disclose, reproduce, make derivative works, use, or allow others to use it except solely for internal evaluation purposes to determine whether to purchase a license to the software described in this documentation, or as otherwise set forth in a written software license agreement between you and FICO (or a FICO affiliate). Use of this documentation and the software described in it must conform strictly to the foregoing permitted uses, and no other use is permitted.