List of usage examples for org.apache.commons.math.util MathUtils round
public static float round(float x, int scale)
From source file:ch.algotrader.service.ForexServiceImpl.java
/** * {@inheritDoc}/*from w w w .j a va 2 s . c o m*/ */ @Override public void hedgeForex() { Strategy server = this.strategyDao.findServer(); CoreConfig coreConfig = this.coreConfig; // potentially close a Forex Future position if it is below the MinTimeToExpiration if (coreConfig.isFxFutureHedgeEnabled()) { // get the closing orders final List<Order> orders = new ArrayList<>(); for (Position position : this.lookupService.getOpenPositionsByStrategyTypeAndUnderlyingType( StrategyImpl.SERVER, Future.class, Forex.class)) { // check if expiration is below minimum Future future = (Future) position.getSecurity(); Forex forex = (Forex) future.getUnderlying(); Subscription forexSubscription = this.subscriptionDao.findByStrategyAndSecurity(StrategyImpl.SERVER, forex.getId()); if (!forexSubscription.hasProperty("hedgingFamily")) { throw new IllegalStateException("no hedgingFamily defined for forex " + forex); } FutureFamily futureFamily = this.futureFamilyDao .load(forexSubscription.getIntProperty("hedgingFamily")); if (!future.getSecurityFamily().equals(futureFamily)) { // continue if forex is not hedged with this futureFamily continue; } if (future.getTimeToExpiration(this.engineManager.getCurrentEPTime()) < coreConfig .getFxFutureHedgeMinTimeToExpiration()) { Order order = this.orderService .createOrderByOrderPreference(coreConfig.getFxHedgeOrderPreference()); order.setStrategy(server); order.setSecurity(future); order.setQuantity(Math.abs(position.getQuantity())); order.setSide(position.getQuantity() > 0 ? Side.SELL : Side.BUY); orders.add(order); } } // setup an TradeCallback so that new hedge positions are only setup when existing positions are closed if (orders.size() > 0) { if (NOTIFICATION_LOGGER.isInfoEnabled()) { NOTIFICATION_LOGGER.info( "{} fx hedging position(s) have been closed due to approaching expiration, please run equalizeForex again", orders.size()); } // send the orders for (Order order : orders) { this.orderService.sendOrder(order); } return; // do not go any furter because closing trades will have to finish first } } // process all non-base currency balances Collection<BalanceVO> balances = this.portfolioService.getBalances(); for (BalanceVO balance : balances) { Currency portfolioBaseCurrency = this.commonConfig.getPortfolioBaseCurrency(); if (balance.getCurrency().equals(portfolioBaseCurrency)) { continue; } // get the netLiqValueBase double netLiqValue = balance.getNetLiqValue().doubleValue(); double netLiqValueBase = balance.getExchangeRate() * netLiqValue; // check if amount is larger than minimum if (Math.abs(netLiqValueBase) >= coreConfig.getFxHedgeMinAmount()) { // get the forex Forex forex = this.forexDao.getForex(portfolioBaseCurrency, balance.getCurrency()); double tradeValue = forex.getBaseCurrency().equals(portfolioBaseCurrency) ? netLiqValueBase : netLiqValue; // create the order Order order = this.orderService .createOrderByOrderPreference(coreConfig.getFxHedgeOrderPreference()); order.setStrategy(server); // if a hedging family is defined for this Forex use it instead of the Forex directly int qty; if (coreConfig.isFxFutureHedgeEnabled()) { Subscription forexSubscription = this.subscriptionDao .findByStrategyAndSecurity(StrategyImpl.SERVER, forex.getId()); if (!forexSubscription.hasProperty("hedgingFamily")) { throw new IllegalStateException("no hedgingFamily defined for forex " + forex); } FutureFamily futureFamily = this.futureFamilyDao .load(forexSubscription.getIntProperty("hedgingFamily")); Date targetDate = DateUtils.addMilliseconds(this.engineManager.getCurrentEPTime(), coreConfig.getFxFutureHedgeMinTimeToExpiration()); Future future = this.futureService.getFutureByMinExpiration(futureFamily.getId(), targetDate); // make sure the future is subscriped this.marketDataService.subscribe(server.getName(), future.getId()); order.setSecurity(future); // round to the number of contracts qty = (int) MathUtils.round(tradeValue / futureFamily.getContractSize(), 0); } else { order.setSecurity(forex); // round to batchSize qty = (int) RoundUtil.roundToNextN(tradeValue, coreConfig.getFxHedgeBatchSize()); } if (forex.getBaseCurrency().equals(portfolioBaseCurrency)) { // expected case order.setQuantity(Math.abs(qty)); order.setSide(qty > 0 ? Side.BUY : Side.SELL); } else { // reverse case order.setQuantity(Math.abs(qty)); order.setSide(qty > 0 ? Side.SELL : Side.BUY); } this.orderService.sendOrder(order); } else { if (LOGGER.isInfoEnabled()) { LOGGER.info("no forex hedge is performed on {} because amount {} is below {}", balance.getCurrency(), RoundUtil.getBigDecimal(Math.abs(netLiqValueBase)), coreConfig.getFxHedgeMinAmount()); } continue; } } }
From source file:cc.kave.episodes.mining.evaluation.Evaluation.java
private void getTargetResults(int targetID, Episode target) { TargetResults episodeResults = new TargetResults(); episodeResults.setTarget(target);/* ww w . j ava 2s.com*/ sb.append("Target query " + targetID + "\t"); for (Map.Entry<Double, List<Averager>> entry : avgQueryProposal.entrySet()) { sb.append(MathUtils.round(entry.getKey(), 2) + ": [ "); for (int p = 0; p < PROPOSALS; p++) { double qp = entry.getValue().get(p).average(); if (qp > 0.0) { double tp = avgTargetProposal.get(entry.getKey()).get(p).average(); episodeResults.addResult(entry.getKey(), qp, tp); sb.append("<" + MathUtils.round(qp, 2) + ", " + MathUtils.round(tp, 2) + ">; "); } } sb.append("]\t"); } sb.append(target.getNumEvents() - 1 + "\n"); results.add(episodeResults); }
From source file:cc.kave.episodes.mining.evaluation.Evaluation.java
private void configurations() { append("\n"); append("%% - Evaluations configuration:\n"); append("%% - Frequency = %d\n", FREQUENCY); append("%% - Bidirectional measure = %s\n", MathUtils.round(BIDIRECTIONAL, 2)); append("%% - Querying strategy = %s\n", Arrays.toString(percentages)); append("%% - Proposal strategy = %d\n", PROPOSALS); append("%% - Similarity metric = F1-value\n"); append("%% - Number of maximal queries = all combinations\n\n"); }
From source file:de.christianseipl.utilities.maputils.MapMath.java
/** * Fhrt die {@link MathUtils#round(double, int)} Operation auf jedem Element der Map * durch. Die Anzahl an signifikanten Stellen kann hierbei vorgegeben werden. * //ww w . ja v a 2 s. c o m * @param <K> ein beliebiger Objekttyp * * @param _map * Die Ursprungsmap * @param _scale Die Anzahl an signifikanten Stellen. * @return Eine neue Map, deren Wert das Ergebnis von * {@link Math#round(double)} darstellen. */ public static <K> Map<K, Double> round(Map<? extends K, ? extends Number> _map, final int _scale) { return operateOnMap(_map, new NumberTransformer<K, Double>() { @Override public Double transform(K _key, Number _number) { return Double.valueOf(MathUtils.round(_number.doubleValue(), _scale)); } }); }
From source file:ch.algotrader.simulation.SimulationExecutorImpl.java
private void rebalancePortfolio(final StrategyGroup strategyGroup) { double initialBalance = this.commonConfig.getSimulationInitialBalance().doubleValue(); double totalAllocation = 0.0; Set<String> strategyNames = strategyGroup.getStrategyNames(); for (String strategyName : strategyNames) { Strategy strategy = this.lookupService.getStrategyByName(strategyName); double weight = strategyGroup.getWeight(strategyName); totalAllocation += weight;/*from w w w .j a va 2 s . c o m*/ BigDecimal amount = RoundUtil.getBigDecimal(initialBalance * weight, 2); Transaction transaction = Transaction.Factory.newInstance(); transaction.setUuid(UUID.randomUUID().toString()); transaction.setDateTime(this.engineManager.getCurrentEPTime()); transaction.setQuantity(1); transaction.setPrice(amount); transaction.setCurrency(this.commonConfig.getPortfolioBaseCurrency()); transaction.setType(TransactionType.REBALANCE); transaction.setStrategy(strategy); this.transactionService.recordTransaction(transaction); } // check allocations add up to 1.0 if (MathUtils.round(totalAllocation, 2) != 1.0) { throw new IllegalStateException( "the total of all allocations is: " + totalAllocation + " where it should be 1.0"); } }
From source file:ch.algotrader.simulation.SimulationExecutorImpl.java
/** * {@inheritDoc}// w ww . j av a 2 s.co m */ @Override public void optimizeMultiParamLinear(final StrategyGroup strategyGroup, final String[] parameters, final double[] mins, final double[] maxs, final double[] increments) { Validate.notNull(parameters, "Parameter is null"); Validate.notNull(mins, "Mins is null"); Validate.notNull(maxs, "Maxs is null"); Validate.notNull(increments, "Increments is null"); int roundDigits = this.commonConfig.getPortfolioDigits(); for (double i0 = mins[0]; i0 <= maxs[0]; i0 += increments[0]) { System.setProperty(parameters[0], format.format(i0)); String message0 = parameters[0] + "=" + format.format(MathUtils.round(i0, roundDigits)); if (parameters.length >= 2) { for (double i1 = mins[1]; i1 <= maxs[1]; i1 += increments[1]) { System.setProperty(parameters[1], format.format(i1)); String message1 = parameters[1] + "=" + format.format(MathUtils.round(i1, roundDigits)); if (parameters.length >= 3) { for (double i2 = mins[2]; i2 <= maxs[2]; i2 += increments[2]) { System.setProperty(parameters[2], format.format(i2)); String message2 = parameters[2] + "=" + format.format(MathUtils.round(i2, roundDigits)); SimulationResultVO resultVO = runSimulation(strategyGroup); if (RESULT_LOGGER.isInfoEnabled()) { RESULT_LOGGER.info("{} {} {} {}", message0, message1, message2, convertStatisticsToShortString(resultVO)); } } } else { SimulationResultVO resultVO = runSimulation(strategyGroup); if (RESULT_LOGGER.isInfoEnabled()) { RESULT_LOGGER.info("{} {} {}", message0, message1, convertStatisticsToShortString(resultVO)); } } } } else { SimulationResultVO resultVO = runSimulation(strategyGroup); if (RESULT_LOGGER.isInfoEnabled()) { RESULT_LOGGER.info("{} {}", message0, convertStatisticsToShortString(resultVO)); } } } }
From source file:hoot.services.db.DbUtils.java
/** * Sets a geo-coordinate value to the decimal precision expected by the * services database/*from ww w .j a v a 2 s . c om*/ * * @param coordVal * a coordinate value * @return input coordinate value with the correct number of decimal places */ public static double toDbCoordPrecision(double coordVal) { return MathUtils.round(coordVal, 7); }
From source file:com.gtwm.pb.model.manageData.DataManagement.java
/** * Fetch direct from the database/*from w w w. ja v a 2s . co m*/ */ private ChartDataInfo fetchChartData(ChartInfo chart, Map<BaseField, String> reportFilterValues) throws CantDoThatException, SQLException { Set<ChartAggregateInfo> aggregateFunctions = chart.getAggregateFunctions(); Set<ChartGroupingInfo> groupings = chart.getGroupings(); logger.debug("Chart groupings are " + groupings); List<ChartDataRowInfo> reportSummaryRows; reportSummaryRows = new LinkedList<ChartDataRowInfo>(); Connection conn = null; PreparedStatement statement = null; try { conn = this.dataSource.getConnection(); conn.setAutoCommit(false); // First, cache the set of display values for relation fields Map<ReportFieldInfo, Map<String, String>> displayLookups = new HashMap<ReportFieldInfo, Map<String, String>>(); for (ChartGroupingInfo grouping : groupings) { ReportFieldInfo groupingReportField = grouping.getGroupingReportField(); BaseField baseField = groupingReportField.getBaseField(); if (baseField instanceof RelationField) { String relatedKey = ((RelationField) baseField).getRelatedField().getInternalFieldName(); String relatedDisplay = ((RelationField) baseField).getDisplayField().getInternalFieldName(); String relatedSource = ((RelationField) baseField).getRelatedTable().getInternalTableName(); Map<String, String> displayLookup = getKeyToDisplayMapping(conn, relatedSource, relatedKey, relatedDisplay); displayLookups.put(groupingReportField, displayLookup); } } // Create some maps to store min. and max. values of each // aggregate column // These numbers can be used e.g. to scale values when charting // summary data Map<ChartAggregateInfo, Number> maxAggValues = new HashMap<ChartAggregateInfo, Number>(); Map<ChartAggregateInfo, Number> minAggValues = new HashMap<ChartAggregateInfo, Number>(); Map<ChartAggregateInfo, Number> grandTotals = new HashMap<ChartAggregateInfo, Number>(); // Also a map for working with in the loop Map<ReportFieldInfo, Date> previousDateValues = new HashMap<ReportFieldInfo, Date>(); Calendar calendar = Calendar.getInstance(); // Get database data BaseReportInfo report = chart.getReport(); ReportData.enableOptimisations(conn, report, true); statement = chart.getChartSqlPreparedStatement(conn, reportFilterValues, false); long startTime = System.currentTimeMillis(); ResultSet summaryResults = statement.executeQuery(); while (summaryResults.next()) { ChartDataRowInfo resultRow = new ChartDataRow(); int resultColumn = 0; for (ChartGroupingInfo grouping : groupings) { ReportFieldInfo groupingReportField = grouping.getGroupingReportField(); SummaryGroupingModifier groupingModifier = grouping.getGroupingModifier(); BaseField baseField = groupingReportField.getBaseField(); resultColumn++; String value = ""; DatabaseFieldType dbType = baseField.getDbType(); if (baseField instanceof RelationField) { value = summaryResults.getString(resultColumn); Map<String, String> displayLookup = displayLookups.get(groupingReportField); value = displayLookup.get(value); } else if (dbType.equals(DatabaseFieldType.TIMESTAMP)) { if (groupingModifier != null) { value = summaryResults.getString(resultColumn); } else { Date dbValue = summaryResults.getTimestamp(resultColumn); if (dbValue != null) { if (groupingReportField instanceof ReportCalcFieldInfo) { // See DateFieldDefn constructor for // format // explanation value = ((ReportCalcFieldInfo) groupingReportField).formatDate(dbValue); } else { DateField dateField = (DateField) baseField; value = (dateField.formatDate(dbValue)); if (Integer.valueOf(dateField.getDateResolution()) .equals(Calendar.DAY_OF_MONTH)) { Date previousDbValue = previousDateValues.get(groupingReportField); if (previousDbValue != null) { calendar.setTime(previousDbValue); int previousDayOfYear = calendar.get(Calendar.DAY_OF_YEAR); calendar.setTime(dbValue); int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR); int difference = Math.abs(dayOfYear - previousDayOfYear); if (difference > 1) { value += " (" + (difference - 1) + " day gap)"; } } previousDateValues.put(groupingReportField, dbValue); } } } } } else if (dbType.equals(DatabaseFieldType.FLOAT)) { double floatValue = summaryResults.getDouble(resultColumn); if (baseField instanceof DecimalField) { value = ((DecimalField) baseField).formatFloat(floatValue); } else if (groupingReportField instanceof ReportCalcFieldInfo) { value = ((ReportCalcFieldInfo) groupingReportField).formatFloat(floatValue); } else { value = summaryResults.getString(resultColumn); } } else if (dbType.equals(DatabaseFieldType.BOOLEAN)) { if (summaryResults.getBoolean(resultColumn)) { value = "true"; } else { value = "false"; } } else { value = summaryResults.getString(resultColumn); } resultRow.addGroupingValue(grouping, value); } for (ChartAggregateInfo aggregateFunction : aggregateFunctions) { resultColumn++; DatabaseFieldType dbType = aggregateFunction.getReportField().getBaseField().getDbType(); Double value = null; // deal with aggregate results which are timestamps // rather than doubles if ((!aggregateFunction.getAggregateFunction().equals(AggregateFunction.COUNT)) && (dbType.equals(DatabaseFieldType.TIMESTAMP))) { java.sql.Timestamp timestampValue = summaryResults.getTimestamp(resultColumn); if (timestampValue != null) { Long longValue = timestampValue.getTime(); value = longValue.doubleValue(); } } else { value = summaryResults.getDouble(resultColumn); } if (value != null) { int precision = 1; ReportFieldInfo aggReportField = aggregateFunction.getReportField(); if (aggReportField instanceof ReportCalcFieldInfo) { DatabaseFieldType dbFieldType = ((ReportCalcFieldInfo) aggReportField).getDbType(); if (dbFieldType.equals(DatabaseFieldType.FLOAT)) { precision = ((ReportCalcFieldInfo) aggReportField).getDecimalPrecision(); } } else if (aggReportField.getBaseField() instanceof DecimalField) { precision = ((DecimalField) aggReportField.getBaseField()).getPrecision(); } Number currentGrandTotal = grandTotals.get(aggregateFunction); if (currentGrandTotal == null) { currentGrandTotal = new Double(0); } double currentGrandTotalDbl = currentGrandTotal.doubleValue() + value; grandTotals.put(aggregateFunction, Double.valueOf(currentGrandTotalDbl)); value = MathUtils.round(value, precision); resultRow.addAggregateValue(aggregateFunction, value); Number currentMin = minAggValues.get(aggregateFunction); Number currentMax = maxAggValues.get(aggregateFunction); if (currentMin == null) { minAggValues.put(aggregateFunction, value); } else if (value.doubleValue() < currentMin.doubleValue()) { minAggValues.put(aggregateFunction, value); } if (currentMax == null) { maxAggValues.put(aggregateFunction, value); } else if (value.doubleValue() > currentMax.doubleValue()) { maxAggValues.put(aggregateFunction, value); } } } reportSummaryRows.add(resultRow); } summaryResults.close(); statement.close(); ReportData.enableOptimisations(conn, report, false); float durationSecs = (System.currentTimeMillis() - startTime) / ((float) 1000); if (durationSecs > AppProperties.longSqlTime) { logger.debug("Long SELECT SQL execution time of " + durationSecs + " seconds for summary '" + chart + "', statement = " + statement); } return new ChartData(reportSummaryRows, minAggValues, maxAggValues, grandTotals); } catch (SQLException sqlex) { throw new SQLException( "Error getting report summary data " + chart + ": " + sqlex + ". SQL = " + statement); } finally { if (conn != null) { conn.close(); } } }
From source file:org.gbif.portal.util.geospatial.CellIdUtils.java
private static boolean isBoundingBoxCentiCell(float minLongitude, float minLatitude, float maxLongitude, float maxLatitude) { float width = maxLongitude > minLongitude ? maxLongitude - minLongitude : minLongitude - maxLongitude; float height = maxLatitude > minLatitude ? maxLatitude - minLatitude : minLatitude - maxLatitude; return MathUtils.round(height, 1) == 0.1f && MathUtils.round(width, 1) == 0.1f; }
From source file:org.peerfact.impl.overlay.dht.kademlia2.measurement.file.ConfidenceCalculatorTest.java
/** * Tests the ConfidenceCalculator with sample data from Jain, R.; The Art of * Computer Systems Performance Analysis, Wiley & Sons, New York 1991, * p. 208./*from www.j a v a 2s .com*/ */ @Test public static void testConfidenceCalculator() { /* * Some expected values differ from the data in [Jain] as we calculate * with greater precision. */ double[] actual = ConfidenceCalculator.calc(new double[] { 1.5, 2.6, -1.8, 1.3, -0.5, 1.7, 2.4 }, 0.01); assertEquals("Expected mean 1.03", 1.03, MathUtils.round(actual[0], 2), 0.1); assertEquals("Expected standard deviation 1.6", 1.6, MathUtils.round(actual[1], 2), 0.1); assertEquals("Expected delta 2.25", 2.25, MathUtils.round(actual[2], 2), 0.1); assertEquals("Expected lower bound -1.22", -1.22, MathUtils.round(actual[3], 2), 0.1); assertEquals("Expected upper bound 3.28", 3.28, MathUtils.round(actual[4], 2), 0.1); }