/******************************************************** Xpress-BCL C# Example Problems ============================== file foliodata.cs ````````````````` Modeling a small LP problem to perform portfolio optimization. -- Data input from file -- (c) 2008 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 / 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