<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	
	xmlns:georss="http://www.georss.org/georss"
	xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"
	>

<channel>
	<title>vb quadratic programming Archives - CenterSpace</title>
	<atom:link href="https://www.centerspace.net/tag/vb-quadratic-programming/feed" rel="self" type="application/rss+xml" />
	<link>https://www.centerspace.net/tag/vb-quadratic-programming</link>
	<description>.NET numerical class libraries</description>
	<lastBuildDate>Tue, 07 Feb 2023 21:49:21 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.1.1</generator>
<site xmlns="com-wordpress:feed-additions:1">104092929</site>	<item>
		<title>Optimal Portfolio Allocation</title>
		<link>https://www.centerspace.net/optimal-portfolio-allocation</link>
					<comments>https://www.centerspace.net/optimal-portfolio-allocation#respond</comments>
		
		<dc:creator><![CDATA[Paul Shirkey]]></dc:creator>
		<pubDate>Wed, 22 Jan 2014 20:12:49 +0000</pubDate>
				<category><![CDATA[NMath]]></category>
		<category><![CDATA[c# finance]]></category>
		<category><![CDATA[c# optimal portfolio allocation]]></category>
		<category><![CDATA[c# optimal profolio]]></category>
		<category><![CDATA[c# optimzation]]></category>
		<category><![CDATA[c# QP]]></category>
		<category><![CDATA[c# quadratic programming]]></category>
		<category><![CDATA[portfolio optimzation]]></category>
		<category><![CDATA[vb portfolio allocation]]></category>
		<category><![CDATA[vb portfolio optimzation]]></category>
		<category><![CDATA[vb QP]]></category>
		<category><![CDATA[vb quadratic programming]]></category>
		<guid isPermaLink="false">http://www.centerspace.net/blog/?p=4917</guid>

					<description><![CDATA[<p>The problem of optimal portfolio allocation, in its simplest form, asks the question of how to fully allocate a given amount of wealth across a fixed universe of investments to achieve a minimum-risk goal-expected return. The known quantities are the potential field of investments, their performance history, and the goal rate of return; The unknown [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://www.centerspace.net/optimal-portfolio-allocation">Optimal Portfolio Allocation</a> appeared first on <a rel="nofollow" href="https://www.centerspace.net">CenterSpace</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>The problem of optimal portfolio allocation, in its simplest form, asks the question of how to <em>fully</em> allocate a given amount of wealth across a fixed universe of investments to achieve a minimum-risk goal-expected return.  The known quantities are the potential field of investments, their performance history, and the goal rate of return; The unknown is the wealth allocation across the investments.  In this standard formulation, the phrase &#8216;minimum-risk&#8217; is understood to be equivalent to &#8216;minimum-variance&#8217; of the portfolio return.  Said another way, in this model the investor will expect to get a &#8216;risk-premium&#8217; (higher return) for investing in assets which have a higher historic return variance.  This understanding of risk is at the heart of Harry Markowitz&#8217;s portfolio theory <a href="#ref5">[5]</a>.</p>
<p>In the following brief development of optimal portfolio allocation theory we follow the paper by P. J. Atzberger <a href="#ref2">[2]</a>. If we have <code>n</code> investments we represent a fully invested portfolio as,<br />
<center><br />
<img decoding="async" loading="lazy" src="https://www.centerspace.net/blog/wp-content/uploads/2014/01/eq1.gif" alt="\sum^{n}_{i=1}w_i = 1" width="79" height="51" class="alignnone size-full wp-image-5279" /><br />
</center></p>
<p>where the fraction of wealth invested in the <code>i<sup>th</sup></code> asset is <code>w<sub>i</sub></code>.  We use this normalization to avoid working with the absolute magnitudes of the assets and resultant portfolios.</p>
<p>The rate of return of the entire portfolio, <code>&rho;<sub>p</sub></code> at a given time <code>t</code> is,<br />
<center><br />
<img decoding="async" loading="lazy" src="https://www.centerspace.net/blog/wp-content/uploads/2014/01/eq2.gif" alt="\rho_p(t) = \sum^{n}_{i=1}w_i*\rho_i" width="139" height="51" class="alignnone size-full wp-image-5280" /><br />
</center></p>
<p>or simply the weighted sum of investment returns.</p>
<p>And because expectation is a linear operator, the expected rate of return of a given portfolio is,<br />
<center><br />
<img decoding="async" loading="lazy" src="https://www.centerspace.net/blog/wp-content/uploads/2014/01/eq3.gif" alt="\mu_p = E \left( \sum^{n}_{i=1}w_i*\rho_i \right ) = \sum^{n}_{i=1}w_i*\mu_i" width="271" height="55" class="alignnone size-full wp-image-5282" /><br />
</center></p>
<p>Where <code>&mu;<sub>i</sub></code> is expected rate of return of the <code>i<sup>th</sup></code> investment option.</p>
<p>And finally from the expected return of return, the portfolio variance will be given by,<br />
<center><br />
<img decoding="async" loading="lazy" src="https://www.centerspace.net/blog/wp-content/uploads/2014/01/eq4.gif" alt="\sigma_p^2 = E \left( |\rho_p - \mu_p|^2 \right ) = \textbf{w}^T V \textbf{w}" width="229" height="24" class="alignnone size-full wp-image-5283" /><br />
</center></p>
<p>where <code><bold>w</bold></code> is the vector of normalized fractional investments defined above.  (See eq. (13) in <a href="#ref2">[2]</a> for the full derivation).  This is the minimum theoretical framework needed to setup the optimization problem.</p>
<h3> Optimization with Markowitz Theory </h3>
<p>Using our established problem framework we can cast the optimal portfolio allocation problem as a constrained quadratic optimization problem by minimizing the portfoilo&#8217;s variance (risk) subject to two linear constraints.<br />
<center><br />
<img decoding="async" loading="lazy" src="https://www.centerspace.net/blog/wp-content/uploads/2014/01/eq51.gif" alt="min {\,\,\,} {1\over{2}} \sum^{n}_{i,j=1} \omega_i \omega_j \sigma_{i,j}" width="149" height="53" class="alignnone size-full wp-image-5287" /><br />
</center></p>
<p>subject to,<br />
<center><br />
<img decoding="async" loading="lazy" src="https://www.centerspace.net/blog/wp-content/uploads/2014/01/eq61.gif" alt="\sum^{n}_{i=1} \omega_i \mu_j - \mu_p = 0" width="136" height="51" class="alignnone size-full wp-image-5288" /><br />
</center></p>
<p>and,<br />
<center><br />
<img decoding="async" loading="lazy" src="https://www.centerspace.net/blog/wp-content/uploads/2014/01/eq7.gif" alt="\sum^{n}_{i=1} \omega_i - 1 = 0" width="109" height="51" class="alignnone size-full wp-image-5289" /><br />
</center></p>
<p>The minimized objective function is the variance of the portfolio &#8211; which is thought of as risk equivalent in this model.  The first constraint insures that the built portfolio achieves a goal return of <code>&mu;<sub>p</sum></code> and the second constraint enforces the full allocation of wealth.  There are many variants of this basic setup such as including a zero-risk investment (cash) to the pool of possible investments or adding constraints to allocate various percentages of wealth into different risk-classified investments [2][4].</p>
<h3> Solving the Quadratic Programming Problem </h3>
<p>This constrained optimization problem can be solved using <strong>NMath</strong>&#8216;s quadratic programming class, <code>ActiveSetQPSolver()</code>.  The basic steps of setting up the QP solver involve (1) Reading and parsing the investment data, (2) Setting up the problem constraints, (3) Executing the solve.  The data for this example come from a <a href="http://people.brunel.ac.uk/~mastjjb/jeb/info.html">data repository</a> for exploring various Operations Research (OR) problems, run by J.E. Beasley.  The specific data we study here has a universe of 225 potential assets, is found <a href="http://people.brunel.ac.uk/~mastjjb/jeb/orlib/files/port5.txt">here,</a> and is the largest test data set used in the paper &#8220;Heuristics for cardinality constrained portfolio optimisation&#8221; [3] (A brief description of the data set can be found on the same server <a href="http://people.brunel.ac.uk/~mastjjb/jeb/orlib/portinfo.html">here</a>).  The data set provides the basic information we need for optimizing the portfolio &#8211; the mean return and standard deviation of return of each investment and the correlation between all possible pairs of assets.  The code to parse this file is appended to the end of this article.</p>
<p>Before generating the QP&#8217;s constraints we need to set up a <code>QuadraticProgrammingProblem</code> instance.</p>
<pre lang="csharp">
  // Set up QR problem using port5.txt data
  FloatMatrix covariance = correlation * 
                           ( NMathFunctions.Product( new FloatMatrix( stdDevReturn ), 
                           ( new FloatMatrix( stdDevReturn ).Transpose() ) ) );
  QuadraticProgrammingProblem problem = new QuadraticProgrammingProblem();
  problem.H = covariance;
  problem.c = new DoubleVector(n, 0);
</pre>
<p>First, the covariance matrix is computed from the investment standard deviations and correlations.  Next we create and initialize a <code>QuadraticProgrammingProblem</code> instance.  Since this QP solver class solves programs of the form: <code>Minimize x'Hx + x'c</code>, the <code>c</code> variable is set to zero.</p>
<p>The following code snippet sets up the QP constraints.</p>
<pre lang="csharp">
  ...
  QuadraticProgrammingProblem problem = new QuadraticProgrammingProblem();
  ...
  // Set up constraints
  LinearConstraint sumToOne = new LinearConstraint( 
                   new DoubleVector( n, 1 ), 1, ConstraintType.EqualTo );
  LinearConstraint returnRate = new LinearConstraint( 
                   meanReturn, targetReturn, ConstraintType.GreaterThanOrEqualTo );
  problem.AddConstraint( returnRate );
  problem.AddConstraint( sumToOne );

  // Add the bound on each var, w: w > 0
  for ( int i = 0; i < n; i++ )
    problem.AddLowerBound( i, 0.0 );
</pre>
<p>The first two constraints, <code>sumToOne</code> and <code>returnRate</code> were outlined above in the brief Markowitz theory section.  The third constraint has been added to insure that we have a positive ownership in all assets; in this way we have disallowed shorting assets.  This constraint can be deleted to include shorted asset in the optimized portfolio, if desired.  All of these constraints are added to the <code>QuadraticProgrammingProblem</code> instance.  </p>
<p>We can now put all of this together and solve the constrained 225 variable QP using the <code>ActiveSetQPSolver</code> class <a href="#ref0">[0]</a>. </p>
<pre lang="c">
Asset   Allocation
   8,   0.0795
  39,   0.0866
  42,   0.0812
  59,   0.1201
  61,   0.2567
  96,   0.0593
 128,   0.0741
 170,   0.0573
 195,   0.0980
 214,   0.0688
 224,   0.0183
(All other assets have an allocation of zero.)

Total allocation:  1.0000
Total return-rate:  0.2000%, Target return-rate  0.2000%
Total solver time required:  0.1830 seconds
</pre>
<p>The optimal allocation includes 11 of our 225 investments and closely adheres to all constraints.  The complete code listing is provided at the end of this article.</p>
<p>Happy Computing,</p>
<p>Paul Shirkey</p>
<h4> References, Resources, Notes </h4>
<p><a name="ref0">[0]</a> Due to the size of this QP problem and the number of constraints (227) the current release of <strong>NMath</strong>'s <code>ActiveSetQPSolver()</code> fails to correctly find the optimal portfolio.  However, the next release of <strong>NMath</strong> due in May (<strong>NMath</strong> 6.0) includes a major upgrade to many of our LP, QP, and NLP classes.  Many of these classes in <strong>NMath</strong> 6.0 are backed by the Microsoft Solver Foundation, providing the ability to solve much larger problems correctly and efficiently.</p>
<p>[1] The <strong>port5 </strong>data set can be found at <a href="http://people.brunel.ac.uk/~mastjjb/jeb/orlib/files/port5.txt">http://people.brunel.ac.uk/~mastjjb/jeb/orlib/files/port5.txt</a> .  This data set is part of the <em>OR-Library</em>, a set of standard data sets maintained by J. E. Beasley at <a href="http://people.brunel.ac.uk/~mastjjb/jeb/info.html">http://people.brunel.ac.uk/~mastjjb/jeb/info.html</a>.</p>
<p><a name="ref2">[2]</a> This blog note follows the notation of this clearly written paper, by Paul J. Atzberger, on optimal portfolio allocation, variants, and the efficient frontier: http://www.math.ucsb.edu/~atzberg/finance/portfolioTheory.pdf.</p>
<p>[3] Chang, T.-J., Meade, N., Beasley, J.E. and Sharaiha, Y.M., "Heuristics for cardinality constrained portfolio optimisation" Comp. & Opns. Res. 27 (2000) 1271-1302.</p>
<p>[4] MATLAB uses this same data set in their optimization <a href="http://www.mathworks.com/products/optimization/code-examples.html">documentation</a>.</p>
<p><a name="ref5">[5]</a> Markowitz, H.M. (March 1952). "Portfolio Selection". The Journal of Finance 7 (1): 77–91.  [<a href="http://www.math.ust.hk/~maykwok/courses/ma362/07F/markowitz_JF.pdf">paper in pdf</a>]</p>
<h3> .NET Code Listings </h3>
<p>Full QP solution code.  Note that NMath 6.0 (due May 2014) is required.</p>
<pre lang="csharp">
using System;
using CenterSpace.NMath.Core;  
using CenterSpace.NMath.Analysis;
using CenterSpace.NMath.Charting.Microsoft;
using System.Windows.Forms.DataVisualization.Charting;

public void OptimalPortAllocation()
    {
      // Get port5 data set : http://people.brunel.ac.uk/~mastjjb/jeb/orlib/files/port5.txt
      // File Format of port5:
      // Line 1: Text description of data
      // Line 2: number of assets, N
      // Line 2 - 2+N : list of mean return _ standard return
      // Remaining 1/2 N*N lines: correlation matrix between asset i and j
      FloatVector meanReturn = null ;
      FloatVector stdDevReturn = null;
      FloatMatrix correlation = null;
      int n = loadData( ref meanReturn, ref stdDevReturn, ref correlation );

      double targetReturn = 0.002;

      // Set up QR problem using port5.txt data
      FloatMatrix covariance = correlation * ( NMathFunctions.Product( new FloatMatrix( stdDevReturn ), ( new FloatMatrix( stdDevReturn ).Transpose() ) ) );
      QuadraticProgrammingProblem problem = new QuadraticProgrammingProblem();
      problem.H = covariance;
      problem.c = new DoubleVector(n, 0);

      // Set up constraints
      LinearConstraint sumToOne = new LinearConstraint( new DoubleVector( n, 1 ), 1, ConstraintType.EqualTo );
      LinearConstraint returnRate = new LinearConstraint( meanReturn, targetReturn, ConstraintType.GreaterThanOrEqualTo );
      problem.AddConstraint( returnRate );
      problem.AddConstraint( sumToOne );

      // Add the bound on each var, w: w > 0
      for ( int i = 0; i < n; i++ )
        problem.AddLowerBound( i, 0.0 );
   
      // Solve constrainted QP
      var solver = new ActiveSetQPSolver();
      solver.StepSizeEpsilon = 1e-10;

      var startEqualAllocation = new DoubleVector( n, 1.0 / n );
      var optAllocation = new DoubleVector();
      
      long before = DateTime.Now.Ticks;
      if ( solver.Solve( problem, startEqualAllocation ) )
      {
        optAllocation = solver.OptimalX;
      }
      else
      {
        throw new Exception( "Solve failed to find a solution." );
      }
      long after = DateTime.Now.Ticks;
      long ticks = after - before;
      double millis = ( (double) ticks ) / 10000;

      Console.WriteLine("Asset #    Allocation");
      double wealth = 0.0;
      double measuredReturnRate = 0.0;
      for ( int i = 0; i < optAllocation.Length; i++ )
      {
        if ( optAllocation[i] > 0.0000001 )
        {
          Console.WriteLine( String.Format( "{0,4},  {1,7:0.0000}",i, optAllocation[i]));
          wealth += optAllocation[i];
          measuredReturnRate += optAllocation[i] * meanReturn[i];
        }

      }
      Console.WriteLine(String.Format("Total allocation: {0,7:0.0000}", wealth) );
      Console.WriteLine( String.Format( "Total return rate: {0,7:0.0000}%, Target return rate {1,7:0.0000}%", 100 * measuredReturnRate, 100 * targetReturn ) );
      Console.WriteLine( String.Format( "Total solver time required: {0,7:0.0000} seconds", millis/1000 ) );


      // Chart optimal portfolio allocation
      DoubleVector x = new DoubleVector(n, 0, 1);
      DoubleVector w = optAllocation;
      var chart = NMathChart.ToChart( x, w );
      chart.Series[0].MarkerStyle = MarkerStyle.Square;
      chart.Series[0].ChartType = SeriesChartType.Bar;
      NMathChart.Show( chart );

    }
</pre>
<p>Below is the full parsing code for the <code>port5.txt</code> data file.</p>
<pre lang="csharp">
    private int loadData( ref FloatVector meanReturn, ref FloatVector stdDevReturn, ref FloatMatrix correlation )
    {
      int n;

      // Fix up the path here to point to your data file copy.
      using ( StreamReader file = new StreamReader( "./data/PortfolioOptimzation_port5.data.txt" ) )
      {
        file.ReadLine(); // skip first line of explanatory text
        n = Int32.Parse( file.ReadLine() );

        // Now get the next n mean return and standard return values.
        meanReturn = new FloatVector( n );
        stdDevReturn = new FloatVector( n );
        string[] values = new string[3];
        for ( int k = 0; k < n; k++ )
        {
          values = file.ReadLine().Split( ' ' );
          meanReturn[k] = float.Parse( values[1] );
          stdDevReturn[k] = float.Parse( values[2] );
        }

        // Now get the correlation matrix.
        correlation = new FloatMatrix( n, n );
        int cnt = 0;
        for ( int i = cnt; i < n; i++ )
        {
          for ( int j = cnt; j < n; j++ )
          {
            values = file.ReadLine().Split( ' ' );
            correlation[i, j] = float.Parse( values[3] );
            correlation[j, i] = float.Parse( values[3] );
          }

          cnt++;
        }
      }
      return n;
    }
</pre>
<p>The post <a rel="nofollow" href="https://www.centerspace.net/optimal-portfolio-allocation">Optimal Portfolio Allocation</a> appeared first on <a rel="nofollow" href="https://www.centerspace.net">CenterSpace</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.centerspace.net/optimal-portfolio-allocation/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4917</post-id>	</item>
	</channel>
</rss>
