Skip to content

Instantly share code, notes, and snippets.

@jonforums
Created November 22, 2012 05:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonforums/4129589 to your computer and use it in GitHub Desktop.
Save jonforums/4129589 to your computer and use it in GitHub Desktop.
basic cvxopt linear programming
import numpy as np
from cvxopt import matrix, printing, solvers
# configuration - turn down the volume and set output formatting
solvers.options['show_progress'] = False
solvers.options['LPX_K_MSGLEV'] = 0
printing.options['dformat'] = '% .3f'
# MINIMIZE - portfolio of current bond prices
p = matrix([109,94.8,99.5,93.1,97.2,92.9,110,104,102,95.2], tc='d')
# CONSTRAINT - bond cash flows
c = np.array([[ 10, 7, 8, 6, 7, 5, 10, 8, 7,100],
[ 10, 7, 8, 6, 7, 5, 10, 8,107, 0],
[ 10, 7, 8, 6, 7, 5,110,108, 0, 0],
[ 10, 7, 8, 6, 7,105, 0, 0, 0, 0],
[ 10, 7, 8,106,107, 0, 0, 0, 0, 0],
[110,107,108, 0, 0, 0, 0, 0, 0, 0]])
I = np.eye(10) # non-negative portfolio weights
c = matrix(np.vstack([c, I]), tc='d')
# CONSTRAINT - obligations
o = np.array([100,200,800,100,800,1200])
o = matrix(np.hstack([o, np.zeros(10)]), tc='d')
# cvxopt solution
#soln = solvers.lp(p, -c, -o)
soln = solvers.lp(p, -c, -o, solver='glpk')
c = 0
for i in soln['x']:
print 'x{0:d} = {1:6.3f}'.format(c,i)
c += 1
print '\nminimum portfolio cost: ${0:,.2f}'.format((p.T*soln['x'])[0])
x0 = 0.000
x1 = 11.215
x2 = 0.000
x3 = 6.807
x4 = 0.000
x5 = 0.000
x6 = 0.000
x7 = 6.302
x8 = 0.283
x9 = 0.000
minimum portfolio cost: $2,381.14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment