1+ package examples ;
2+
3+ import java .io .File ;
4+ import java .io .FileOutputStream ;
5+ import java .util .List ;
6+ import java .util .Map ;
7+ import java .util .UUID ;
8+
9+ import javax .ws .rs .client .ClientBuilder ;
10+
11+ import org .apache .poi .xssf .usermodel .XSSFCell ;
12+ import org .apache .poi .xssf .usermodel .XSSFRow ;
13+ import org .apache .poi .xssf .usermodel .XSSFSheet ;
14+ import org .apache .poi .xssf .usermodel .XSSFWorkbook ;
15+ import org .glassfish .jersey .apache .connector .ApacheConnectorProvider ;
16+ import org .glassfish .jersey .client .ClientProperties ;
17+
18+ import com .factset .protobuf .stach .extensions .RowStachExtensionBuilder ;
19+ import com .factset .protobuf .stach .extensions .StachExtensionFactory ;
20+ import com .factset .protobuf .stach .extensions .models .StachVersion ;
21+ import com .factset .protobuf .stach .extensions .models .TableData ;
22+ import com .fasterxml .jackson .core .JsonProcessingException ;
23+ import com .fasterxml .jackson .databind .JsonNode ;
24+ import com .fasterxml .jackson .databind .ObjectMapper ;
25+
26+ import factset .analyticsapi .engines .ApiClient ;
27+ import factset .analyticsapi .engines .ApiException ;
28+ import factset .analyticsapi .engines .ApiResponse ;
29+ import factset .analyticsapi .engines .api .AxpOptimizerApi ;
30+ import factset .analyticsapi .engines .models .AxiomaEquityOptimizationParameters ;
31+ import factset .analyticsapi .engines .models .AxiomaEquityOptimizationParametersRoot ;
32+ import factset .analyticsapi .engines .models .AxiomaEquityOptimizerStrategy ;
33+ import factset .analyticsapi .engines .models .ObjectRoot ;
34+ import factset .analyticsapi .engines .models .Optimization ;
35+ import factset .analyticsapi .engines .models .OptimizerAccount ;
36+ import factset .analyticsapi .engines .models .OptimizerOptimalHoldings ;
37+ import factset .analyticsapi .engines .models .OptimizerOutputTypes ;
38+ import factset .analyticsapi .engines .models .OptimizerTradesList ;
39+ import factset .analyticsapi .engines .models .OptimizerTradesList .IdentifierTypeEnum ;
40+
41+ public class AxpInteractiveOptimizerEngineExample {
42+ private static FdsApiClient apiClient = null ;
43+ private static String BASE_PATH = "https://api.factset.com" ;
44+ private static String USERNAME = "<username-serial>" ;
45+ private static String PASSWORD = "<apiKey>" ;
46+
47+ private static String AXIOMA_ACCOUNT_ID = "CLIENT:/OPTIMIZER/IBM.ACCT" ;
48+ private static String OPTIMIZATION_DATE = "09/01/2020" ;
49+ private static String OPTIMIZATION_CASHFLOW = "0" ;
50+ private static String STRATEGY_ID = "Client:/Optimizer/CN_TEST" ;
51+ private static IdentifierTypeEnum TRADES_ID_TYPE = IdentifierTypeEnum .ASSET ;
52+ private static Boolean INCLUDE_CASH = false ;
53+ private static Boolean EXCLUDE_ZERO = false ;
54+
55+ private static Integer DEADLINE_HEADER_VALUE = 20 ;
56+
57+ public static void main (String [] args ) throws InterruptedException , JsonProcessingException {
58+ try {
59+ AxpOptimizerApi apiInstance = new AxpOptimizerApi (getApiClient ());
60+ AxiomaEquityOptimizationParameters axpItem = new AxiomaEquityOptimizationParameters ();
61+ OptimizerAccount accountId = new OptimizerAccount ();
62+ accountId .setId (AXIOMA_ACCOUNT_ID );
63+
64+ Optimization optimization = new Optimization ();
65+ optimization .setBacktestDate (OPTIMIZATION_DATE );
66+ optimization .setRiskModelDate (OPTIMIZATION_DATE );
67+ optimization .setCashflow (OPTIMIZATION_CASHFLOW );
68+
69+ AxiomaEquityOptimizerStrategy strategy = new AxiomaEquityOptimizerStrategy ();
70+ strategy .setId (STRATEGY_ID );
71+
72+ OptimizerOutputTypes optOutputTypes = new OptimizerOutputTypes ();
73+ OptimizerTradesList tradesList = new OptimizerTradesList ();
74+ tradesList .setIdentifierType (TRADES_ID_TYPE );
75+ tradesList .setIncludeCash (INCLUDE_CASH );
76+ optOutputTypes .setTrades (tradesList );
77+
78+ // OptimizerOptimalHoldings optimal = new OptimizerOptimalHoldings();
79+ // optimal.setIdentifierType(OptimizerOptimalHoldings.IdentifierTypeEnum.ASSET);
80+ // optimal.setIncludeCash(INCLUDE_CASH);
81+ // optimal.setExcludeZero(EXCLUDE_ZERO);
82+ // optOutputTypes.setOptimal(optimal);
83+
84+ axpItem .setAccount (accountId );
85+ axpItem .setOptimization (optimization );
86+ axpItem .setStrategy (strategy );
87+ axpItem .setOutputTypes (optOutputTypes );
88+ AxiomaEquityOptimizationParametersRoot axpOptimizerParam = new AxiomaEquityOptimizationParametersRoot ();
89+ axpOptimizerParam .setData (axpItem );
90+
91+ ApiResponse <Object > response = apiInstance .postAndOptimizeWithHttpInfo (DEADLINE_HEADER_VALUE , "max-stale=0" , axpOptimizerParam );
92+ Map <String , List <String >> headers = response .getHeaders ();
93+
94+ Object result = null ;
95+ switch (response .getStatusCode ()) {
96+ case 201 : // Calculation completed
97+ System .out .println ("Calculation successful!!!" );
98+ result = ((ObjectRoot )response .getData ()).getData ();
99+ headers = response .getHeaders ();
100+ break ;
101+ case 202 :
102+ String [] locationList = headers .get ("Location" ).get (0 ).split ("/" );
103+ String requestId = locationList [locationList .length - 2 ];
104+ do {
105+ response = apiInstance .getOptimizationStatusByIdWithHttpInfo (requestId );
106+ headers = response .getHeaders ();
107+
108+ List <String > cacheControl = headers .get ("Cache-Control" );
109+ if (cacheControl != null ) {
110+ int maxAge = Integer .parseInt (cacheControl .get (0 ).replace ("max-age=" , "" ));
111+ System .out .println ("Sleeping for: " + maxAge + " seconds" );
112+ Thread .sleep (maxAge * 1000L );
113+ } else {
114+ System .out .println ("Sleeping for: 2 seconds" );
115+ Thread .sleep (2 * 1000L );
116+ }
117+ } while (response .getStatusCode () == 202 );
118+
119+ System .out .println ("Calculation successful!!!" );
120+ // Get Calculation Result
121+ String [] location = headers .get ("Location" ).get (0 ).split ("/" );
122+ String id = location [location .length - 2 ];
123+ ApiResponse <ObjectRoot > resultResponse = apiInstance .getOptimizationResultWithHttpInfo (id );
124+ result = resultResponse .getData ().getData ();
125+ break ;
126+ }
127+
128+ List <TableData > tables = null ;
129+ try {
130+ ObjectMapper mapper = new ObjectMapper ();
131+ String jsonString = mapper .writeValueAsString (result );
132+ JsonNode jsonObject = mapper .readTree (jsonString );
133+
134+ RowStachExtensionBuilder stachExtensionBuilder = StachExtensionFactory .getRowOrganizedBuilder (StachVersion .V2 );
135+ stachExtensionBuilder .addTable ("tradesTable" , jsonObject .get ("trades" ));
136+ // stachExtensionBuilder.addTable("optimalTable", jsonObject.get("optimal"));
137+ tables = stachExtensionBuilder .build ().convertToTable ();
138+ } catch (Exception e ) {
139+ System .out .println (e .getMessage ());
140+ e .printStackTrace ();
141+ }
142+
143+ ObjectMapper mapper = new ObjectMapper ();
144+ String json = mapper .writeValueAsString (tables );
145+ System .out .println (json ); // Prints the result in 2D table format.
146+ // Uncomment the following line to generate an Excel file
147+ // generateExcel(tables);
148+ } catch (ApiException e ) {
149+ handleException ("AxpOptimizerEngineExample#Main" , e );
150+ }
151+ }
152+
153+ private static void generateExcel (List <TableData > tableList ) {
154+ for (TableData table : tableList ) {
155+ writeDataToExcel (table , UUID .randomUUID ().toString () + ".xlsv" );
156+ }
157+ }
158+
159+ private static void writeDataToExcel (TableData table , String fileLocation ) {
160+ XSSFWorkbook workbook = new XSSFWorkbook ();
161+ XSSFSheet sheet = workbook .createSheet ("Calculation Report" );
162+ int rowsSize = table .getRows ().size ();
163+ for (int rowIndex = 0 ; rowIndex < rowsSize ; rowIndex ++) {
164+ XSSFRow xsswRow = sheet .createRow (rowIndex );
165+ List <String > cells = table .getRows ().get (rowIndex ).getCells ();
166+ for (int cellIndex = 0 ; cellIndex < cells .size (); cellIndex ++) {
167+ XSSFCell xssfCell = xsswRow .createCell (cellIndex );
168+ xssfCell .setCellValue (cells .get (cellIndex ));
169+ }
170+ }
171+ try {
172+ FileOutputStream fileStream = new FileOutputStream (new File (fileLocation ));
173+ workbook .write (fileStream );
174+ fileStream .close ();
175+ workbook .close ();
176+ } catch (Exception e ) {
177+ System .err .println ("Failed to write data to excel" );
178+ e .printStackTrace ();
179+ }
180+ }
181+
182+ private static class FdsApiClient extends ApiClient
183+ {
184+ // Uncomment the below lines to use a proxy server
185+ /*@Override
186+ protected void customizeClientBuilder(ClientBuilder clientBuilder) {
187+ clientConfig.property( ClientProperties.PROXY_URI, "http://127.0.0.1:8866" );
188+ clientConfig.connectorProvider( new ApacheConnectorProvider() );
189+ }*/
190+ }
191+
192+ private static FdsApiClient getApiClient () {
193+ if (apiClient != null ) {
194+ return apiClient ;
195+ }
196+
197+ apiClient = new FdsApiClient ();
198+ apiClient .setConnectTimeout (30000 );
199+ apiClient .setReadTimeout (30000 );
200+ apiClient .setBasePath (BASE_PATH );
201+ apiClient .setUsername (USERNAME );
202+ apiClient .setPassword (PASSWORD );
203+
204+ return apiClient ;
205+ }
206+
207+ private static void handleException (String method , ApiException e ) {
208+ System .err .println ("Exception when calling " + method );
209+ if (e .getResponseHeaders () != null && e .getResponseHeaders ().containsKey ("x-datadirect-request-key" )) {
210+ System .out .println ("x-datadirect-request-key: " + e .getResponseHeaders ().get ("x-datadirect-request-key" ).get (0 ));
211+ }
212+ System .out .println ("Status code: " + e .getCode ());
213+ System .out .println ("Reason: " + e .getClientErrorResponse ());
214+ e .printStackTrace ();
215+ }
216+ }
0 commit comments