\[
\begin{align}
& \Gamma = 5 &\\
& p_i = 1.15 + i\frac{0.05}{150}, &\forall i = 1, 2, ..., n \\
& \delta_i = \frac{0.05}{450}\sqrt{2 \cdot i \cdot n \cdot (n+1)}, &\forall i = 1, 2, ..., n.
\end{align}
\]
from rsome import rofrom rsome import grb_solver as grbimport rsome as rsoimport numpy as npn =150# number of stocksi = np.arange(1, n+1) # indices of stocksp =1.15+ i*0.05/150# mean returnsdelta =0.05/450* (2*i*n*(n+1))**0.5# deviations of returnsGamma =5# budget of uncertaintymodel = ro.Model() x = model.dvar(n) # fractions of investmentz = model.rvar(n) # random variablesmodel.maxmin((p + delta*z) @ x, # the max-min objective rso.norm(z, np.infty) <=1, # uncertainty set constraints rso.norm(z, 1) <= Gamma) # uncertainty set constraintsmodel.st(sum(x) ==1) # summation of x is onemodel.st(x >=0) # x is non-negativemodel.solve(grb) # solve the model by Gurobi
Restricted license - for non-production use only - expires 2025-11-24
Being solved by Gurobi...
Solution status: 2
Running time: 0.0032s
import matplotlib.pyplot as pltobj_val = model.get() # the optimal objective valuex_sol = x.get() # the optimal investment decisionplt.plot(range(1, n+1), x_sol, linewidth=2, color='b')plt.xlabel('Stocks')plt.ylabel('Fraction of investment')plt.show()print('Objective value: {0:0.4f}'.format(obj_val))
import pandas as pdimport yfinance as yfstocks = ['JPM', 'AMZN', 'TSLA']start ='2021-1-2'# starting date of historical dataend='2021-1-31'# end date of historical datadata = pd.DataFrame([])for stock in stocks: each = yf.Ticker(stock).history(start=start, end=end) close = each['Close'].values returns = (close[1:] - close[:-1]) / close[:-1] data[stock] = returnsdata.head()
JPM
AMZN
TSLA
0
0.005441
0.010004
0.007317
1
0.046956
-0.024897
0.028390
2
0.032839
0.007577
0.079447
3
0.001104
0.006496
0.078403
4
0.014924
-0.021519
-0.078214
import numpy as npy = data.values # stock data as an arrays, n = y.shape # s: sample size; n: number of stocksx_lb = np.zeros(n) # lower bounds of investment decisionsx_ub = np.ones(n) # upper bounds of investment decisionsbeta =0.95# confidence intervalw0 =1# investment budgetmu =0.001# target minimum expected return rate
from rsome import drofrom rsome import normfrom rsome import Efrom rsome import grb_solver as grbimport numpy as npimport numpy.random as rd# model and ambiguity set parametersI =1S =10c = np.ones(I)d =50* Ip =1+4*rd.rand(I)zbar =100* rd.rand(I)zhat = zbar * rd.rand(S, I)theta =0.01* zbar.min()# modeling with RSOMEmodel = dro.Model(S) # create a DRO model with S scenariosz = model.rvar(I) # random demand zu = model.rvar() # auxiliary random variablefset = model.ambiguity() # create an ambiguity setfor s inrange(S): fset[s].suppset(0<= z, z <= zbar, norm(z - zhat[s]) <= u) # define the support for each scenariofset.exptset(E(u) <= theta) # the Wasserstein metric constraintpr = model.p # an array of scenario probabilitiesfset.probset(pr ==1/S) # support of scenario probabilitiesx = model.dvar(I) # define first-stage decisionsy = model.dvar(I) # define decision rule variablesy.adapt(z) # y affinely adapts to zy.adapt(u) # y affinely adapts to ufor s inrange(S): y.adapt(s) # y adapts to each scenario smodel.minsup(-p@x + E(p@y), fset) # worst-case expectation over fsetmodel.st(y >=0) # constraintsmodel.st(y >= x - z) # constraintsmodel.st(x >=0) # constraintsmodel.st(c@x == d) # constraintsmodel.solve(grb) # solve the model by Gurobi
Being solved by Gurobi...
Solution status: 2
Running time: 0.0029s
from rsome import dro from rsome import Efrom rsome import squarefrom rsome import grb_solver as grbimport numpy as npphi = np.array([vbar*((t-r+1)/3)for t inrange(T)for r inrange(t+1)]) # ambiguity set parameter phimodel = dro.Model()v = model.rvar(T) # random variable vu = model.rvar(T*(T+1)//2) # auxiliary random variable ufset = model.ambiguity() # create an ambiguity setfset.exptset(E(v) ==0, E(u) <= phi) # define the uncertainty set of expectationsfset.suppset(v >=-vbar, v <= vbar, [square(v[r:t].sum()) <= u[t*(t-1)//2+ r]for t inrange(T+1)for r inrange(t)]) # define the support of random variablestemp = alpha*np.triu(np.ones(T), 0) + (1-alpha)*np.eye(T)d = v@temp + mu # random demandx1 = model.dvar() # variable x1x = model.dvar(T-1) # an array of variables x2, x3, ..., xTI = model.dvar(T) # an array of variables I1, I2, ..., ITy = model.dvar(T) # an array of variables y1, y2, ..., yTfor t inrange(T-1): x[t].adapt(v[:t+1]) # x[t] adapts to v[0], ..., v[t] x[t].adapt(u[:(t+1)*(t+2)//2]) # x[t] adapts to u[0], ..., u[t*(t+3)//2]for t inrange(T): I[t].adapt(v[:t+1]) # I[t] adapts to v[0], ..., v[t] I[t].adapt(u[:(t+1)*(t+2)//2]) # I[t] adapts to u[0], ..., u[t*(t+3)//2] y[t].adapt(v[:t+1]) # y[t] adapts to v[0], ..., v[t] y[t].adapt(u[:(t+1)*(t+2)//2]) # y[t] adapts to u[0], ..., u[t*(t+3)//2]model.minsup(E(c[0]*x1 + c[1:]@x + y.sum()), fset)model.st(I[0] == I0 + x1 - d[0])for t inrange(1, T): model.st(I[t] == I[t-1] + x[t-1] - d[t])model.st(y >= h*I, y >=-b*I) model.st(x1 >=0, x1 <= xbar[0]) model.st(x >=0, x <= xbar[1:])model.solve(grb) # solve the model by Gurobi
Being solved by Gurobi...
---------------------------------------------------------------------------GurobiError Traceback (most recent call last)
Cell In[101], line 45 42 model.st(x1 >=0, x1 <= xbar[0])
43 model.st(x >=0, x <= xbar[1:])
---> 45model.solve(grb)# solve the model by Gurobi
File ~/miniconda3/envs/jupyterlab/lib/python3.10/site-packages/rsome/dro.py:798, in Model.solve(self, solver, display, log, params) 796 solution = def_sol(self.do_math(), display, log, params)
797else:
--> 798 solution =solver.solve(self.do_math(),display,log,params) 800ifisinstance(solution, Solution):
801self.ro_model.solution = solution
File ~/miniconda3/envs/jupyterlab/lib/python3.10/site-packages/rsome/grb_solver.py:72, in solve(formula, display, log, params) 70print('Being solved by Gurobi...', flush=True)
71 time.sleep(0.2)
---> 72grb.optimize() 73if display:
74print('Solution status: {0}'.format(grb.Status))
File src/gurobipy/model.pxi:893, in gurobipy.Model.optimize()GurobiError: Model too large for size-limited license; visit https://gurobi.com/unrestricted for more information
model.do_math()
Conic program object:
=============================================
Number of variables: 1785
Continuous/binaries/integers: 1785/0/0
---------------------------------------------
Number of linear constraints: 634
Inequalities/equalities: 33/601
Number of coefficients: 4046
---------------------------------------------
Number of SOC constraints: 435
---------------------------------------------
Number of ExpCone constraints: 0
---------------------------------------------
Number of PSCone constraints: 0