Package com.opengamma.core.historicaltimeseries

Examples of com.opengamma.core.historicaltimeseries.HistoricalTimeSeries


  private DoubleTimeSeries<?> getPnLSeries(final RawSecurity security, final SecuritySource secSource, final HistoricalTimeSeriesBundle timeSeries,
      final FunctionInputs inputs, final LocalDate startDate, final LocalDate now, final LocalDate[] schedule, final TimeSeriesSamplingFunction samplingFunction) {
    DoubleTimeSeries<?> pnlSeries = null;
    final List<FactorExposureData> factors = RawSecurityUtils.decodeFactorExposureData(secSource, security);
    for (final FactorExposureData factor : factors) {
      final HistoricalTimeSeries dbNodeTimeSeries = timeSeries.get("PX_LAST", factor.getFactorExternalId());
      if (dbNodeTimeSeries == null || dbNodeTimeSeries.getTimeSeries().size() == 0) {
        //s_logger.warn("Could not identifier / price series pair for " + id + " for " + _resolutionKey + "/PX_LAST");
        //throw new OpenGammaRuntimeException("Could not identifier / price series pair for " + id + " for " + _resolutionKey + "/PX_LAST");
        continue;
      }
      DateDoubleTimeSeries<?> nodeTimeSeries = samplingFunction.getSampledTimeSeries(dbNodeTimeSeries.getTimeSeries(), schedule);
      nodeTimeSeries = DIFFERENCE.evaluate(nodeTimeSeries);
      final Double sensitivity = (Double) inputs.getValue(getSensitivityRequirement(factor.getExposureExternalId()));
      if (sensitivity != null) {
        if (pnlSeries == null) {
          pnlSeries = nodeTimeSeries.multiply(sensitivity / 100d);
View Full Code Here


    if (specification == null) {
      throw new OpenGammaRuntimeException("Couldn't find FX forward curve specification called " + domesticCurveName + " for target " + currencyPair);
    }
    final FXForwardCurveInstrumentProvider provider = specification.getCurveInstrumentProvider();
    final HistoricalTimeSeriesBundle timeSeriesBundle = getTimeSeriesBundle(inputs, ComputationTargetType.UNORDERED_CURRENCY_PAIR.specification(currencyPair), domesticCurveName);
    final HistoricalTimeSeries spotTimeSeries = timeSeriesBundle.get(provider.getMarketDataField(), provider.getSpotInstrument());
    if (spotTimeSeries == null) {
      throw new OpenGammaRuntimeException("Could not get spot FX time series");
    }
    final LocalDateDoubleTimeSeries spotTS = spotTimeSeries.getTimeSeries();
    final Map<LocalDate, YieldAndDiscountCurve> foreignCurves = (Map<LocalDate, YieldAndDiscountCurve>) foreignCurveObject;
    final Map<LocalDate, YieldAndDiscountCurve> domesticCurves = new LinkedHashMap<>();
    final Calendar calendar = CalendarUtils.getCalendar(holidaySource, domesticCurrency, foreignCurrency);
    final ConventionSource conventionSource = OpenGammaExecutionContext.getConventionSource(executionContext);
    final FXSpotConvention fxSpotConvention = (FXSpotConvention) conventionSource.getConvention(ExternalId.of("CONVENTION", "FX Spot"));
    final int spotLag = fxSpotConvention.getSettlementDays();
    final boolean isRegular = specification.isMarketQuoteConvention();
    final ExternalId conventionSettlementRegion = fxSpotConvention.getSettlementRegion();
    for (final Map.Entry<LocalDate, YieldAndDiscountCurve> entry : foreignCurves.entrySet()) {
      final LocalDate valuationDate = entry.getKey();
      final ZonedDateTime valuationDateTime = ZonedDateTime.of(valuationDate, now.toLocalTime(), now.getZone());
      final Double spotValue = spotTS.getValue(valuationDate);
      if (spotValue == null) {
        continue;
      }
      final double spotFX = invertFXQuotes ? 1 / spotValue : spotValue;
      final YieldAndDiscountCurve foreignCurve = entry.getValue();
      final DoubleArrayList marketValues = new DoubleArrayList();
      final DoubleArrayList nodeTimes = new DoubleArrayList();
      final DoubleArrayList initialRatesGuess = new DoubleArrayList();
      final String fullDomesticCurveName = domesticCurveName + "_" + domesticCurrency.getCode();
      final String fullForeignCurveName = foreignCurveName + "_" + foreignCurrency.getCode();
      final List<InstrumentDerivative> derivatives = new ArrayList<>();
      int nInstruments = 0;
      ZonedDateTime spotDate;
      if (spotLag == 0 && conventionSettlementRegion == null) {
        spotDate = valuationDateTime;
      } else {
        spotDate = ScheduleCalculator.getAdjustedDate(valuationDateTime, spotLag, calendar);
      }
      for (final Tenor tenor : definition.getTenors()) {
        final ExternalId identifier = provider.getInstrument(valuationDate, tenor);
        final HistoricalTimeSeries forwardFXTS = timeSeriesBundle.get(provider.getMarketDataField(), identifier);
        if (forwardFXTS == null) {
          throw new OpenGammaRuntimeException("Could not get time series for " + identifier);
        }
        final LocalDateDoubleTimeSeries forwardTS = forwardFXTS.getTimeSeries();
        final ZonedDateTime paymentDate;

        if (spotLag == 0 && conventionSettlementRegion == null) {
          paymentDate = now.plus(tenor.getPeriod()); //This preserves the old behaviour that ignored holidays and settlement days.
        } else {
View Full Code Here

      if (ValueRequirementNames.PNL_SERIES.equals(input.getSpecification().getValueName())) {
        assetPnL = (DoubleTimeSeries<?>) inputs.getValue(ValueRequirementNames.PNL_SERIES); //TODO replace with return series when portfolio weights are in
      } else if (ValueRequirementNames.FAIR_VALUE.equals(input.getSpecification().getValueName())) {
        assetFairValue = (Double) inputs.getValue(ValueRequirementNames.FAIR_VALUE);
      } else if (ValueRequirementNames.HISTORICAL_TIME_SERIES.equals(input.getSpecification().getValueName())) {
        final HistoricalTimeSeries ts = (HistoricalTimeSeries) input.getValue();
        timeSeries.add(input.getSpecification().getProperty(HistoricalTimeSeriesFunctionUtils.DATA_FIELD_PROPERTY), timeSeriesSource.getExternalIdBundle(ts.getUniqueId()), ts);
      }
    }
    final ComputationTargetSpecification targetSpec = target.toSpecification();
    final ConventionBundleSource conventionSource = OpenGammaExecutionContext.getConventionBundleSource(executionContext);
    final ConventionBundle bundle = conventionSource.getConventionBundle(ExternalId.of(InMemoryConventionBundleMaster.SIMPLE_NAME_SCHEME, "USD_CAPM")); //TODO
    final ValueRequirement desiredValue = desiredValues.iterator().next();
    final ValueProperties constraints = desiredValue.getConstraints();
    final HistoricalTimeSeries marketTimeSeries = timeSeries.get(MarketDataRequirementNames.MARKET_VALUE, bundle.getCAPMMarket());
    final HistoricalTimeSeries riskFreeTimeSeries = timeSeries.get(MarketDataRequirementNames.MARKET_VALUE, bundle.getCAPMRiskFreeRate());
    final TimeSeriesReturnCalculator returnCalculator = getReturnCalculator(constraints.getValues(ValuePropertyNames.RETURN_CALCULATOR));
    DoubleTimeSeries<?> marketReturn = returnCalculator.evaluate(marketTimeSeries.getTimeSeries());
    final DoubleTimeSeries<?> riskFreeTS = riskFreeTimeSeries.getTimeSeries().divide(100 * DAYS_IN_YEAR);
    marketReturn = marketReturn.subtract(riskFreeTS);
    DoubleTimeSeries<?> assetReturn = assetPnL.divide(assetFairValue);
    assetReturn = assetReturn.subtract(riskFreeTS);
    assetReturn = assetReturn.intersectionFirstValue(marketReturn);
    marketReturn = marketReturn.intersectionFirstValue(assetReturn);
View Full Code Here

  @Override
  public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues) {
    final ValueRequirement desiredValue = desiredValues.iterator().next();
    BigDecimal tradeValue = null;
    HistoricalTimeSeries htsMarkToMarket = null;
    HistoricalTimeSeries htsCostOfCarry = null;
    final PositionOrTrade trade = target.getPositionOrTrade();
    for (final ComputedValue input : inputs.getAllValues()) {
      if (ValueRequirementNames.VALUE.equals(input.getSpecification().getValueName())) {
        tradeValue = BigDecimal.valueOf((Double) input.getValue());
        if (trade instanceof Trade) {
View Full Code Here

  public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target,
      final Set<ValueRequirement> desiredValues) {
    final ComputationTargetSpecification targetSpec = target.toSpecification();
    final ValueRequirement desiredValue = desiredValues.iterator().next();
    final ValueProperties constraints = desiredValue.getConstraints();
    final HistoricalTimeSeries riskFreeRateTSObject = (HistoricalTimeSeries) inputs.getValue(ValueRequirementNames.HISTORICAL_TIME_SERIES);
    final Object assetPnLObject = inputs.getValue(new ValueRequirement(ValueRequirementNames.PNL_SERIES, targetSpec)); //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, targetSpec));
    if (assetFairValueObject == null) {
      throw new OpenGammaRuntimeException("Asset fair value was null");
    }
    final Object betaObject = inputs.getValue(new ValueRequirement(ValueRequirementNames.CAPM_BETA, targetSpec));
    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);
View Full Code Here

  public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target,
      final Set<ValueRequirement> desiredValues) {
    final ValueRequirement desiredValue = desiredValues.iterator().next();
    final ValueProperties resultProperties = getResultProperties(desiredValue);
    final ValueProperties constraints = desiredValue.getConstraints();
    final HistoricalTimeSeries marketTSObject = (HistoricalTimeSeries) inputs.getValue(ValueRequirementNames.HISTORICAL_TIME_SERIES);
    final DoubleTimeSeries<?> assetPnL = (DoubleTimeSeries<?>) inputs.getValue(ValueRequirementNames.PNL_SERIES);
    final double fairValue = (Double) inputs.getValue(ValueRequirementNames.FAIR_VALUE);
    final TimeSeriesReturnCalculator returnCalculator = getReturnCalculator(constraints.getValues(ValuePropertyNames.RETURN_CALCULATOR));
    DoubleTimeSeries<?> marketReturn = returnCalculator.evaluate(marketTSObject.getTimeSeries());
    DoubleTimeSeries<?> assetReturn = assetPnL.divide(fairValue);
    DoubleTimeSeries<?>[] series = TimeSeriesIntersector.intersect(assetReturn, marketReturn);
    assetReturn = series[0];
    marketReturn = series[1];
    final CAPMBetaCalculator calculator = getBetaCalculator(constraints.getValues(ValuePropertyNames.COVARIANCE_CALCULATOR),
View Full Code Here

  }
 
  private void ensureTimeseries(ExternalId externalId) {
    s_logger.info("Checking time-series for {}", externalId);
    try {
      HistoricalTimeSeries hts = getHistoricalTimeSeriesSource().getHistoricalTimeSeries(ExternalIdBundle.of(externalId), getDataSource(), getDataProvider(), getDataField());
      if (hts == null) {
        s_logger.info("Adding time-series for {}", externalId);
        getHistoricalTimeSeriesLoader().loadTimeSeries(ImmutableSet.of(externalId), getDataProvider(), getDataField(), null, null);
      } else if (isUpdateExisting()) {
        s_logger.info("Updating time-series for {} with identifier {}", externalId, hts.getUniqueId());
        getHistoricalTimeSeriesLoader().updateTimeSeries(hts.getUniqueId());
      }
    } catch (Exception e) {
      s_logger.error("Error with time-series for " + externalId, e);
    }
  }
View Full Code Here

          UniqueId uniqueId = _htsMaster.updateTimeSeriesDataPoints(doc.getInfo().getTimeSeriesObjectId(), timeSeries);
          result.put(bundleToIdentifier.get(bundleWithDates), uniqueId);
        } else {
          // update existing
          HistoricalTimeSeriesInfoDocument doc = searchResult.getDocuments().get(0);
          HistoricalTimeSeries existingSeries = _htsMaster.getTimeSeries(doc.getInfo().getTimeSeriesObjectId(), VersionCorrection.LATEST, HistoricalTimeSeriesGetFilter.ofLatestPoint());
          if (existingSeries.getTimeSeries().size() > 0) {
            LocalDate latestTime = existingSeries.getTimeSeries().getLatestTime();
            timeSeries = timeSeries.subSeries(latestTime, false, timeSeries.getLatestTime(), true);
          }
          UniqueId uniqueId = existingSeries.getUniqueId();
          if (timeSeries.size() > 0) {
            uniqueId = _htsMaster.updateTimeSeriesDataPoints(doc.getInfo().getTimeSeriesObjectId(), timeSeries);
          }
          result.put(bundleToIdentifier.get(bundleWithDates), uniqueId);
        }
View Full Code Here

    for (FactorExposureData exposure : factorExposureDataList) {
      HistoricalTimeSeriesInfoSearchRequest exposureSearchRequest = new HistoricalTimeSeriesInfoSearchRequest();
      exposureSearchRequest.addExternalId(exposure.getExposureExternalId());
      exposureSearchRequest.setDataField("EXPOSURE");
      HistoricalTimeSeriesInfoSearchResult exposureSearchResult = data().getHistoricalTimeSeriesMaster().search(exposureSearchRequest);
      HistoricalTimeSeries exposureHTS = null;
      if (exposureSearchResult.getFirstInfo() != null) {
        exposureHTS = data().getHistoricalTimeSeriesMaster().getTimeSeries(exposureSearchResult.getFirstInfo().getTimeSeriesObjectId(), VersionCorrection.LATEST);
      }

      HistoricalTimeSeriesInfoSearchRequest convexitySearchRequest = new HistoricalTimeSeriesInfoSearchRequest();
      convexitySearchRequest.addExternalId(exposure.getExposureExternalId());
      convexitySearchRequest.setDataField("CONVEXITY");
      HistoricalTimeSeriesInfoSearchResult convexitySearchResult = data().getHistoricalTimeSeriesMaster().search(convexitySearchRequest);
      HistoricalTimeSeries convexityHTS = null;
      if (convexitySearchResult.getFirstInfo() != null) {
        convexityHTS = data().getHistoricalTimeSeriesMaster().getTimeSeries(convexitySearchResult.getFirstInfo().getTimeSeriesObjectId(), VersionCorrection.LATEST);
      }

      HistoricalTimeSeriesInfoSearchRequest priceSearchRequest = new HistoricalTimeSeriesInfoSearchRequest();
      priceSearchRequest.addExternalId(exposure.getExposureExternalId());
      priceSearchRequest.setDataField("PX_LAST");
      HistoricalTimeSeriesInfoSearchResult priceSearchResult = data().getHistoricalTimeSeriesMaster().search(priceSearchRequest);
      HistoricalTimeSeries priceHTS = null;
      if (priceSearchResult.getFirstInfo() != null) {
        priceHTS = data().getHistoricalTimeSeriesMaster().getTimeSeries(priceSearchResult.getFirstInfo().getTimeSeriesObjectId(), VersionCorrection.LATEST);
      }

      results.add(new FactorExposure(exposure.getFactorType().getFactorType(),
        exposure.getFactorName(),
        exposure.getNode(),
        priceHTS != null ? priceHTS.getUniqueId() : null,
        priceHTS != null ? priceHTS.getTimeSeries().getLatestValue() : null,
        exposureHTS != null ? exposureHTS.getUniqueId() : null,
        exposureHTS != null ? exposureHTS.getTimeSeries().getLatestValue() : null,
        convexityHTS != null ? convexityHTS.getUniqueId() : null,
        convexityHTS != null ? convexityHTS.getTimeSeries().getLatestValue() : null));
    }
View Full Code Here

    ObjectId tsObjectId = null;
    Security security = doc.getPosition().getSecurityLink().resolveQuiet(data().getSecuritySource());
    if (security != null && !security.getExternalIdBundle().isEmpty()) {
      // Get the last price HTS for the security
      HistoricalTimeSeriesSource htsSource = data().getHistoricalTimeSeriesSource();
      HistoricalTimeSeries series = htsSource.getHistoricalTimeSeries(
          MarketDataRequirementNames.MARKET_VALUE, doc.getPosition().getSecurity().getExternalIdBundle(), null, null, false, null, false, 0);
      if (series != null) {
        tsObjectId = series.getUniqueId().getObjectId();
      }
    }
   
    out.put("positionDoc", doc);
    out.put("position", doc.getPosition());
View Full Code Here

TOP

Related Classes of com.opengamma.core.historicaltimeseries.HistoricalTimeSeries

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.