PySCIPOpt  4.3.0
Python Interface for the SCIP Optimization Suite
markowitz_soco.py
Go to the documentation of this file.
1 
3 """
4 Approach: use second-order cone optimization.
5 
6 Copyright (c) by Joao Pedro PEDROSO, Masahiro MURAMATSU and Mikio KUBO, 2012
7 """
8 from pyscipopt import Model, quicksum, multidict
9 
10 def markowitz(I,sigma,r,alpha):
11  """markowitz -- simple markowitz model for portfolio optimization.
12  Parameters:
13  - I: set of items
14  - sigma[i]: standard deviation of item i
15  - r[i]: revenue of item i
16  - alpha: acceptance threshold
17  Returns a model, ready to be solved.
18  """
19  model = Model("markowitz")
20 
21  x = {}
22  for i in I:
23  x[i] = model.addVar(vtype="C", name="x(%s)"%i) # quantity of i to buy
24 
25  model.addCons(quicksum(r[i]*x[i] for i in I) >= alpha)
26  model.addCons(quicksum(x[i] for i in I) == 1)
27 
28  # set nonlinear objective: SCIP only allow for linear objectives hence the following
29  obj = model.addVar(vtype="C", name="objective", lb = None, ub = None) # auxiliary variable to represent objective
30  model.addCons(quicksum(sigma[i]**2 * x[i] * x[i] for i in I) <= obj)
31  model.setObjective(obj, "minimize")
32 
33  model.data = x
34  return model
35 
36 
37 
38 if __name__ == "__main__":
39  # portfolio
40  import math
41  I,sigma,r = multidict(
42  {1:[0.07,1.01],
43  2:[0.09,1.05],
44  3:[0.1,1.08],
45  4:[0.2,1.10],
46  5:[0.3,1.20]}
47  )
48  alpha = 1.05
49 
50  model = markowitz(I,sigma,r,alpha)
51  model.optimize()
52 
53  x = model.data
54  EPS = 1.e-6
55  print("%5s\t%8s" % ("i","x[i]"))
56  for i in I:
57  print("%5s\t%8g" % (i,model.getVal(x[i])))
58  print("sum:",sum(model.getVal(x[i]) for i in I))
59  print
60  print("Optimal value:", model.getObjVal())
pyscipopt.expr.quicksum
def quicksum(termlist)
Definition: expr.pxi:357
pyscipopt.Multidict.multidict
def multidict(D)
Definition: Multidict.py:3
markowitz_soco.markowitz
def markowitz(I, sigma, r, alpha)
Definition: markowitz_soco.py:10