@Override public HistoricalTimeSeries getHistoricalTimeSeries( ExternalIdBundle identifiers, String dataSource, String dataProvider, String dataField, LocalDate start, boolean includeStart, LocalDate end, boolean includeEnd, int maxPoints) { LocalDate resolvedStart = null; if (!includeStart && start != null) { resolvedStart = start.plusDays(1); } else { resolvedStart = start; } LocalDate resolvedEnd = null; if (!includeEnd && end != null) { resolvedEnd = end.minusDays(1); } else { resolvedEnd = end; } return doGetHistoricalTimeSeries( identifiers, dataSource, dataProvider, dataField, resolvedStart, resolvedEnd, maxPoints); }
public void testUpdateTimeSeriesAddNewLaterPointsOnly() { // Add the test series testAddTimeSeries(); List<LocalDate> dates = ImmutableList.of(_today.plusDays(1)); List<Double> values = ImmutableList.of(4d); ArrayLocalDateDoubleTimeSeries newTs = new ArrayLocalDateDoubleTimeSeries(dates, values); UniqueId id = _htsWriter.writeTimeSeries( DESCRIPTION, DATA_SOURCE, DATA_PROVIDER, DATA_FIELD, OBSERVATION_TIME, ExternalIdBundle.of(ID), newTs); ManageableHistoricalTimeSeries manageableTs = _htsMaster.getTimeSeries(id); LocalDateDoubleTimeSeries readTs = manageableTs.getTimeSeries(); List<LocalDate> expectedDates = ImmutableList.of(_today.minusDays(2), _today.minusDays(1), _today, _today.plusDays(1)); List<Double> expectedValues = ImmutableList.of(1d, 2d, 3d, 4d); ArrayLocalDateDoubleTimeSeries expectedTs = new ArrayLocalDateDoubleTimeSeries(expectedDates, expectedValues); assertEquals(expectedTs, readTs); }
@Test public void test() { assertEquals( COUPON * DC.getDayCountFraction(D1, D2), DC.getAccruedInterest(D1, D2, D3, COUPON, PAYMENTS), 0); assertEquals(DC.getConventionName(), "28/360"); final LocalDate d1 = LocalDate.of(2012, 7, 2); final LocalDate d2 = LocalDate.of(2012, 7, 28); final LocalDate d3 = LocalDate.of(2012, 8, 2); final LocalDate d4 = LocalDate.of(2012, 8, 28); final LocalDate d5 = LocalDate.of(2013, 8, 2); final LocalDate d6 = LocalDate.of(2013, 8, 28); final LocalDate d7 = LocalDate.of(2012, 6, 29); final LocalDate d8 = LocalDate.of(2012, 7, 31); final LocalDate d9 = LocalDate.of(2012, 8, 31); final LocalDate d10 = LocalDate.of(2013, 8, 31); assertEquals(26. / 360, DC.getDayCountFraction(d1, d2), 0); assertEquals(28. / 360, DC.getDayCountFraction(d1, d3), 0); assertEquals(54. / 360, DC.getDayCountFraction(d1, d4), 0); assertEquals(1 + 28. / 360, DC.getDayCountFraction(d1, d5), 0); assertEquals(1 + 54. / 360, DC.getDayCountFraction(d1, d6), 0); assertEquals(28. / 360, DC.getDayCountFraction(d7, d2), 0); assertEquals(30. / 360, DC.getDayCountFraction(d7, d3), 0); assertEquals(56. / 360, DC.getDayCountFraction(d7, d4), 0); assertEquals(1 + 30. / 360, DC.getDayCountFraction(d7, d5), 0); assertEquals(1 + 56. / 360, DC.getDayCountFraction(d7, d6), 0); assertEquals(26. / 360, DC.getDayCountFraction(d1, d8), 0); assertEquals(28. / 360, DC.getDayCountFraction(d7, d8), 0); assertEquals(54. / 360, DC.getDayCountFraction(d1, d9), 0); assertEquals(56. / 360, DC.getDayCountFraction(d7, d9), 0); assertEquals(1 + 54. / 360, DC.getDayCountFraction(d1, d10), 0); assertEquals(1 + 56. / 360, DC.getDayCountFraction(d7, d10), 0); }
@Override public Set<ComputedValue> execute( final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues) { final Object positionOrNode = getTarget(target); final ConventionBundleSource conventionSource = OpenGammaExecutionContext.getConventionBundleSource(executionContext); final ConventionBundle bundle = conventionSource.getConventionBundle( ExternalId.of(InMemoryConventionBundleMaster.SIMPLE_NAME_SCHEME, "USD_CAPM")); final Clock snapshotClock = executionContext.getValuationClock(); final LocalDate now = snapshotClock.zonedDateTime().toLocalDate(); final ValueRequirement desiredValue = desiredValues.iterator().next(); final ValueProperties constraints = desiredValue.getConstraints(); final Period samplingPeriod = getSamplingPeriod(constraints.getValues(ValuePropertyNames.SAMPLING_PERIOD)); final LocalDate startDate = now.minus(samplingPeriod); final HistoricalTimeSeries riskFreeRateTSObject = (HistoricalTimeSeries) inputs.getValue(ValueRequirementNames.HISTORICAL_TIME_SERIES); final Object assetPnLObject = inputs.getValue( new ValueRequirement( ValueRequirementNames.PNL_SERIES, positionOrNode)); // TODO replace with return series when portfolio weights are in if (assetPnLObject == null) { throw new OpenGammaRuntimeException("Asset P&L was null"); } final Object assetFairValueObject = inputs.getValue(new ValueRequirement(ValueRequirementNames.FAIR_VALUE, positionOrNode)); if (assetFairValueObject == null) { throw new OpenGammaRuntimeException("Asset fair value was null"); } final Object betaObject = inputs.getValue(new ValueRequirement(ValueRequirementNames.CAPM_BETA, positionOrNode)); if (betaObject == null) { throw new OpenGammaRuntimeException("Beta was null"); } final double beta = (Double) betaObject; final double fairValue = (Double) assetFairValueObject; DoubleTimeSeries<?> assetReturnTS = ((DoubleTimeSeries<?>) assetPnLObject).divide(fairValue); DoubleTimeSeries<?> riskFreeReturnTS = riskFreeRateTSObject.getTimeSeries().divide(100 * DAYS_PER_YEAR); DoubleTimeSeries<?>[] series = TimeSeriesIntersector.intersect(riskFreeReturnTS, assetReturnTS); riskFreeReturnTS = series[0]; assetReturnTS = series[1]; final TreynorRatioCalculator calculator = getCalculator(constraints.getValues(ValuePropertyNames.EXCESS_RETURN_CALCULATOR)); final double ratio = calculator.evaluate(assetReturnTS, riskFreeReturnTS, beta); final ValueProperties resultProperties = getResultProperties(desiredValues.iterator().next()); return Sets.newHashSet( new ComputedValue( new ValueSpecification( new ValueRequirement( ValueRequirementNames.TREYNOR_RATIO, positionOrNode, resultProperties), getUniqueId()), ratio)); }
/** * Checks if the identifier is valid on the specified date. * * @param date the date to check for validity on, null returns true * @return true if valid on the specified date */ public boolean isValidOn(LocalDate date) { if (date == null) { return true; } LocalDate from = Objects.firstNonNull( getValidFrom(), LocalDate.of(Year.MIN_YEAR, 1, 1)); // TODO: JSR-310 far past/future LocalDate to = Objects.firstNonNull(getValidTo(), LocalDate.of(Year.MAX_YEAR, 12, 31)); return date.isBefore(from) == false && date.isAfter(to) == false; }
/** * Returns the identifier in the form {@code <SCHEME>~<VALUE>~S~<VALID_FROM>~E~<VALID_TO>}. * * @return the identifier, not null */ @Override public String toString() { StringBuilder buf = new StringBuilder(_identifier.toString()); if (_validFrom != null) { buf.append("~S~").append(_validFrom.toString()); } if (_validTo != null) { buf.append("~E~").append(_validTo.toString()); } return buf.toString(); }
/** * Creates an instance. * * @param identifier the identifier, not null * @param validFrom the valid from date, may be null * @param validTo the valid to date, may be null */ private ExternalIdWithDates(ExternalId identifier, LocalDate validFrom, LocalDate validTo) { ArgumentChecker.notNull(identifier, "identifier"); if (validFrom != null && validTo != null) { ArgumentChecker.isTrue( validTo.isAfter(validFrom) || validTo.equals(validFrom), "ValidTo must be after or eqauls to ValidFrom"); } _identifier = identifier; _validFrom = validFrom; _validTo = validTo; }
@Test public void testStartAndEndSame1() { final LocalDate date = LocalDate.of(2001, 2, 13); final LocalDate[] dates = CALCULATOR.getSchedule(date, date, true, false); assertEquals(dates.length, 1); assertEquals(dates[0], date); }
private void processFieldData( Element securityElem, String field, Map<String, ExternalIdBundle> bbgSecDomainMap, Map<ExternalIdBundle, HistoricalTimeSeries> result) { String secDes = securityElem.getElementAsString(BloombergConstants.SECURITY); ExternalIdBundle identifiers = bbgSecDomainMap.get(secDes); if (identifiers == null) { String message = "Found time series data for unrecognized security" + secDes + " " + bbgSecDomainMap; throw new OpenGammaRuntimeException(message); } HistoricalTimeSeries hts = result.get(identifiers); MapLocalDateDoubleTimeSeries timeSeries; if (hts == null) { timeSeries = new MapLocalDateDoubleTimeSeries(); hts = new SimpleHistoricalTimeSeries(UID_SUPPLIER.get(), timeSeries); result.put(identifiers, hts); } else { timeSeries = (MapLocalDateDoubleTimeSeries) hts.getTimeSeries(); } Element fieldDataArray = securityElem.getElement(FIELD_DATA); int numValues = fieldDataArray.numValues(); for (int i = 0; i < numValues; i++) { Element fieldData = fieldDataArray.getValueAsElement(i); Datetime date = fieldData.getElementAsDate("date"); double lastPrice = fieldData.getElementAsFloat64(field); int year = date.year(); int month = date.month(); int day = date.dayOfMonth(); timeSeries.putDataPoint(LocalDate.of(year, month, day), lastPrice); } }
@Test public void test1() { LocalDate startDate = LocalDate.of(2000, 1, 1); LocalDate endDate = LocalDate.of(2000, 12, 30); LocalDate[] forward = CALCULATOR.getSchedule(startDate, endDate, false, true); assertEquals(forward.length, 1); assertEquals(forward[0], startDate); assertArrayEquals(forward, CALCULATOR.getSchedule(startDate, endDate, true, true)); assertArrayEquals(forward, CALCULATOR.getSchedule(startDate, endDate, false, false)); assertArrayEquals(forward, CALCULATOR.getSchedule(startDate, endDate, true, false)); startDate = LocalDate.of(2000, 1, 2); endDate = LocalDate.of(2000, 12, 30); forward = CALCULATOR.getSchedule(startDate, endDate, false, true); assertEquals(forward.length, 0); assertArrayEquals(forward, CALCULATOR.getSchedule(startDate, endDate, true, true)); assertArrayEquals(forward, CALCULATOR.getSchedule(startDate, endDate, false, false)); assertArrayEquals(forward, CALCULATOR.getSchedule(startDate, endDate, true, false)); startDate = LocalDate.of(2002, 2, 2); endDate = LocalDate.of(2003, 2, 9); forward = CALCULATOR.getSchedule(startDate, endDate, false, true); assertEquals(forward.length, 1); assertEquals(forward[0], LocalDate.of(2003, 1, 1)); assertArrayEquals(forward, CALCULATOR.getSchedule(startDate, endDate, true, true)); assertArrayEquals(forward, CALCULATOR.getSchedule(startDate, endDate, false, false)); assertArrayEquals(forward, CALCULATOR.getSchedule(startDate, endDate, true, false)); startDate = LocalDate.of(2000, 1, 1); endDate = LocalDate.of(2010, 2, 9); final int months = 11; forward = CALCULATOR.getSchedule(startDate, endDate, false, true); assertEquals(forward.length, months); assertEquals(forward[0], startDate); assertArrayEquals(forward, CALCULATOR.getSchedule(startDate, endDate, true, true)); assertArrayEquals(forward, CALCULATOR.getSchedule(startDate, endDate, false, false)); assertArrayEquals(forward, CALCULATOR.getSchedule(startDate, endDate, true, false)); final LocalDate lastDate = LocalDate.of(2010, 1, 1); assertEquals(forward[months - 1], lastDate); for (int i = 1; i < months; i++) { if (forward[i].getYear() == forward[i - 1].getYear()) { assertEquals(forward[i].getYear() - forward[i - 1].getYear(), 1); assertEquals(forward[i].getMonthOfYear().getValue(), 1); assertEquals(forward[i].getDayOfMonth(), 1); } } assertArrayEquals(forward, CALCULATOR.getSchedule(startDate, endDate, true, true)); assertArrayEquals(forward, CALCULATOR.getSchedule(startDate, endDate, false, false)); assertArrayEquals(forward, CALCULATOR.getSchedule(startDate, endDate, true, false)); }
public class BloombergEquityFutureOptionVolatilitySurfaceInstrumentProviderTest { private static final String PREFIX = "DJX"; private static final String POSTFIX = "Index"; private static final LocalDate DATE = LocalDate.of(2012, 5, 23); private static final Short[] EXPIRY_OFFSETS = new Short[] {1, 2, 8}; private static final Double[] STRIKES = new Double[] {90.0, 145.0, 205.0}; private static final String DATA_FIELD_NAME = "OPT_IMPLIED_VOLATILITY_MID"; private static final String[][] RESULTS = new String[][] { new String[] { "DJX 06/16/12 P90.0 Index", "DJX 06/16/12 P145.0 Index", "DJX 06/16/12 C205.0 Index" }, new String[] { "DJX 07/21/12 P90.0 Index", "DJX 07/21/12 P145.0 Index", "DJX 07/21/12 C205.0 Index" }, new String[] { "DJX 03/16/13 P90.0 Index", "DJX 03/16/13 P145.0 Index", "DJX 03/16/13 C205.0 Index" } }; // TODO Fix date on this last one private static final FutureOptionExpiries UTILS = FutureOptionExpiries.of(new NextExpiryAdjuster(3, DayOfWeek.FRIDAY, 1)); private static LocalDate[] EXPIRY_DATES = new LocalDate[3]; private static final String EXCHANGE = "OSE"; static { for (int i = 0; i < EXPIRY_OFFSETS.length; i++) { EXPIRY_DATES[i] = FutureOptionExpiries.EQUITY.getFutureOptionExpiry(EXPIRY_OFFSETS[i], DATE); } } private static final BloombergEquityFutureOptionVolatilitySurfaceInstrumentProvider PROVIDER = new BloombergEquityFutureOptionVolatilitySurfaceInstrumentProvider( PREFIX, POSTFIX, DATA_FIELD_NAME, 150.25, EXCHANGE); @Test public void test() { for (int i = 0; i < EXPIRY_OFFSETS.length; i++) { for (int j = 0; j < STRIKES.length; j++) { final String expected = RESULTS[i][j]; final ExternalId actual = PROVIDER.getInstrument(EXPIRY_OFFSETS[i], STRIKES[j], DATE); assertEquals(ExternalSchemes.BLOOMBERG_TICKER_WEAK, actual.getScheme()); assertEquals(expected, actual.getValue()); } } } @Test public void testUtils() { assertEquals(EXPIRY_DATES[0], FutureOptionExpiries.EQUITY.getMonthlyExpiry(1, DATE)); assertEquals(EXPIRY_DATES[1], FutureOptionExpiries.EQUITY.getMonthlyExpiry(2, DATE)); assertEquals( EXPIRY_DATES[2], FutureOptionExpiries.EQUITY.getQuarterlyExpiry( EXPIRY_OFFSETS[2] - 6, UTILS.getMonthlyExpiry(6, DATE))); } }
public void testAddTimeSeries() { List<LocalDate> dates = ImmutableList.of(_today.minusDays(2), _today.minusDays(1), _today); List<Double> values = ImmutableList.of(1d, 2d, 3d); ArrayLocalDateDoubleTimeSeries origTs = new ArrayLocalDateDoubleTimeSeries(dates, values); UniqueId id = _htsWriter.writeTimeSeries( DESCRIPTION, DATA_SOURCE, DATA_PROVIDER, DATA_FIELD, OBSERVATION_TIME, ExternalIdBundle.of(ID), origTs); ManageableHistoricalTimeSeries manageableTs = _htsMaster.getTimeSeries(id); LocalDateDoubleTimeSeries readTs = manageableTs.getTimeSeries(); assertEquals(origTs, readTs); }
public void test() { ManageableTrade obj = new ManageableTrade(); obj.setUniqueId(UniqueId.of("U", "1")); obj.setQuantity(BigDecimal.ONE); obj.setSecurityLink(new ManageableSecurityLink(ExternalId.of("A", "B"))); obj.getSecurityLink().setObjectId(ObjectId.of("O", "1")); obj.setTradeDate(LocalDate.of(2011, 6, 1)); obj.setCounterpartyExternalId(ExternalId.of("C", "D")); testFudgeMessage(obj); }
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + _convention.hashCode(); result = prime * result + Arrays.hashCode(_conversionFactors); result = prime * result + Arrays.hashCode(_deliverableBonds); result = prime * result + _deliveryDate.hashCode(); return result; }
private HistoricalTimeSeries getAllowedRecentPoints( HistoricalTimeSeriesInfoDocument timeSeriesInfo) { LocalDate from = oldestTimeSeriesAllowed(); HistoricalTimeSeries timeSeries = getToolContext() .getHistoricalTimeSeriesSource() .getHistoricalTimeSeries( timeSeriesInfo.getUniqueId().toLatest(), from, true, LocalDate.now(), true); return timeSeries; }
@Override public void convertValue( final ValueConversionContext conversionContext, final Object value, final JavaTypeInfo<?> type) { if ((value == null) && type.isAllowNull()) { conversionContext.setResult(null); return; } final Class<?> clazz = type.getRawClass(); if (clazz == Value.class) { if (value instanceof LocalDate) { conversionContext.setResult(ValueUtils.of(((LocalDate) value).toString())); } else if (value instanceof InstantProvider) { conversionContext.setResult( ValueUtils.of((double) ((InstantProvider) value).toInstant().getEpochSeconds())); } else { conversionContext.setFail(); } } else if (clazz == LocalDate.class) { final String str = ((Value) value).getStringValue(); if (str != null) { try { conversionContext.setResult(LocalDate.parse(str)); } catch (CalendricalException e) { conversionContext.setFail(); } } else { conversionContext.setFail(); } } else if (clazz == Instant.class) { final Double epochSeconds = ((Value) value).getDoubleValue(); if (epochSeconds != null) { conversionContext.setResult(Instant.ofEpochSeconds(epochSeconds.longValue())); } else { conversionContext.setFail(); } } else if (clazz == ZonedDateTime.class) { final ZonedDateTime zdt = valueToZonedDateTime((Value) value); if (zdt != null) { conversionContext.setResult(zdt); } else { conversionContext.setFail(); } } else if (clazz == Expiry.class) { final ZonedDateTime zdt = valueToZonedDateTime((Value) value); if (zdt != null) { conversionContext.setResult(new Expiry(zdt)); } else { conversionContext.setFail(); } } else { conversionContext.setFail(); } }
@Test public void testRecursive1() { LocalDate startDate = LocalDate.of(2000, 1, 1); LocalDate endDate = LocalDate.of(2000, 1, 30); LocalDate[] forward = CALCULATOR.getSchedule(startDate, endDate, false, true); LocalDate[] backward = CALCULATOR.getSchedule(startDate, endDate, true, true); assertEquals(forward.length, 1); assertEquals(backward.length, 1); assertEquals(forward[0], startDate); assertEquals(backward[0], endDate); startDate = LocalDate.of(2002, 2, 1); endDate = LocalDate.of(2002, 2, 9); forward = CALCULATOR.getSchedule(startDate, endDate, false, true); backward = CALCULATOR.getSchedule(startDate, endDate, true, true); assertEquals(forward.length, 1); assertEquals(backward.length, 1); assertEquals(forward[0], startDate); assertEquals(backward[0], endDate); startDate = LocalDate.of(2000, 1, 1); endDate = LocalDate.of(2002, 2, 9); final int months = 26; forward = CALCULATOR.getSchedule(startDate, endDate, false, true); backward = CALCULATOR.getSchedule(startDate, endDate, true, true); assertEquals(forward.length, months); assertEquals(backward.length, months); assertEquals(forward[0], startDate); assertEquals(backward[0], LocalDate.of(2000, 1, 9)); assertEquals(forward[months - 1], LocalDate.of(2002, 2, 1)); assertEquals(backward[months - 1], endDate); for (int i = 1; i < months; i++) { if (forward[i].getYear() == forward[i - 1].getYear()) { assertEquals( forward[i].getMonthOfYear().getValue() - forward[i - 1].getMonthOfYear().getValue(), 1); assertEquals( backward[i].getMonthOfYear().getValue() - backward[i - 1].getMonthOfYear().getValue(), 1); } else { assertEquals( forward[i].getMonthOfYear().getValue() - forward[i - 1].getMonthOfYear().getValue(), -11); assertEquals( backward[i].getMonthOfYear().getValue() - backward[i - 1].getMonthOfYear().getValue(), -11); } assertEquals(forward[i].getDayOfMonth(), 1); assertEquals(backward[i].getDayOfMonth(), 9); } }
/** * Parses an {@code ExternalIdWithDates} from a formatted scheme and value. * * <p>This parses the identifier from the form produced by {@code toString()} which is {@code * <SCHEME>~<VALUE>~S~<VALID_FROM>~E~<VALID_TO>}. * * @param str the identifier to parse, not null * @return the identifier, not null * @throws IllegalArgumentException if the identifier cannot be parsed */ public static ExternalIdWithDates parse(String str) { ArgumentChecker.notNull(str, "parse string"); ExternalId identifier = null; LocalDate validFrom = null; LocalDate validTo = null; int startPos = str.indexOf("~S~"); int endPos = str.indexOf("~E~"); if (startPos > 0) { identifier = ExternalId.parse(str.substring(0, startPos)); if (endPos > 0) { validFrom = LocalDate.parse(str.substring(startPos + 3, endPos)); validTo = LocalDate.parse(str.substring(endPos + 3)); } else { validFrom = LocalDate.parse(str.substring(startPos + 3)); } } else if (endPos > 0) { identifier = ExternalId.parse(str.substring(0, endPos)); validTo = LocalDate.parse(str.substring(endPos + 3)); } else { identifier = ExternalId.parse(str); } return new ExternalIdWithDates(identifier, validFrom, validTo); }
protected void processFieldData( final Element fieldDataArray, String field, final List<LocalDate> dates, final List<Double> values) { int numValues = fieldDataArray.numValues(); for (int i = 0; i < numValues; i++) { Element fieldData = fieldDataArray.getValueAsElement(i); Datetime date = fieldData.getElementAsDate("date"); double fieldValue = fieldData.getElementAsFloat64(field); dates.add(LocalDate.of(date.year(), date.month(), date.dayOfMonth())); values.add(fieldValue); } }
private HistoricalTimeSeriesInfoDocument loadTimeSeries(ExternalIdBundle idBundle) { ReferenceDataProvider referenceDataProvider = ((BloombergToolContext) getToolContext()).getBloombergReferenceDataProvider(); if (idBundle.getExternalId(ExternalSchemes.BLOOMBERG_BUID) == null && idBundle.getExternalId(ExternalSchemes.BLOOMBERG_TICKER) != null) { // For some reason loading some series by TICKER fails, but BUID works BiMap<String, ExternalIdBundle> map = BloombergDataUtils.convertToBloombergBuidKeys( Collections.singleton(idBundle), referenceDataProvider); if (map.size() != 1) { throw new OpenGammaRuntimeException("Failed to get buid"); } for (String key : map.keySet()) { ReferenceDataResult buidResult = referenceDataProvider.getFields( Collections.singleton(key), Collections.singleton(BloombergConstants.FIELD_ID_BBG_UNIQUE)); String buid = buidResult .getResult(key) .getFieldData() .getString(BloombergConstants.FIELD_ID_BBG_UNIQUE); idBundle = idBundle.withExternalId(ExternalSchemes.bloombergTickerSecurityId(buid)); } } ExternalIdBundle searchBundle = idBundle.withoutScheme( ExternalSchemes .ISIN); // For things which move country, e.g. ISIN(VALE5 BZ Equity) == ISIN(RIODF // US Equity) Map<ExternalId, UniqueId> timeSeries = getToolContext() .getHistoricalTimeSeriesLoader() .addTimeSeries( searchBundle.getExternalIds(), "CMPL", "PX_LAST", LocalDate.now().minusYears(1), null); if (timeSeries.size() != 1) { throw new OpenGammaRuntimeException( "Failed to load time series " + idBundle + " " + timeSeries); } for (UniqueId uid : timeSeries.values()) { return getToolContext().getHistoricalTimeSeriesMaster().get(uid); } throw new OpenGammaRuntimeException("Unexpected state"); }
private static ZonedDateTime valueToZonedDateTime(final Value v) { final Double epochSeconds = v.getDoubleValue(); if (epochSeconds != null) { return ZonedDateTime.ofEpochSeconds(epochSeconds.longValue(), TimeZone.UTC); } else { final String dateTime = v.getStringValue(); if (dateTime != null) { try { return ZonedDateTime.parse(dateTime); } catch (CalendricalException e) { // Ignore } try { return ZonedDateTime.of(LocalDate.parse(dateTime), LocalTime.MIDDAY, TimeZone.UTC); } catch (CalendricalException e) { // Ignore } } } return null; }
@Test(enabled = false) // Current implementation does not support removing points public void testUpdateTimeSeriesRemoveExistingPoints() { // Add the test series testAddTimeSeries(); List<LocalDate> dates = ImmutableList.of(_today.minusDays(2), _today); List<Double> values = ImmutableList.of(6d, 7d); ArrayLocalDateDoubleTimeSeries updatedTs = new ArrayLocalDateDoubleTimeSeries(dates, values); UniqueId id = _htsWriter.writeTimeSeries( DESCRIPTION, DATA_SOURCE, DATA_PROVIDER, DATA_FIELD, OBSERVATION_TIME, ExternalIdBundle.of(ID), updatedTs); ManageableHistoricalTimeSeries manageableTs = _htsMaster.getTimeSeries(id); LocalDateDoubleTimeSeries readTs = manageableTs.getTimeSeries(); assertEquals(updatedTs, readTs); }
private HistoricalTimeSeries doGetHistoricalTimeSeries( ExternalIdBundle identifiers, String dataSource, String dataProvider, String field, LocalDate startDate, LocalDate endDate, Integer maxPoints) { ArgumentChecker.notNull(identifiers, "identifiers"); ArgumentChecker.notNull(field, "field"); ArgumentChecker.notNull(startDate, "startDate"); ArgumentChecker.notNull(endDate, "endDate"); Validate.isTrue( ObjectUtils.equals(dataSource, BLOOMBERG_DATA_SOURCE_NAME), getClass().getName() + "cannot support " + dataSource); if (maxPoints != null && maxPoints > 0) { throw new UnsupportedOperationException( "Fetching a bounded number of points from the start of a Bloomberg time-series is unsupported"); } s_logger.info("Getting HistoricalTimeSeries for security {}", identifiers); ensureStarted(); if (endDate.isBefore(startDate)) { throw new IllegalArgumentException("endDate must be after startDate"); } ExternalId dsid = BloombergDomainIdentifierResolver.resolvePreferredIdentifier(identifiers); String bbgKey = BloombergDomainIdentifierResolver.toBloombergKeyWithDataProvider(dsid, dataProvider); Request request = composeRequest(bbgKey, dataSource, dataProvider, field, startDate, endDate, maxPoints); _statistics.gotFields(Collections.singleton(bbgKey), Collections.singleton(field)); LocalDateDoubleTimeSeries timeSeries = processRequest(bbgKey, request, field); return new SimpleHistoricalTimeSeries(UID_SUPPLIER.get(), timeSeries); }
@BeforeMethod public void setup() { _htsMaster = new InMemoryHistoricalTimeSeriesMaster(); _htsWriter = new HistoricalTimeSeriesMasterUtils(_htsMaster); _today = LocalDate.now(); }
private LocalDate oldestTimeSeriesAllowed() { return LocalDate.now().minusWeeks(1); }
private LocalDate getRandomTradeDate(ExternalId ticker) { int tradeAge = (int) (3 + (Math.random() * 30)); LocalDate tradeDate = LocalDate.now().minusDays(tradeAge); // TODO: pick a date for which PX_LAST is known return tradeDate; }
private void spreadOptions( ManageablePortfolioNode bucketNode, Collection<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> options, OptionType type, int scale, Set<ExternalId> tickersToLoad, BigDecimal underlyingAmount, boolean includeUnderlying, int targetNumber) { if (targetNumber == 0) { return; } Collection<BloombergTickerParserEQOption> chosen = new ArrayList<BloombergTickerParserEQOption>(); int remaining = targetNumber; for (Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair : options) { BloombergTickerParserEQOption option; if (type == OptionType.PUT) { option = pair.getSecond(); } else { option = pair.getFirst(); } // TODO [LAPANA-29] Should be able to do this for index options too if (includeUnderlying) { try { HistoricalTimeSeriesInfoDocument loadedTs = getOrLoadTimeSeries(option.getIdentifier()); HistoricalTimeSeries ts = getToolContext() .getHistoricalTimeSeriesSource() .getHistoricalTimeSeries( loadedTs.getUniqueId(), LocalDate.now().minusWeeks(1), true, LocalDate.now(), true); if (ts.getTimeSeries().isEmpty()) { s_logger.info("No recent time series points for " + option.getIdentifier()); // leave in for now // continue; //This option is not liquid enough for us } } catch (Exception ex) { s_logger.warn("Failed to get time series for " + option.getIdentifier(), ex); // TODO: stop refetching this series each time continue; // This option is not liquid enough for us } } chosen.add(option); remaining--; if (remaining == 0) { break; } } if (chosen.size() == 0) { s_logger.warn("Couldn't find any liquid " + type + " options from " + options); return; // TODO: should we try another expiry? } for (BloombergTickerParserEQOption option : chosen) { tickersToLoad.add(option.getIdentifier()); addPosition( bucketNode, BigDecimal.valueOf(scale).multiply(_numContracts), option.getIdentifier()); } }
private void addNodes( ManageablePortfolioNode rootNode, String underlying, boolean includeUnderlying, Period[] expiries) { ExternalId ticker = ExternalSchemes.bloombergTickerSecurityId(underlying); ManageableSecurity underlyingSecurity = null; if (includeUnderlying) { underlyingSecurity = getOrLoadEquity(ticker); } ExternalIdBundle bundle = underlyingSecurity == null ? ExternalIdBundle.of(ticker) : underlyingSecurity.getExternalIdBundle(); HistoricalTimeSeriesInfoDocument timeSeriesInfo = getOrLoadTimeSeries(ticker, bundle); double estimatedCurrentStrike = getOrLoadMostRecentPoint(timeSeriesInfo); Set<ExternalId> optionChain = getOptionChain(ticker); // TODO: reuse positions/nodes? String longName = underlyingSecurity == null ? "" : underlyingSecurity.getName(); String formattedName = MessageFormatter.format("[{}] {}", underlying, longName); ManageablePortfolioNode equityNode = new ManageablePortfolioNode(formattedName); BigDecimal underlyingAmount = VALUE_OF_UNDERLYING.divide( BigDecimal.valueOf(estimatedCurrentStrike), BigDecimal.ROUND_HALF_EVEN); if (includeUnderlying) { addPosition(equityNode, underlyingAmount, ticker); } TreeMap<LocalDate, Set<BloombergTickerParserEQOption>> optionsByExpiry = new TreeMap<LocalDate, Set<BloombergTickerParserEQOption>>(); for (ExternalId optionTicker : optionChain) { s_logger.debug("Got option {}", optionTicker); BloombergTickerParserEQOption optionInfo = BloombergTickerParserEQOption.getOptionParser(optionTicker); s_logger.debug("Got option info {}", optionInfo); LocalDate key = optionInfo.getExpiry(); Set<BloombergTickerParserEQOption> set = optionsByExpiry.get(key); if (set == null) { set = new HashSet<BloombergTickerParserEQOption>(); optionsByExpiry.put(key, set); } set.add(optionInfo); } Set<ExternalId> tickersToLoad = new HashSet<ExternalId>(); BigDecimal expiryCount = BigDecimal.valueOf(expiries.length); BigDecimal defaultAmountAtExpiry = underlyingAmount.divide(expiryCount, BigDecimal.ROUND_DOWN); BigDecimal spareAmountAtExpiry = defaultAmountAtExpiry.add(BigDecimal.ONE); int spareCount = underlyingAmount.subtract(defaultAmountAtExpiry.multiply(expiryCount)).intValue(); for (int i = 0; i < expiries.length; i++) { Period bucketPeriod = expiries[i]; ManageablePortfolioNode bucketNode = new ManageablePortfolioNode(bucketPeriod.toString().substring(1)); LocalDate nowish = LocalDate.now() .withDayOfMonth( 20); // This avoids us picking different options every time this script is run LocalDate targetExpiry = nowish.plus(bucketPeriod); LocalDate chosenExpiry = optionsByExpiry.floorKey(targetExpiry); if (chosenExpiry == null) { s_logger.warn("No options for {} on {}", targetExpiry, underlying); continue; } s_logger.info( "Using time {} for bucket {} ({})", new Object[] {chosenExpiry, bucketPeriod, targetExpiry}); Set<BloombergTickerParserEQOption> optionsAtExpiry = optionsByExpiry.get(chosenExpiry); TreeMap<Double, Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> optionsByStrike = new TreeMap< Double, Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>(); for (BloombergTickerParserEQOption option : optionsAtExpiry) { // s_logger.info("option {}", option); double key = option.getStrike(); Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike.get(key); if (pair == null) { pair = Pair.of(null, null); } if (option.getOptionType() == OptionType.CALL) { pair = Pair.of(option, pair.getSecond()); } else { pair = Pair.of(pair.getFirst(), option); } optionsByStrike.put(key, pair); } // cascading collar? BigDecimal amountAtExpiry = spareCount-- > 0 ? spareAmountAtExpiry : defaultAmountAtExpiry; s_logger.info(" est strike {}", estimatedCurrentStrike); Double[] strikes = optionsByStrike.keySet().toArray(new Double[0]); int strikeIndex = Arrays.binarySearch(strikes, estimatedCurrentStrike); if (strikeIndex < 0) { strikeIndex = -(1 + strikeIndex); } s_logger.info( "strikes length {} index {} strike of index {}", new Object[] { Integer.valueOf(strikes.length), Integer.valueOf(strikeIndex), Double.valueOf(strikes[strikeIndex]) }); int minIndex = strikeIndex - _numOptions; minIndex = Math.max(0, minIndex); int maxIndex = strikeIndex + _numOptions; maxIndex = Math.min(strikes.length - 1, maxIndex); s_logger.info("min {} max {}", Integer.valueOf(minIndex), Integer.valueOf(maxIndex)); StringBuffer sb = new StringBuffer("strikes: ["); for (int j = minIndex; j <= maxIndex; j++) { sb.append(" "); sb.append(strikes[j]); } sb.append(" ]"); s_logger.info(sb.toString()); // Short Calls ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> calls = new ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>(); for (int j = minIndex; j < strikeIndex; j++) { Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike.get(strikes[j]); if (pair == null) { throw new OpenGammaRuntimeException("no pair for strike" + strikes[j]); } calls.add(pair); } spreadOptions( bucketNode, calls, OptionType.CALL, -1, tickersToLoad, amountAtExpiry, includeUnderlying, calls.size()); // Long Puts ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> puts = new ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>(); for (int j = strikeIndex + 1; j <= maxIndex; j++) { Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike.get(strikes[j]); if (pair == null) { throw new OpenGammaRuntimeException("no pair for strike" + strikes[j]); } puts.add(pair); } spreadOptions( bucketNode, puts, OptionType.PUT, 1, tickersToLoad, amountAtExpiry, includeUnderlying, puts.size()); if (bucketNode.getChildNodes().size() + bucketNode.getPositionIds().size() > 0) { equityNode.addChildNode(bucketNode); // Avoid generating empty nodes } } for (ExternalId optionTicker : tickersToLoad) { ManageableSecurity loaded = getOrLoadSecurity(optionTicker); if (loaded == null) { throw new OpenGammaRuntimeException("Unexpected option type " + loaded); } // TODO [LAPANA-29] Should be able to do this for index options too if (includeUnderlying) { try { HistoricalTimeSeriesInfoDocument loadedTs = getOrLoadTimeSeries(optionTicker, loaded.getExternalIdBundle()); if (loadedTs == null) { throw new OpenGammaRuntimeException("Failed to get time series for " + loaded); } } catch (Exception ex) { s_logger.error("Failed to get time series for " + loaded, ex); } } } if (equityNode.getPositionIds().size() + equityNode.getChildNodes().size() > 0) { rootNode.addChildNode(equityNode); } }
/** Tests related to the construction of interest rate future security. */ public class InterestRateFutureSecurityTest { // EURIBOR 3M Index private static final Period TENOR = Period.ofMonths(3); private static final int SETTLEMENT_DAYS = 2; private static final Calendar CALENDAR = new MondayToFridayCalendar("A"); private static final DayCount DAY_COUNT_INDEX = DayCountFactory.INSTANCE.getDayCount("Actual/360"); private static final BusinessDayConvention BUSINESS_DAY = BusinessDayConventionFactory.INSTANCE.getBusinessDayConvention("Modified Following"); private static final boolean IS_EOM = true; private static final Currency CUR = Currency.EUR; private static final IborIndex IBOR_INDEX = new IborIndex(CUR, TENOR, SETTLEMENT_DAYS, CALENDAR, DAY_COUNT_INDEX, BUSINESS_DAY, IS_EOM); // Future private static final ZonedDateTime SPOT_LAST_TRADING_DATE = DateUtil.getUTCDate(2012, 9, 19); private static final ZonedDateTime LAST_TRADING_DATE = ScheduleCalculator.getAdjustedDate(SPOT_LAST_TRADING_DATE, CALENDAR, -SETTLEMENT_DAYS); private static final ZonedDateTime FIXING_END_DATE = ScheduleCalculator.getAdjustedDate( SPOT_LAST_TRADING_DATE, BUSINESS_DAY, CALENDAR, IS_EOM, TENOR); private static final double NOTIONAL = 1000000.0; // 1m private static final double FUTURE_FACTOR = 0.25; private static final String NAME = "ERU2"; // private static final InterestRateFutureSecurityDefinition ERU2 = new // InterestRateFutureSecurityDefinition(LAST_TRADING_DATE, IBOR_INDEX, NOTIONAL, FUTURE_FACTOR, // NAME); private static final LocalDate REFERENCE_DATE = LocalDate.of(2010, 8, 18); private static final DayCount ACT_ACT = DayCountFactory.INSTANCE.getDayCount("Actual/Actual ISDA"); private static final ZonedDateTime REFERENCE_DATE_ZONED = ZonedDateTime.of(LocalDateTime.ofMidnight(REFERENCE_DATE), TimeZone.UTC); private static final double LAST_TRADING_TIME = ACT_ACT.getDayCountFraction(REFERENCE_DATE_ZONED, LAST_TRADING_DATE); private static final double FIXING_START_TIME = ACT_ACT.getDayCountFraction(REFERENCE_DATE_ZONED, SPOT_LAST_TRADING_DATE); private static final double FIXING_END_TIME = ACT_ACT.getDayCountFraction(REFERENCE_DATE_ZONED, FIXING_END_DATE); private static final double FIXING_ACCRUAL = DAY_COUNT_INDEX.getDayCountFraction(SPOT_LAST_TRADING_DATE, FIXING_END_DATE); private static final String DISCOUNTING_CURVE_NAME = "Funding"; private static final String FORWARD_CURVE_NAME = "Forward"; private static final InterestRateFutureSecurity ERU2 = new InterestRateFutureSecurity( LAST_TRADING_TIME, IBOR_INDEX, FIXING_START_TIME, FIXING_END_TIME, FIXING_ACCRUAL, NOTIONAL, FUTURE_FACTOR, NAME, DISCOUNTING_CURVE_NAME, FORWARD_CURVE_NAME); @Test(expectedExceptions = IllegalArgumentException.class) public void testNullIndex() { new InterestRateFutureSecurity( LAST_TRADING_TIME, null, FIXING_START_TIME, FIXING_END_TIME, FIXING_ACCRUAL, NOTIONAL, FUTURE_FACTOR, NAME, DISCOUNTING_CURVE_NAME, FORWARD_CURVE_NAME); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNullName() { new InterestRateFutureSecurity( LAST_TRADING_TIME, IBOR_INDEX, FIXING_START_TIME, FIXING_END_TIME, FIXING_ACCRUAL, NOTIONAL, FUTURE_FACTOR, null, DISCOUNTING_CURVE_NAME, FORWARD_CURVE_NAME); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNullDscCurve() { new InterestRateFutureSecurity( LAST_TRADING_TIME, IBOR_INDEX, FIXING_START_TIME, FIXING_END_TIME, FIXING_ACCRUAL, NOTIONAL, FUTURE_FACTOR, NAME, null, FORWARD_CURVE_NAME); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNullForwardCurve() { new InterestRateFutureSecurity( LAST_TRADING_TIME, IBOR_INDEX, FIXING_START_TIME, FIXING_END_TIME, FIXING_ACCRUAL, NOTIONAL, FUTURE_FACTOR, NAME, DISCOUNTING_CURVE_NAME, null); } @Test public void getter() { assertEquals(LAST_TRADING_TIME, ERU2.getLastTradingTime()); assertEquals(IBOR_INDEX, ERU2.getIborIndex()); assertEquals(NOTIONAL, ERU2.getNotional()); assertEquals(FUTURE_FACTOR, ERU2.getPaymentAccrualFactor()); assertEquals(DISCOUNTING_CURVE_NAME, ERU2.getDiscountingCurveName()); assertEquals(FORWARD_CURVE_NAME, ERU2.getForwardCurveName()); assertEquals(NAME, ERU2.getName()); assertEquals(FIXING_START_TIME, ERU2.getFixingPeriodStartTime()); assertEquals(FIXING_END_TIME, ERU2.getFixingPeriodEndTime()); assertEquals(FIXING_ACCRUAL, ERU2.getFixingPeriodAccrualFactor()); } @Test public void equalHash() { assertTrue(ERU2.equals(ERU2)); InterestRateFutureSecurity other = new InterestRateFutureSecurity( LAST_TRADING_TIME, IBOR_INDEX, FIXING_START_TIME, FIXING_END_TIME, FIXING_ACCRUAL, NOTIONAL, FUTURE_FACTOR, NAME, DISCOUNTING_CURVE_NAME, FORWARD_CURVE_NAME); assertTrue(ERU2.equals(other)); assertTrue(ERU2.hashCode() == other.hashCode()); assertEquals(ERU2.toString(), other.toString()); InterestRateFutureSecurity modifiedFuture; modifiedFuture = new InterestRateFutureSecurity( LAST_TRADING_TIME - 0.01, IBOR_INDEX, FIXING_START_TIME, FIXING_END_TIME, FIXING_ACCRUAL, NOTIONAL, FUTURE_FACTOR, NAME, DISCOUNTING_CURVE_NAME, FORWARD_CURVE_NAME); assertFalse(ERU2.equals(modifiedFuture)); modifiedFuture = new InterestRateFutureSecurity( LAST_TRADING_TIME, IBOR_INDEX, FIXING_START_TIME + 0.01, FIXING_END_TIME, FIXING_ACCRUAL, NOTIONAL, FUTURE_FACTOR, NAME, DISCOUNTING_CURVE_NAME, FORWARD_CURVE_NAME); assertFalse(ERU2.equals(modifiedFuture)); modifiedFuture = new InterestRateFutureSecurity( LAST_TRADING_TIME, IBOR_INDEX, FIXING_START_TIME, FIXING_END_TIME + 0.01, FIXING_ACCRUAL, NOTIONAL, FUTURE_FACTOR, NAME, DISCOUNTING_CURVE_NAME, FORWARD_CURVE_NAME); assertFalse(ERU2.equals(modifiedFuture)); modifiedFuture = new InterestRateFutureSecurity( LAST_TRADING_TIME, IBOR_INDEX, FIXING_START_TIME, FIXING_END_TIME, FIXING_ACCRUAL + 0.01, NOTIONAL, FUTURE_FACTOR, NAME, DISCOUNTING_CURVE_NAME, FORWARD_CURVE_NAME); assertFalse(ERU2.equals(modifiedFuture)); modifiedFuture = new InterestRateFutureSecurity( LAST_TRADING_TIME, IBOR_INDEX, FIXING_START_TIME, FIXING_END_TIME, FIXING_ACCRUAL, NOTIONAL + 1.0, FUTURE_FACTOR, NAME, DISCOUNTING_CURVE_NAME, FORWARD_CURVE_NAME); assertFalse(ERU2.equals(modifiedFuture)); modifiedFuture = new InterestRateFutureSecurity( LAST_TRADING_TIME, IBOR_INDEX, FIXING_START_TIME, FIXING_END_TIME, FIXING_ACCRUAL, NOTIONAL, FUTURE_FACTOR + 0.25, NAME, DISCOUNTING_CURVE_NAME, FORWARD_CURVE_NAME); assertFalse(ERU2.equals(modifiedFuture)); modifiedFuture = new InterestRateFutureSecurity( LAST_TRADING_TIME, IBOR_INDEX, FIXING_START_TIME, FIXING_END_TIME, FIXING_ACCRUAL, NOTIONAL, FUTURE_FACTOR, NAME, DISCOUNTING_CURVE_NAME + "NO", FORWARD_CURVE_NAME); assertFalse(ERU2.equals(modifiedFuture)); modifiedFuture = new InterestRateFutureSecurity( LAST_TRADING_TIME, IBOR_INDEX, FIXING_START_TIME, FIXING_END_TIME, FIXING_ACCRUAL, NOTIONAL, FUTURE_FACTOR, NAME, DISCOUNTING_CURVE_NAME, FORWARD_CURVE_NAME + "NO"); assertFalse(ERU2.equals(modifiedFuture)); modifiedFuture = new InterestRateFutureSecurity( LAST_TRADING_TIME, IBOR_INDEX, FIXING_START_TIME, FIXING_END_TIME, FIXING_ACCRUAL, NOTIONAL, FUTURE_FACTOR, NAME + NAME, DISCOUNTING_CURVE_NAME, FORWARD_CURVE_NAME); assertFalse(ERU2.equals(modifiedFuture)); IborIndex otherIndex = new IborIndex( CUR, TENOR, SETTLEMENT_DAYS, CALENDAR, DAY_COUNT_INDEX, BUSINESS_DAY, !IS_EOM); modifiedFuture = new InterestRateFutureSecurity( LAST_TRADING_TIME, otherIndex, FIXING_START_TIME, FIXING_END_TIME, FIXING_ACCRUAL, NOTIONAL, FUTURE_FACTOR, NAME, DISCOUNTING_CURVE_NAME, FORWARD_CURVE_NAME); assertFalse(ERU2.equals(modifiedFuture)); assertFalse(ERU2.equals(LAST_TRADING_DATE)); assertFalse(ERU2.equals(null)); } }
private HistoricalTimeSeriesInfoDocument loadTimeSeries( HistoricalTimeSeriesInfoDocument timeSeriesInfo) { ExternalIdBundle idBundle = timeSeriesInfo.getInfo().getExternalIdBundle().toBundle(LocalDate.now()); return loadTimeSeries(idBundle); }