protected FXForwardSecurity createFXForwardSecurity(final Bundle bundle) { final double putAmount = bundle._firstCurrency.equals(Currency.JPY) ? NOTIONAL * 100 : NOTIONAL; final ZonedDateTime forwardDate = nextWorkingDay( bundle._tradeDate.plusDays(bundle._daysOffset), bundle._firstCurrency, bundle._secondCurrency); final Double fxRate = getApproxFXRate( forwardDate.toLocalDate(), Pair.of(bundle._firstCurrency, bundle._secondCurrency)); if (fxRate == null) { return null; } final double callAmount = NOTIONAL * fxRate; final Currency payCurrency = bundle._long ? bundle._secondCurrency : bundle._firstCurrency; final Currency receiveCurrency = bundle._long ? bundle._firstCurrency : bundle._secondCurrency; final String dateString = forwardDate.toString(DATE_FORMATTER); final FXForwardSecurity fxForwardSecurity = new FXForwardSecurity( payCurrency, callAmount, receiveCurrency, putAmount, forwardDate, REGION); final String callAmountString = NOTIONAL_FORMATTER.format(callAmount); final String putAmountString = NOTIONAL_FORMATTER.format(putAmount); fxForwardSecurity.setName( "Pay " + payCurrency + " " + callAmountString + ", receive " + receiveCurrency + " " + putAmountString + " on " + dateString); return fxForwardSecurity; }
protected FXDigitalOptionSecurity createFXDigitalOptionSecurity(final Bundle bundle) { final Currency putCurrency = bundle._firstCurrency; final Currency callCurrency = bundle._secondCurrency; final Currency paymentCurrency = bundle._paymentCurrency; final double putAmount = putCurrency.equals(Currency.JPY) ? NOTIONAL * 100 : NOTIONAL; final ZonedDateTime expiry = nextWorkingDay(bundle._tradeDate.plusDays(bundle._daysOffset), putCurrency, callCurrency); final Double rate = getApproxFXRate(expiry.toLocalDate(), Pair.of(putCurrency, callCurrency)); if (rate == null) { return null; } final double callAmount = rate * NOTIONAL; final ZonedDateTime settlementDate = nextWorkingDay(expiry.plusDays(2), putCurrency, callCurrency); final FXDigitalOptionSecurity security = new FXDigitalOptionSecurity( putCurrency, callCurrency, putAmount, callAmount, paymentCurrency, new Expiry(expiry), settlementDate, bundle._long); final StringBuilder sb = new StringBuilder("Digital "); sb.append(bundle._long ? "Long" : "Short"); sb.append(" put ").append(putCurrency).append(' ').append(NOTIONAL_FORMATTER.format(putAmount)); sb.append(", call ") .append(callCurrency) .append(' ') .append(NOTIONAL_FORMATTER.format(callAmount)); sb.append(" on ").append(expiry.toString(DATE_FORMATTER)); security.setName(sb.toString()); return security; }
protected FXBarrierOptionSecurity createFXBarrierOptionSecurity(final Bundle bundle) { final Currency putCurrency = bundle._firstCurrency; final Currency callCurrency = bundle._secondCurrency; final double putAmount = putCurrency.equals(Currency.JPY) ? NOTIONAL * 100 : NOTIONAL; final ZonedDateTime settlementDate = nextWorkingDay( bundle._tradeDate.plusDays(bundle._daysOffset), bundle._firstCurrency, bundle._secondCurrency); final Expiry expiry = new Expiry(settlementDate, ExpiryAccuracy.DAY_MONTH_YEAR); final Double fxRate = getApproxFXRate( settlementDate.toLocalDate(), Pair.of(bundle._firstCurrency, bundle._secondCurrency)); if (fxRate == null) { return null; } final double callAmount = NOTIONAL * fxRate; final String dateString = settlementDate.toString(DATE_FORMATTER); final BarrierType barrierType = bundle._up ? BarrierType.UP : BarrierType.DOWN; final BarrierDirection barrierDirection = BarrierDirection.KNOCK_IN; final MonitoringType monitoringType = MonitoringType.CONTINUOUS; final SamplingFrequency samplingFrequency = SamplingFrequency.DAILY_CLOSE; final double barrierLevel = bundle._up ? fxRate * 1.5 : fxRate / 1.5; final FXBarrierOptionSecurity fxBarrierOptionSecurity = new FXBarrierOptionSecurity( putCurrency, callCurrency, putAmount, callAmount, expiry, settlementDate, barrierType, barrierDirection, monitoringType, samplingFrequency, barrierLevel, bundle._long); final String callAmountString = NOTIONAL_FORMATTER.format(callAmount); final String putAmountString = NOTIONAL_FORMATTER.format(putAmount); final String barrierLevelString = RATE_FORMATTER.format(barrierLevel); final String barrierUnitString = callCurrency + "/" + putCurrency; fxBarrierOptionSecurity.setName( (bundle._long ? "Long " : "Short ") + (bundle._up ? "up" : "down") + " knock-in at " + barrierLevelString + " " + barrierUnitString + ", put " + putCurrency + " " + putAmountString + ", call " + callCurrency + " " + callAmountString + " on " + dateString); return fxBarrierOptionSecurity; }
/** * Entry point from the service wrapper - starts a connection handler for a given client. * * @param userName the user name of the incoming connection * @param inputPipeName the pipe created for sending data from C++ to Java * @param outputPipeName the pipe created for sending data from Java to C++ * @param languageID the identifier of the bound language. Language specific factories will be * used if present, otherwise the default factories will be used. * @param debug true if the bound language is a debug build * @return true if the connection started okay */ public static synchronized boolean svcAccept( final String userName, final String inputPipeName, final String outputPipeName, final String languageID, final boolean debug) { try { s_logger.info("Accepted {} connection from {}", languageID, userName); s_logger.debug("Using pipes IN:{} OUT:{}", inputPipeName, outputPipeName); final Pair<ClientFactory, SessionContextFactory> factories = s_springContext.getLanguageFactories(languageID); final SessionContext sessionContext = factories.getSecond().createSessionContext(userName, debug); final Client client = factories.getFirst().createClient(inputPipeName, outputPipeName, sessionContext); s_activeConnections++; s_executorService.submit( new Runnable() { @Override public void run() { client.run(); s_logger.info("Session for {} disconnected", userName); clientDisconnected(); } }); return true; } catch (Throwable t) { s_logger.error("Exception thrown", t); return false; } }
/* package */ void updateDepGraphCells(Set<WebGridCell> newCells) { Set<WebGridCell> currentCells = _depGraphGrids.keySet(); Set<WebGridCell> cellsToRemove = Sets.difference(currentCells, newCells); Set<WebGridCell> cellsToAdd = Sets.difference(newCells, currentCells); for (WebGridCell cell : cellsToRemove) { _depGraphGrids.remove(cell); } for (WebGridCell cell : cellsToAdd) { String gridName = getName() + ".depgraph-" + cell.getRowId() + "-" + cell.getColumnId(); OperationTimer timer = new OperationTimer(s_logger, "depgraph"); Pair<String, ValueSpecification> columnMappingPair = getGridStructure() .findCellSpecification(cell, getViewClient().getLatestCompiledViewDefinition()); s_logger.debug("includeDepGraph took {}", timer.finished()); // TODO should this ever happen? it is currently if (columnMappingPair != null) { PushWebViewDepGraphGrid grid = new PushWebViewDepGraphGrid( gridName, getViewClient(), getConverterCache(), cell, columnMappingPair.getFirst(), columnMappingPair.getSecond()); _depGraphGrids.put(cell, grid); } } }
private static void populateVolatilitySurfaceDefinitions( final ConfigMaster configMaster, final UniqueIdentifiable target) { final Tenor[] expiryTenors = new Tenor[] { Tenor.ofDays(7), Tenor.ofDays(14), Tenor.ofDays(21), Tenor.ofMonths(1), Tenor.ofMonths(3), Tenor.ofMonths(6), Tenor.ofMonths(9), Tenor.ofYears(1), Tenor.ofYears(5), Tenor.ofYears(10) }; @SuppressWarnings("unchecked") final Pair<Number, FXVolQuoteType>[] deltaAndTypes = new Pair[] { Pair.of(25, FXVolQuoteType.BUTTERFLY), Pair.of(25, FXVolQuoteType.RISK_REVERSAL), Pair.of(15, FXVolQuoteType.BUTTERFLY), Pair.of(15, FXVolQuoteType.RISK_REVERSAL), Pair.of(0, FXVolQuoteType.ATM) }; final VolatilitySurfaceDefinition<Tenor, Pair<Number, FXVolQuoteType>> volSurfaceDefinition = new VolatilitySurfaceDefinition<Tenor, Pair<Number, FXVolQuoteType>>( "SECONDARY_EURUSD_" + InstrumentTypeProperties.FOREX, target, expiryTenors, deltaAndTypes); ConfigMasterUtils.storeByName(configMaster, makeConfigDocument(volSurfaceDefinition)); }
public static VolatilityAndBucketedSensitivities getVolatilityAndSensitivities( final SmileDeltaTermStructureDataBundle data, final Currency ccy1, final Currency ccy2, final double time, final double strike, final double forward) { ArgumentChecker.notNull(ccy1, "ccy1"); ArgumentChecker.notNull(ccy2, "ccy2"); ArgumentChecker.notNull(data, "data"); final Pair<Currency, Currency> currencyPair = data.getCurrencyPair(); final SmileDeltaTermStructureParametersStrikeInterpolation smile = data.getVolatilityModel(); if ((ccy1 == currencyPair.getFirst()) && (ccy2 == currencyPair.getSecond())) { return smile.getVolatilityAndSensitivities(time, strike, forward); } if ((ccy2 == currencyPair.getFirst()) && (ccy1 == currencyPair.getSecond())) { return smile.getVolatilityAndSensitivities(time, 1.0 / strike, 1.0 / forward); } throw new IllegalArgumentException( "Currencies not compatible with smile data; asked for " + ccy1 + " and " + ccy2 + ", have " + data.getCurrencyMap().values()); }
/** * Creates the output root data. * * @return the output root data, not null */ protected FlexiBean createRootData() { FlexiBean out = super.createRootData(); HolidayDocument latestDoc = data().getHoliday(); HolidayDocument versionedHoliday = data().getVersioned(); out.put("latestHolidayDoc", latestDoc); out.put("latestHoliday", latestDoc.getHoliday()); out.put("holidayDoc", versionedHoliday); out.put("holiday", versionedHoliday.getHoliday()); out.put("deleted", !latestDoc.isLatest()); List<Pair<Year, List<LocalDate>>> map = new ArrayList<Pair<Year, List<LocalDate>>>(); List<LocalDate> dates = versionedHoliday.getHoliday().getHolidayDates(); if (dates.size() > 0) { int year = dates.get(0).getYear(); int start = 0; int pos = 0; for (; pos < dates.size(); pos++) { if (dates.get(pos).getYear() == year) { continue; } map.add(Pair.of(Year.of(year), dates.subList(start, pos))); year = dates.get(pos).getYear(); start = pos; } map.add(Pair.of(Year.of(year), dates.subList(start, pos))); } out.put("holidayDatesByYear", map); return out; }
private static List<RequirementBasedColumnKey> getRequirements( ViewDefinition viewDefinition, EnumSet<ComputationTargetType> targetTypes) { List<RequirementBasedColumnKey> result = new ArrayList<RequirementBasedColumnKey>(); for (ViewCalculationConfiguration calcConfig : viewDefinition.getAllCalculationConfigurations()) { String calcConfigName = calcConfig.getName(); if (targetTypes.contains(ComputationTargetType.POSITION) || targetTypes.contains(ComputationTargetType.PORTFOLIO_NODE)) { for (Pair<String, ValueProperties> portfolioOutput : calcConfig.getAllPortfolioRequirements()) { String valueName = portfolioOutput.getFirst(); ValueProperties constraints = portfolioOutput.getSecond(); RequirementBasedColumnKey columnKey = new RequirementBasedColumnKey(calcConfigName, valueName, constraints); result.add(columnKey); } } for (ValueRequirement specificRequirement : calcConfig.getSpecificRequirements()) { if (!targetTypes.contains(specificRequirement.getTargetSpecification().getType())) { continue; } String valueName = specificRequirement.getValueName(); ValueProperties constraints = specificRequirement.getConstraints(); RequirementBasedColumnKey columnKey = new RequirementBasedColumnKey(calcConfigName, valueName, constraints); result.add(columnKey); } } return result; }
@BeforeClass public void createServer() throws Exception { Pair<Server, WebApplicationContext> serverAndContext = _webPushTestUtils.createJettyServer( "classpath:/com/opengamma/web/analytics/push/rest-subscription-test.xml"); _server = serverAndContext.getFirst(); WebApplicationContext context = serverAndContext.getSecond(); _positionChangeManager = context.getBean("positionChangeManager", TestChangeManager.class); }
private ResolutionIterator(final Pair<?, ?> values) { _properties = values.getFirst(); _functions = values.getSecond(); if (_properties instanceof ValueProperties) { _length = 1; } else { _length = ((ValueProperties[]) _properties).length; } _index = 0; }
@Override public CurveBuildingBlockBundle buildObject( final FudgeDeserializer deserializer, final FudgeMsg message) { final List<FudgeField> curveNames = message.getAllByName(CURVE_NAME_FIELD); final List<FudgeField> blocks = message.getAllByName(BLOCK_FIELD); final List<FudgeField> matrices = message.getAllByName(MATRIX_FIELD); final int n = curveNames.size(); if (blocks.size() != n) { throw new IllegalStateException( "Should have one block for each curve name; have " + curveNames + " and " + blocks); } if (matrices.size() != n) { throw new IllegalStateException( "Should have one matrix for each curve name; have " + curveNames + " and " + matrices); } final LinkedHashMap<String, Pair<CurveBuildingBlock, DoubleMatrix2D>> data = new LinkedHashMap<>(); for (int i = 0; i < n; i++) { final String curveName = (String) curveNames.get(i).getValue(); final CurveBuildingBlock block = deserializer.fieldValueToObject(CurveBuildingBlock.class, blocks.get(i)); final DoubleMatrix2D m = new DoubleMatrix2D(deserializer.fieldValueToObject(double[][].class, matrices.get(i))); data.put(curveName, Pair.of(block, m)); } return new CurveBuildingBlockBundle(data); }
@Override public synchronized YieldCurveDefinitionDocument update(YieldCurveDefinitionDocument document) { ArgumentChecker.notNull(document, "document"); ArgumentChecker.notNull(document.getYieldCurveDefinition(), "document.yieldCurveDefinition"); final Currency currency = document.getYieldCurveDefinition().getCurrency(); final String name = document.getYieldCurveDefinition().getName(); final UniqueId uid = UniqueId.of(getUniqueIdScheme(), name + "_" + currency.getCode()); if (!uid.equals(document.getUniqueId())) { throw new IllegalArgumentException("Invalid unique identifier"); } final Pair<Currency, String> key = Pair.of(currency, name); final TreeMap<Instant, YieldCurveDefinition> value = _definitions.get(key); if (value == null) { throw new DataNotFoundException("UID '" + uid + "' not found"); } if (_sourceVersionCorrection.getVersionAsOf() != null) { // Don't need to keep the old values before the one needed by "versionAsOfInstant" final Instant oldestNeeded = value.floorKey(_sourceVersionCorrection.getVersionAsOf()); value.headMap(oldestNeeded).clear(); } else { // Don't need any old values value.clear(); } Instant now = Instant.now(); value.put(now, document.getYieldCurveDefinition()); document.setUniqueId(uid); changeManager().entityChanged(ChangeType.CHANGED, uid.getObjectId(), null, null, now); return document; }
@Override public synchronized YieldCurveDefinitionDocument get( ObjectIdentifiable objectIdable, VersionCorrection versionCorrection) { ArgumentChecker.notNull(objectIdable, "objectIdable"); ObjectId objectId = objectIdable.getObjectId(); if (!getUniqueIdScheme().equals(objectId.getScheme())) { throw new DataNotFoundException( "Scheme '" + objectId.getScheme() + "' not valid for '" + getUniqueIdScheme() + "'"); } final int i = objectId.getValue().indexOf('_'); if (i <= 0) { throw new DataNotFoundException( "Identifier '" + objectId.getValue() + "' not valid for '" + getUniqueIdScheme() + "'"); } final String name = objectId.getValue().substring(0, i); final String iso = objectId.getValue().substring(i + 1); final Currency currency; try { currency = Currency.of(iso); } catch (IllegalArgumentException e) { throw new DataNotFoundException( "Identifier '" + objectId.getValue() + "' not valid for '" + getUniqueIdScheme() + "'", e); } final TreeMap<Instant, YieldCurveDefinition> definitions = _definitions.get(Pair.of(currency, name)); if (definitions == null) { throw new DataNotFoundException("Curve definition not found"); } final YieldCurveDefinition definition = definitions.lastEntry().getValue(); if (definition == null) { throw new DataNotFoundException("Curve definition not found"); } return new YieldCurveDefinitionDocument(objectId.atLatestVersion(), definition); }
// ------------------------------------------------------------------------- @Override public synchronized YieldCurveDefinitionDocument add(YieldCurveDefinitionDocument document) { ArgumentChecker.notNull(document, "document"); ArgumentChecker.notNull(document.getYieldCurveDefinition(), "document.yieldCurveDefinition"); final Currency currency = document.getYieldCurveDefinition().getCurrency(); final String name = document.getYieldCurveDefinition().getName(); final Pair<Currency, String> key = Pair.of(currency, name); if (_definitions.containsKey(key)) { throw new IllegalArgumentException("Duplicate definition"); } final TreeMap<Instant, YieldCurveDefinition> value = new TreeMap<Instant, YieldCurveDefinition>(); Instant now = Instant.now(); value.put(now, document.getYieldCurveDefinition()); _definitions.put(key, value); final UniqueId uid = UniqueId.of(getUniqueIdScheme(), name + "_" + currency.getCode()); document.setUniqueId(uid); changeManager() .entityChanged( ChangeType.ADDED, document.getObjectId(), document.getVersionFromInstant(), document.getVersionToInstant(), now); return document; }
@Override public CurveBuildingBlock buildObject( final FudgeDeserializer deserializer, final FudgeMsg message) { final List<FudgeField> curveNames = message.getAllByName(CURVE_NAME_FIELD); final List<FudgeField> startIndices = message.getAllByName(START_INDEX_FIELD); final int n = curveNames.size(); if (startIndices.size() != n) { throw new IllegalStateException( "Should have one start index for each curve name; have " + curveNames + " and " + startIndices); } final List<FudgeField> numbers = message.getAllByName(NUMBER_FIELD); if (numbers.size() != n) { throw new IllegalStateException( "Should have one parameter number for each curve name; have " + curveNames + " and " + numbers); } final LinkedHashMap<String, Pair<Integer, Integer>> data = new LinkedHashMap<>(); for (int i = 0; i < n; i++) { final String curveName = (String) curveNames.get(i).getValue(); final Integer startIndex = ((Number) startIndices.get(i).getValue()).intValue(); final Integer number = ((Number) numbers.get(i).getValue()).intValue(); data.put(curveName, Pair.of(startIndex, number)); } return new CurveBuildingBlock(data); }
@SuppressWarnings("unchecked") @Test public void expandedRectangular() { Tenor[] xVals = new Tenor[] {Tenor.DAY, Tenor.ONE_WEEK, Tenor.TWO_WEEKS}; Tenor[] yVals = new Tenor[] {Tenor.ONE_YEAR, Tenor.TWO_YEARS}; double[] vols = new double[] {10, 11, 12, 13, 14, 15}; Map<Pair<Tenor, Tenor>, Double> vol = Maps.newHashMap(); for (int y = 0; y < yVals.length; y++) { for (int x = 0; x < xVals.length; x++) { vol.put(Pair.of(xVals[x], yVals[y]), vols[x + (y * xVals.length)]); } } String name = "test"; UniqueIdentifiable target = Currency.USD; VolatilitySurfaceData<Tenor, Tenor> data = new VolatilitySurfaceData<>(name, name, target, xVals, yVals, vol); Map<String, Object> map = (Map<String, Object>) new VolatilitySurfaceDataFormatter() .format(data, null, TypeFormatter.Format.EXPANDED, null); assertEquals(Lists.newArrayList("1D", "7D", "14D"), map.get(SurfaceFormatterUtils.X_LABELS)); assertEquals(Lists.newArrayList("1Y", "2Y"), map.get(SurfaceFormatterUtils.Y_LABELS)); assertEquals( Lists.newArrayList(10d, 11d, 12d, 13d, 14d, 15d), map.get(SurfaceFormatterUtils.VOL)); }
@SuppressWarnings("unchecked") @Test public void expandedRagged() { Tenor[] xs = new Tenor[] {Tenor.DAY, Tenor.ONE_WEEK, Tenor.TWO_WEEKS, Tenor.TWO_WEEKS, Tenor.ONE_MONTH}; Tenor[] ys = new Tenor[] { Tenor.ONE_YEAR, Tenor.ONE_YEAR, Tenor.ONE_YEAR, Tenor.TWO_YEARS, Tenor.TWO_YEARS }; double[] vols = new double[] {10, 11, 12, 13, 14}; Map<Pair<Tenor, Tenor>, Double> values = Maps.newHashMap(); for (int i = 0; i < xs.length; i++) { values.put(Pair.of(xs[i], ys[i]), vols[i]); } String name = "test"; UniqueIdentifiable target = Currency.USD; VolatilitySurfaceData<Tenor, Tenor> data = new VolatilitySurfaceData<>(name, name, target, xs, ys, values); Map<String, Object> map = (Map<String, Object>) new VolatilitySurfaceDataFormatter() .format(data, null, TypeFormatter.Format.EXPANDED, null); assertEquals( Lists.newArrayList("1D", "7D", "14D", "1M"), map.get(SurfaceFormatterUtils.X_LABELS)); assertEquals(Lists.newArrayList("1Y", "2Y"), map.get(SurfaceFormatterUtils.Y_LABELS)); assertEquals( Lists.newArrayList(10d, 11d, 12d, null, null, null, 13d, 14d), map.get(SurfaceFormatterUtils.VOL)); }
@SuppressWarnings("unchecked") public Pair<ResolveTask[], ResolvedValueProducer[]> getTasksProducing( final ValueSpecification valueSpecification) { do { final MapEx<ResolveTask, ResolvedValueProducer> tasks = getBuilder().getTasks(valueSpecification); if (tasks != null) { final ResolveTask[] resultTasks; final ResolvedValueProducer[] resultProducers; synchronized (tasks) { if (tasks.containsKey(null)) { continue; } if (tasks.isEmpty()) { return null; } resultTasks = new ResolveTask[tasks.size()]; resultProducers = new ResolvedValueProducer[tasks.size()]; int i = 0; for (final Map.Entry<ResolveTask, ResolvedValueProducer> task : (Set<Map.Entry<ResolveTask, ResolvedValueProducer>>) tasks.entrySet()) { // Don't ref-count the tasks; they're just used for parent comparisons resultTasks[i] = task.getKey(); resultProducers[i++] = task.getValue(); task.getValue().addRef(); // We're holding the task lock } } return Pair.of(resultTasks, resultProducers); } else { return null; } } while (true); }
public static String getFormattedStrike( final double strike, final Pair<Currency, Currency> pair) { if (pair.getFirst().compareTo(pair.getSecond()) < 0) { return STRIKE_FORMATTER.format(strike) + " " + pair.getFirst() + "/" + pair.getSecond(); } if (pair.getFirst().compareTo(pair.getSecond()) > 0) { return STRIKE_FORMATTER.format(1. / strike) + " " + pair.getSecond() + "/" + pair.getFirst(); } throw new OpenGammaRuntimeException("Currencies were equal"); }
public static Collection<Pair<ValueSpecification, Object>> getValues( final ViewComputationCache cache, final Collection<ValueSpecification> specifications) { final Collection<Pair<ValueSpecification, Object>> values = new ArrayList<Pair<ValueSpecification, Object>>(specifications.size()); for (ValueSpecification specification : specifications) { values.add(Pair.of(specification, cache.getValue(specification))); } return values; }
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + _ccyPair.hashCode(); result = prime * result + _forwardPoints.hashCode(); result = prime * result + _multicurveProvider.hashCode(); return result; }
protected synchronized InMemoryCompiledFunctionRepository getNextCompilation( final Pair<FunctionRepository, Instant> key) { final Map.Entry<Pair<FunctionRepository, Instant>, InMemoryCompiledFunctionRepository> entry = getCompilationCache().higherEntry(key); if ((entry != null) && (entry.getKey().getFirst() == key.getFirst())) { return entry.getValue(); } return null; }
@Override public synchronized void remove(ObjectIdentifiable objectIdentifiable) { ArgumentChecker.notNull(objectIdentifiable, "objectIdentifiable"); if (!getUniqueIdScheme().equals(objectIdentifiable.getObjectId().getScheme())) { throw new DataNotFoundException( "Scheme '" + objectIdentifiable.getObjectId().getScheme() + "' not valid for '" + getUniqueIdScheme() + "'"); } final int i = objectIdentifiable.getObjectId().getValue().indexOf('_'); if (i <= 0) { throw new DataNotFoundException( "Identifier '" + objectIdentifiable.getObjectId().getValue() + "' not valid for '" + getUniqueIdScheme() + "'"); } final String name = objectIdentifiable.getObjectId().getValue().substring(0, i); final String iso = objectIdentifiable.getObjectId().getValue().substring(i + 1); final Currency currency; try { currency = Currency.of(iso); } catch (IllegalArgumentException e) { throw new DataNotFoundException( "Identifier '" + objectIdentifiable.getObjectId().getValue() + "' not valid for '" + getUniqueIdScheme() + "'", e); } final Pair<Currency, String> key = Pair.of(currency, name); if (_sourceVersionCorrection.getVersionAsOf() != null) { final TreeMap<Instant, YieldCurveDefinition> value = _definitions.get(key); if (value == null) { throw new DataNotFoundException("Curve definition not found"); } // Don't need to keep the old values before the one needed by "versionAsOfInstant" final Instant oldestNeeded = value.floorKey(_sourceVersionCorrection.getVersionAsOf()); if (oldestNeeded != null) { value.headMap(oldestNeeded).clear(); } // Store a null to indicate the delete value.put(Instant.now(), null); } else { if (_definitions.remove(key) == null) { throw new DataNotFoundException("Curve definition not found"); } } changeManager() .entityChanged( ChangeType.REMOVED, objectIdentifiable.getObjectId(), null, null, Instant.now()); }
/** * Computes the fair value strike of a spot starting VarianceSwap parameterized in 'variance' * terms, It is quoted as an annual variance value, hence 1/T * integral(0,T) {sigmaSquared dt} * * <p> * * @param expiry Time from spot until last observation * @param market VarianceSwapDataBundle containing volatility surface, forward underlying, and * funding curve * @param cutoff The cutoff * @return presentValue of the *remaining* variance in the swap. */ protected double impliedVarianceFromSpot( final double expiry, final VarianceSwapDataBundle market, final DoublesPair cutoff) { // 1. Unpack Market data final double fwd = market.getForwardCurve().getForward(expiry); final BlackVolatilitySurface<?> volSurf = market.getVolatilitySurface(); VarianceCalculator varCal; if (cutoff == null) { varCal = new VarianceCalculator(fwd, expiry); } else { final ExtrapolationParameters exParCal = new ExtrapolationParameters(fwd, expiry); final Pair<double[], double[]> pars = exParCal.getparameters(volSurf, cutoff); final double[] ks = pars.getFirst(); final double[] vols = pars.getSecond(); final double res = getResidual(fwd, expiry, ks, vols); varCal = new VarianceCalculator(fwd, expiry, res, ks[0]); } return varCal.getVariance(volSurf); }
/** * @param priority The priority of the functions * @param interpolatorName The volatility surface interpolator name * @param leftExtrapolatorName The volatility surface left extrapolator name * @param rightExtrapolatorName The volatility surface right extrapolator name * @param propertyValuesByCurrencies Values for the properties per currency: an array of strings * where the <i>i<sup>th</sup></i> currency has properties: * <ul> * <li><i>i</i> = first currency name, * <li><i>i + 1</i> = first currency curve configuration name * <li><i>i + 2</i> = first currency discounting curve name * <li><i>i + 3</i> = second currency name, * <li><i>i + 4</i> = second currency curve configuration name * <li><i>i + 5</i> = second currency discounting curve name * <li><i>i + 6</i> = surface name * </ul> */ public FXOptionBlackDefaults( final String priority, final String interpolatorName, final String leftExtrapolatorName, final String rightExtrapolatorName, final String... propertyValuesByCurrencies) { super(ComputationTargetType.SECURITY, true); ArgumentChecker.notNull(priority, "priority"); ArgumentChecker.notNull(interpolatorName, "interpolator name"); ArgumentChecker.notNull(leftExtrapolatorName, "left extrapolator name"); ArgumentChecker.notNull(rightExtrapolatorName, "right extrapolator name"); ArgumentChecker.notNull(propertyValuesByCurrencies, "property values by currency"); ArgumentChecker.isTrue( propertyValuesByCurrencies.length % 7 == 0, "Must have two currencies, one curve config and discounting curve name per currency pair and one surface name"); _priority = PriorityClass.valueOf(priority); _interpolatorName = interpolatorName; _leftExtrapolatorName = leftExtrapolatorName; _rightExtrapolatorName = rightExtrapolatorName; _propertyValuesByFirstCurrency = new HashMap<String, Pair<String, String>>(); _propertyValuesBySecondCurrency = new HashMap<String, Pair<String, String>>(); _surfaceNameByCurrencyPair = new HashMap<Pair<String, String>, String>(); for (int i = 0; i < propertyValuesByCurrencies.length; i += 7) { final String firstCurrency = propertyValuesByCurrencies[i]; final Pair<String, String> firstCurrencyValues = Pair.of(propertyValuesByCurrencies[i + 1], propertyValuesByCurrencies[i + 2]); final String secondCurrency = propertyValuesByCurrencies[i + 3]; ArgumentChecker.isFalse( firstCurrency.equals(secondCurrency), "The two currencies must not be equal; have {} and {}", firstCurrency, secondCurrency); final Pair<String, String> secondCurrencyValues = Pair.of(propertyValuesByCurrencies[i + 4], propertyValuesByCurrencies[i + 5]); final String surfaceName = propertyValuesByCurrencies[i + 6]; _propertyValuesByFirstCurrency.put(firstCurrency, firstCurrencyValues); _propertyValuesBySecondCurrency.put(secondCurrency, secondCurrencyValues); _surfaceNameByCurrencyPair.put(Pair.of(firstCurrency, secondCurrency), surfaceName); } }
@Override public List<UniqueId> replaceAllVersions( ObjectIdentifiable objectIdentifiable, List<YieldCurveDefinitionDocument> replacementDocuments) { ArgumentChecker.notNull(replacementDocuments, "replacementDocuments"); ArgumentChecker.notNull(objectIdentifiable, "objectIdentifiable"); final Instant now = Instant.now(); for (YieldCurveDefinitionDocument replacementDocument : replacementDocuments) { ArgumentChecker.notNull(replacementDocument, "document"); ArgumentChecker.notNull( replacementDocument.getYieldCurveDefinition(), "document.yieldCurveDefinition"); final Currency currency = replacementDocument.getYieldCurveDefinition().getCurrency(); final String name = replacementDocument.getYieldCurveDefinition().getName(); final UniqueId id = UniqueId.of(getUniqueIdScheme(), name + "_" + currency.getCode()); ArgumentChecker.isTrue(id.equals(objectIdentifiable), "Invalid object identifier"); } YieldCurveDefinitionDocument storedDocument = get(objectIdentifiable, null); if (storedDocument == null) { throw new DataNotFoundException("Document not found: " + objectIdentifiable); } final Currency currency = storedDocument.getYieldCurveDefinition().getCurrency(); final String name = storedDocument.getYieldCurveDefinition().getName(); Pair<Currency, String> key = Pair.of(currency, name); final TreeMap<Instant, YieldCurveDefinition> value = _definitions.get(key); if (value == null) { throw new DataNotFoundException("OID '" + objectIdentifiable + "' not found"); } value.clear(); List<YieldCurveDefinitionDocument> orderedReplacementDocuments = MasterUtils.adjustVersionInstants(now, null, null, replacementDocuments); final Instant lowestVersionFrom = orderedReplacementDocuments.get(0).getVersionFromInstant(); ArgumentChecker.notNull( lowestVersionFrom, "You must define version from of the first document"); for (YieldCurveDefinitionDocument replacementDocument : orderedReplacementDocuments) { value.put( replacementDocument.getVersionFromInstant(), replacementDocument.getYieldCurveDefinition()); changeManager() .entityChanged(ChangeType.CHANGED, replacementDocument.getObjectId(), null, null, now); } return MasterUtils.mapToUniqueIDs(orderedReplacementDocuments); }
@Override public ObjectsPair<Collection<LiveDataSpecification>, Collection<LiveDataSpecification>> splitShouldFake( FakeSubscriptionBloombergLiveDataServer server, Collection<LiveDataSpecification> specs) { if (specs.isEmpty()) { return Pair.of( (Collection<LiveDataSpecification>) new ArrayList<LiveDataSpecification>(), (Collection<LiveDataSpecification>) new ArrayList<LiveDataSpecification>()); } Set<LiveDataSpecification> fakes = new HashSet<LiveDataSpecification>(); Set<LiveDataSpecification> underlyings = new HashSet<LiveDataSpecification>(); for (LiveDataSpecification liveDataSpecification : specs) { if (shouldFake(liveDataSpecification)) { fakes.add(liveDataSpecification); } else { underlyings.add(liveDataSpecification); } } return Pair.of( (Collection<LiveDataSpecification>) underlyings, (Collection<LiveDataSpecification>) fakes); }
@Override public YieldCurveDefinition getDefinition( final Currency currency, final String name, final VersionCorrection versionCorrection) { ArgumentChecker.notNull(currency, "currency"); ArgumentChecker.notNull(name, "name"); final TreeMap<Instant, YieldCurveDefinition> definitions = _definitions.get(Pair.of(currency, name)); if (definitions == null) { return null; } final Map.Entry<Instant, YieldCurveDefinition> entry = definitions.floorEntry(versionCorrection.getVersionAsOf()); if (entry == null) { return null; } return entry.getValue(); }
@Override public ComputedValue getComputedValue(final ValueRequirement requirement) { final Pair<String, Object> key = Pair.of( requirement.getValueName(), targetSpecKey(_resolver.getTargetSpecification(requirement.getTargetReference()))); final ComputedValue[] values = _valuesByRequirement.get(key); if (values != null) { for (final ComputedValue value : values) { // Shortcut to check the properties as we already know the name and target match if (requirement.getConstraints().isSatisfiedBy(value.getSpecification().getProperties())) { return value; } } } return null; }