7if __name__ ==
"__main__":
12 os.environ[
'SSL_CERT_FILE'] = certifi.where()
13 from gams.magic
import GamsInteractive
14 gams = GamsInteractive()
24 url=
"https://github.com/daveh19/pydataberlin2017/raw/master/notebooks/dowjones2016.csv"
25 price_data=pd.read_csv(url)
28 m = gams.exchange_container
29 date = m.addSet(
'date', description=
'trading date')
30 symbol = m.addSet(
'symbol', description=
'stock symbol')
31 price = m.addParameter(
'price', [date, symbol], domain_forwarding=
True, records=price_data, description=
'price of stock on date')
32 d = m.addAlias(
'd', date)
33 s = m.addAlias(
's', symbol)
40 avgprice = m.addParameter(
'avgprice', [symbol], description=
'average price of stock')
41 gams.gams(
'avgprice(s) = sum(d, price(d,s))/card(d);')
42 print(avgprice.records.head())
49 weight = m.addParameter(
'weight', [symbol], description=
'weight of stock')
50 gams.gams(
'weight(symbol) = avgprice(symbol)/sum(s, avgprice(s));')
51 print(weight.records.head())
58 contribution = m.addParameter(
'contribution', [date,symbol])
59 gams.gams(
'contribution(d,s) = weight(s)*price(d,s);')
60 print(contribution.records.head())
67 index = m.addParameter(
'index', [date], description=
'Dow Jones index')
68 gams.gams(
'index(d) = sum(s, contribution(d,s));')
69 print(index.records.head())
82 trainingdays = m.addParameter(
'trainingdays', records = 100)
83 maxstock = m.addParameter(
'maxstock', records = 3, description=
'maximum number of stocks to select')
84 ds = m.addSet(
'ds', [date], description=
'selected dates')
85 ds.setRecords(date.records[
'uni'][:100])
92 p = m.addVariable(
'p',
'binary', [symbol], description =
'is stock included?')
93 w = m.addVariable(
'w',
'positive', [symbol], description =
'what part of the portfolio')
94 slpos = m.addVariable(
'slpos',
'positive', [date], description =
'positive slack')
95 slneg = m.addVariable(
'slneg',
'positive', [date], description =
'negative slack')
96 obj = m.addVariable(
'obj',
'free', description =
'objective')
111Equation deffit(date) 'fit to Dow Jones index';
112deffit(ds).. sum(s, price(ds,s)*w(s)) =e= index(ds) + slpos(ds) - slneg(ds);
114Equation defpick(symbol) 'can only use stock if picked';
115defpick(s).. w(s) =l= p(s);
117Equation defnumstock 'few stocks allowed';
118defnumstock.. sum(s, p(s)) =l= maxstock;
120Equation defobj 'absolute violation (L1 norm) from index';
121defobj.. obj =e= sum(ds, slpos(ds) + slneg(ds));
123Model pickStock /all/;''')
130 ds.setRecords(date.records[
'uni'][:100])
131 maxstock.setRecords(3)
134 gams.gams(
'option optCR=0.01, resLim=6; solve pickStock min obj using mip;')
141 fund = m.addParameter(
'fund', [date], description=
'Index fund report parameter')
142 gams.gams(
'fund(d) = sum(s, price(d, s)*w.l(s));')
143 error = m.addParameter(
'error', [date], description=
'Absolute error')
144 gams.gams(
'error(d) = abs(index(d)-fund(d));')
153 gams.gams_cleanup(closedown=
True)