7if __name__ ==
"__main__":
10 from gams.magic
import GamsInteractive
11 gams = GamsInteractive()
21 url=
"https://github.com/daveh19/pydataberlin2017/raw/master/notebooks/dowjones2016.csv"
22 price_data=pd.read_csv(url)
25 m = gams.exchange_container
26 date = m.addSet(
'date', description=
'trading date')
27 symbol = m.addSet(
'symbol', description=
'stock symbol')
28 price = m.addParameter(
'price', [date, symbol], domain_forwarding=
True, records=price_data, description=
'price of stock on date')
29 d = m.addAlias(
'd', date)
30 s = m.addAlias(
's', symbol)
37 avgprice = m.addParameter(
'avgprice', [symbol], description=
'average price of stock')
38 gams.gams(
'avgprice(s) = sum(d, price(d,s))/card(d);')
39 print(avgprice.records.head())
46 weight = m.addParameter(
'weight', [symbol], description=
'weight of stock')
47 gams.gams(
'weight(symbol) = avgprice(symbol)/sum(s, avgprice(s));')
48 print(weight.records.head())
55 contribution = m.addParameter(
'contribution', [date,symbol])
56 gams.gams(
'contribution(d,s) = weight(s)*price(d,s);')
57 print(contribution.records.head())
64 index = m.addParameter(
'index', [date], description=
'Dow Jones index')
65 gams.gams(
'index(d) = sum(s, contribution(d,s));')
66 print(index.records.head())
79 trainingdays = m.addParameter(
'trainingdays', records = 100)
80 maxstock = m.addParameter(
'maxstock', records = 3, description=
'maximum number of stocks to select')
81 ds = m.addSet(
'ds', [date], description=
'selected dates')
82 ds.setRecords(date.records[
'uni'][:100])
89 p = m.addVariable(
'p',
'binary', [symbol], description =
'is stock included?')
90 w = m.addVariable(
'w',
'positive', [symbol], description =
'what part of the portfolio')
91 slpos = m.addVariable(
'slpos',
'positive', [date], description =
'positive slack')
92 slneg = m.addVariable(
'slneg',
'positive', [date], description =
'negative slack')
93 obj = m.addVariable(
'obj',
'free', description =
'objective')
108Equation deffit(date) 'fit to Dow Jones index';
111Equation defpick(symbol)
'can only use stock if picked';
112defpick(s)..
w(s) =l=
p(s);
114Equation defnumstock
'few stocks allowed';
115defnumstock.. sum(s,
p(s)) =l= maxstock;
117Equation defobj
'absolute violation (L1 norm) from index';
118defobj.. obj =e= sum(ds,
slpos(ds) +
slneg(ds));
120Model pickStock /all/;
''')
127 ds.setRecords(date.records[
'uni'][:100])
128 maxstock.setRecords(3)
131 gams.gams(
'option optCR=0.01, resLim=6; solve pickStock min obj using mip;')
138 fund = m.addParameter(
'fund', [date], description=
'Index fund report parameter')
139 gams.gams(
'fund(d) = sum(s, price(d, s)*w.l(s));')
140 error = m.addParameter(
'error', [date], description=
'Absolute error')
141 gams.gams(
'error(d) = abs(index(d)-fund(d));')
150 gams.gams_cleanup(closedown=
True)
GamsInteractive p
Declaration of the variables and equations used to formulate the optimization model.
GamsInteractive index
Compute index values.