@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));
 }
 @SuppressWarnings("unchecked")
 @Override
 public Set<ComputedValue> execute(
     final FunctionExecutionContext executionContext,
     final FunctionInputs inputs,
     final ComputationTarget target,
     final Set<ValueRequirement> desiredValues) {
   final HistoricalTimeSeriesSource timeSeriesSource =
       OpenGammaExecutionContext.getHistoricalTimeSeriesSource(executionContext);
   final ValueRequirement desiredValue = desiredValues.iterator().next();
   Object value = timeSeriesSource.getLatestDataPoint(target.getUniqueId());
   if (value == null) {
     value = MissingMarketDataSentinel.getInstance();
   } else {
     final String adjusterString =
         desiredValue.getConstraint(HistoricalTimeSeriesFunctionUtils.ADJUST_PROPERTY);
     final HistoricalTimeSeriesAdjustment htsa =
         HistoricalTimeSeriesAdjustment.parse(adjusterString);
     value = htsa.adjust(((Pair<LocalDate, Double>) value).getValue());
   }
   return Collections.singleton(
       new ComputedValue(
           new ValueSpecification(
               desiredValue.getValueName(),
               desiredValue.getTargetSpecification(),
               desiredValue.getConstraints()),
           value));
 }
 @Override
 public Set<ValueRequirement> getRequirements(
     final FunctionCompilationContext context,
     final ComputationTarget target,
     final ValueRequirement desiredValue) {
   final Set<String> curves = desiredValue.getConstraints().getValues(ValuePropertyNames.CURVE);
   final Set<String> curveCalcConfigs =
       desiredValue.getConstraints().getValues(ValuePropertyNames.CURVE_CALCULATION_CONFIG);
   if ((curves == null) || (curves.size() != 1)) {
     s_logger.warn("no curve specified");
     // Can't support an unbound request; an injection function must be used (or declare all as
     // optional and use [PLAT-1771])
     return null;
   }
   if ((curveCalcConfigs == null) || (curveCalcConfigs.size() != 1)) {
     s_logger.warn("no curve config specified");
     return null;
   }
   final String curve = curves.iterator().next();
   final String curveCalcConfig = curveCalcConfigs.iterator().next();
   final Set<ValueRequirement> requirements = Sets.newHashSet();
   requirements.add(getCurveRequirement(target, curve, curveCalcConfig));
   requirements.add(getCurveSpecRequirement(target, curve));
   requirements.addAll(
       getSensitivityRequirements(
           context.getSecuritySource(), (RawSecurity) target.getSecurity()));
   return requirements;
 }
  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;
  }
 @Override
 public Set<ComputedValue> execute(
     final FunctionExecutionContext executionContext,
     final FunctionInputs inputs,
     final ComputationTarget target,
     final Set<ValueRequirement> desiredValues) {
   double parentValue = 0;
   double targetValue = 0;
   final UniqueId targetIdentifier = target.getUniqueId();
   for (final ComputedValue c : inputs.getAllValues()) {
     if (targetIdentifier.equals(c.getSpecification().getTargetSpecification().getUniqueId())) {
       targetValue = (Double) c.getValue();
     } else {
       parentValue = (Double) c.getValue();
     }
   }
   final ValueRequirement desiredValue = desiredValues.iterator().next();
   return Collections.singleton(
       new ComputedValue(
           new ValueSpecification(
               ValueRequirementNames.WEIGHT,
               target.toSpecification(),
               desiredValue.getConstraints()),
           targetValue / parentValue));
 }
 @Override
 public Set<ComputedValue> execute(
     final FunctionExecutionContext executionContext,
     final FunctionInputs inputs,
     final ComputationTarget target,
     final Set<ValueRequirement> desiredValues) {
   final ValueRequirement desiredValue = desiredValues.iterator().next();
   final String surfaceName = desiredValue.getConstraint(SURFACE);
   final Object interpolatorObject =
       inputs.getValue(getInterpolatorRequirement(target, desiredValue));
   if (interpolatorObject == null) {
     throw new OpenGammaRuntimeException("Could not get volatility surface interpolator");
   }
   final VolatilitySurfaceInterpolator surfaceInterpolator =
       (VolatilitySurfaceInterpolator) interpolatorObject;
   final SmileSurfaceDataBundle data =
       getData(
           inputs,
           getVolatilityDataRequirement(
               target,
               surfaceName,
               getInstrumentType(),
               getSurfaceQuoteType(),
               getSurfaceQuoteUnits()),
           getForwardCurveRequirement(target, desiredValue));
   final BlackVolatilitySurfaceMoneyness impliedVolatilitySurface =
       surfaceInterpolator.getVolatilitySurface(data);
   final ValueProperties properties = getResultProperties(desiredValue);
   final ValueSpecification spec =
       new ValueSpecification(
           ValueRequirementNames.BLACK_VOLATILITY_SURFACE, target.toSpecification(), properties);
   return Collections.singleton(new ComputedValue(spec, impliedVolatilitySurface));
 }
 @Override
 public Set<ValueRequirement> getRequirements(
     final FunctionCompilationContext context,
     final ComputationTarget target,
     final ValueRequirement desiredValue) {
   Set<String> values =
       desiredValue.getConstraints().getValues(HistoricalTimeSeriesFunctionUtils.ADJUST_PROPERTY);
   if ((values == null) || values.isEmpty()) {
     return Collections.singleton(
         new ValueRequirement(
             ValueRequirementNames.HISTORICAL_TIME_SERIES_LATEST,
             target.toSpecification(),
             desiredValue
                 .getConstraints()
                 .copy()
                 .withoutAny(HistoricalTimeSeriesFunctionUtils.ADJUST_PROPERTY)
                 .with(HistoricalTimeSeriesFunctionUtils.ADJUST_PROPERTY, "")
                 .get()));
   } else if (values.size() > 1) {
     return Collections.singleton(
         new ValueRequirement(
             ValueRequirementNames.HISTORICAL_TIME_SERIES_LATEST,
             target.toSpecification(),
             desiredValue
                 .getConstraints()
                 .copy()
                 .withoutAny(HistoricalTimeSeriesFunctionUtils.ADJUST_PROPERTY)
                 .with(HistoricalTimeSeriesFunctionUtils.ADJUST_PROPERTY, values.iterator().next())
                 .get()));
   }
   return Collections.emptySet();
 }
  @Override
  public Set<ComputedValue> execute(
      final FunctionExecutionContext executionContext,
      final FunctionInputs inputs,
      final ComputationTarget target,
      final Set<ValueRequirement> desiredValues) {
    final ValueRequirement desiredValue = desiredValues.iterator().next();
    final String curveName = desiredValue.getConstraint(ValuePropertyNames.CURVE);
    final String interpolatorName =
        desiredValue.getConstraint(
            ForwardCurveValuePropertyNames.PROPERTY_FORWARD_CURVE_INTERPOLATOR);
    final String leftExtrapolatorName =
        desiredValue.getConstraint(
            ForwardCurveValuePropertyNames.PROPERTY_FORWARD_CURVE_LEFT_EXTRAPOLATOR);
    final String rightExtrapolatorName =
        desiredValue.getConstraint(
            ForwardCurveValuePropertyNames.PROPERTY_FORWARD_CURVE_RIGHT_EXTRAPOLATOR);

    final Object objectFuturePriceData =
        inputs.getValue(ValueRequirementNames.FUTURE_PRICE_CURVE_DATA);
    if (objectFuturePriceData == null) {
      throw new OpenGammaRuntimeException("Could not get futures curve " + curveName);
    }
    final NodalDoublesCurve futurePriceData = (NodalDoublesCurve) objectFuturePriceData;

    final Interpolator1D interpolator =
        CombinedInterpolatorExtrapolatorFactory.getInterpolator(
            interpolatorName, leftExtrapolatorName, rightExtrapolatorName);

    final ForwardCurve curve =
        new ForwardCurve(
            InterpolatedDoublesCurve.from(
                futurePriceData.getXData(), futurePriceData.getYData(), interpolator));

    final ValueProperties properties =
        createValueProperties()
            .with(
                ForwardCurveValuePropertyNames.PROPERTY_FORWARD_CURVE_CALCULATION_METHOD,
                ForwardCurveValuePropertyNames.PROPERTY_FUTURE_PRICE_METHOD)
            .with(ValuePropertyNames.CURVE, curveName)
            .with(
                ForwardCurveValuePropertyNames.PROPERTY_FORWARD_CURVE_INTERPOLATOR,
                interpolatorName)
            .with(
                ForwardCurveValuePropertyNames.PROPERTY_FORWARD_CURVE_LEFT_EXTRAPOLATOR,
                leftExtrapolatorName)
            .with(
                ForwardCurveValuePropertyNames.PROPERTY_FORWARD_CURVE_RIGHT_EXTRAPOLATOR,
                rightExtrapolatorName)
            .with(
                InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE,
                InstrumentTypeProperties.EQUITY_FUTURE_PRICE)
            .get();

    final ValueSpecification resultSpec =
        new ValueSpecification(
            ValueRequirementNames.FORWARD_CURVE, target.toSpecification(), properties);
    return Collections.singleton(new ComputedValue(resultSpec, curve));
  }
 @Override
 public Set<ComputedValue> execute(
     final FunctionExecutionContext executionContext,
     final FunctionInputs inputs,
     final ComputationTarget target,
     final Set<ValueRequirement> desiredValues) {
   String curveName = null;
   String curveCalculationConfig = null;
   for (final ValueRequirement requirement : desiredValues) {
     final ValueProperties constraints = requirement.getConstraints();
     final Set<String> values = constraints.getValues(ValuePropertyNames.CURVE);
     if (values != null) {
       curveName = values.iterator().next();
     }
     final Set<String> curveConfigValues =
         constraints.getValues(ValuePropertyNames.CURVE_CALCULATION_CONFIG);
     if (curveConfigValues != null) {
       curveCalculationConfig = curveConfigValues.iterator().next();
     }
   }
   assert curveName != null;
   assert curveCalculationConfig != null;
   final RawSecurity security = (RawSecurity) target.getSecurity();
   // final BigDecimal qty = target.getPosition().getQuantity();
   final ValueRequirement curveRequirement =
       getCurveRequirement(target, curveName, curveCalculationConfig);
   final Object curveObject = inputs.getValue(curveRequirement);
   if (curveObject == null) {
     throw new OpenGammaRuntimeException("Could not get " + curveRequirement);
   }
   Object curveSpecObject = null;
   final ValueRequirement curveSpecRequirement = getCurveSpecRequirement(target, curveName);
   curveSpecObject = inputs.getValue(curveSpecRequirement);
   if (curveSpecObject == null) {
     throw new OpenGammaRuntimeException("Could not get " + curveSpecRequirement);
   }
   final YieldAndDiscountCurve curve = (YieldAndDiscountCurve) curveObject;
   final InterpolatedYieldCurveSpecificationWithSecurities curveSpec =
       (InterpolatedYieldCurveSpecificationWithSecurities) curveSpecObject;
   final LinkedHashMap<String, YieldAndDiscountCurve> interpolatedCurves =
       new LinkedHashMap<String, YieldAndDiscountCurve>();
   interpolatedCurves.put(curveName, curve);
   final YieldCurveBundle bundle = new YieldCurveBundle(interpolatedCurves);
   final DoubleMatrix1D sensitivitiesForCurves =
       getSensitivities(executionContext.getSecuritySource(), inputs, security, curveSpec, curve);
   final ValueProperties.Builder properties =
       createValueProperties(target)
           .with(ValuePropertyNames.CURVE, curveName)
           .with(ValuePropertyNames.CURVE_CALCULATION_CONFIG, curveCalculationConfig);
   final ComputationTargetSpecification targetSpec = target.toSpecification();
   final ValueSpecification resultSpec =
       new ValueSpecification(YCNS_REQUIREMENT, targetSpec, properties.get());
   final Set<ComputedValue> results =
       YieldCurveNodeSensitivitiesHelper.getInstrumentLabelledSensitivitiesForCurve(
           curveName, bundle, sensitivitiesForCurves, curveSpec, resultSpec);
   // s_logger.debug("execute, returning " + results);
   return results;
 }
Exemple #10
0
 @Override
 public Set<ComputedValue> execute(
     final FunctionExecutionContext executionContext,
     final FunctionInputs inputs,
     final ComputationTarget target,
     final Set<ValueRequirement> desiredValues) {
   final Clock snapshotClock = executionContext.getValuationClock();
   final ZonedDateTime now = snapshotClock.zonedDateTime();
   final FinancialSecurity security = (FinancialSecurity) target.getSecurity();
   final Currency payCurrency, receiveCurrency;
   if (security instanceof FXForwardSecurity) {
     final FXForwardSecurity forward = (FXForwardSecurity) security;
     payCurrency = forward.getPayCurrency();
     receiveCurrency = forward.getReceiveCurrency();
   } else {
     final NonDeliverableFXForwardSecurity ndf = (NonDeliverableFXForwardSecurity) security;
     payCurrency = ndf.getPayCurrency();
     receiveCurrency = ndf.getReceiveCurrency();
   }
   final ForexDefinition definition = (ForexDefinition) security.accept(VISITOR);
   final ValueRequirement desiredValue = desiredValues.iterator().next();
   final String payCurveName = desiredValue.getConstraint(ValuePropertyNames.PAY_CURVE);
   final String receiveCurveName = desiredValue.getConstraint(ValuePropertyNames.RECEIVE_CURVE);
   final String payCurveConfig = desiredValue.getConstraint(PAY_CURVE_CALC_CONFIG);
   final String receiveCurveConfig = desiredValue.getConstraint(RECEIVE_CURVE_CALC_CONFIG);
   final String fullPutCurveName = payCurveName + "_" + payCurrency.getCode();
   final String fullCallCurveName = receiveCurveName + "_" + receiveCurrency.getCode();
   final YieldAndDiscountCurve payFundingCurve =
       getCurve(inputs, payCurrency, payCurveName, payCurveConfig);
   final YieldAndDiscountCurve receiveFundingCurve =
       getCurve(inputs, receiveCurrency, receiveCurveName, receiveCurveConfig);
   final YieldAndDiscountCurve[] curves;
   final Map<String, Currency> curveCurrency = new HashMap<String, Currency>();
   curveCurrency.put(fullPutCurveName, payCurrency);
   curveCurrency.put(fullCallCurveName, receiveCurrency);
   final String[] allCurveNames;
   if (FXUtils.isInBaseQuoteOrder(
       payCurrency, receiveCurrency)) { // To get Base/quote in market standard order.
     curves = new YieldAndDiscountCurve[] {payFundingCurve, receiveFundingCurve};
     allCurveNames = new String[] {fullPutCurveName, fullCallCurveName};
   } else {
     curves = new YieldAndDiscountCurve[] {receiveFundingCurve, payFundingCurve};
     allCurveNames = new String[] {fullCallCurveName, fullPutCurveName};
   }
   final YieldCurveBundle yieldCurves = new YieldCurveBundle(allCurveNames, curves);
   final ValueProperties.Builder properties =
       getResultProperties(
           payCurveName, receiveCurveName, payCurveConfig, receiveCurveConfig, target);
   final ValueSpecification spec =
       new ValueSpecification(
           ValueRequirementNames.VALUE_THETA, target.toSpecification(), properties.get());
   final ConstantSpreadHorizonThetaCalculator calculator =
       ConstantSpreadHorizonThetaCalculator.getInstance();
   final MultipleCurrencyAmount theta =
       calculator.getTheta(definition, now, allCurveNames, yieldCurves, DAYS_TO_MOVE_FORWARD);
   return Collections.singleton(new ComputedValue(spec, theta));
 }
 /**
  * Respecifies the properties to match a tighter requirement.
  *
  * <p>This adds a new requirement to the specification. It requires {@code
  * requirement.isSatisfiedBy(this) == true}.
  *
  * @param requirement additional requirement to reduce properties against
  * @return the value specification based on this with the additional requirement added, not null
  */
 public ValueSpecification compose(final ValueRequirement requirement) {
   assert requirement.isSatisfiedBy(this);
   final ValueProperties oldProperties = getProperties();
   final ValueProperties newProperties = oldProperties.compose(requirement.getConstraints());
   if (newProperties == oldProperties) {
     return this;
   } else {
     return new ValueSpecification(getValueName(), getTargetSpecification(), newProperties);
   }
 }
 @Override
 public Set<ValueSpecification> getResults(
     final FunctionCompilationContext context,
     final ComputationTarget target,
     final Map<ValueSpecification, ValueRequirement> inputs) {
   if (inputs.size() == 1) {
     final ValueSpecification input = Iterables.getOnlyElement(inputs.keySet());
     if (ValueRequirementNames.PNL_SERIES.equals(input.getValueName())) {
       return Collections.singleton(input);
     }
   }
   final FXForwardSecurity security = (FXForwardSecurity) target.getPosition().getSecurity();
   final CurrencyPair currencyPair =
       _currencyPairs.getCurrencyPair(security.getPayCurrency(), security.getReceiveCurrency());
   if (currencyPair == null) {
     return null;
   }
   final Currency currencyBase = currencyPair.getBase();
   String resultCurrency = null;
   final ValueProperties.Builder builder = createValueProperties();
   for (final Map.Entry<ValueSpecification, ValueRequirement> entry : inputs.entrySet()) {
     final ValueSpecification inputSpec = entry.getKey();
     final ValueRequirement inputReq = entry.getValue();
     if (inputReq.getValueName().equals(RETURN_SERIES)) {
       final Set<String> resultCurrencies = inputReq.getConstraints().getValues(CURRENCY);
       if (resultCurrencies != null && resultCurrencies.size() == 1) {
         resultCurrency = inputReq.getConstraint(CURRENCY);
       } else {
         resultCurrency = currencyBase.getCode();
       }
     }
     for (final String propertyName : inputSpec.getProperties().getProperties()) {
       if (ValuePropertyNames.FUNCTION.equals(propertyName)) {
         continue;
       }
       final Set<String> values = inputSpec.getProperties().getValues(propertyName);
       if (values == null || values.isEmpty()) {
         builder.withAny(propertyName);
       } else {
         builder.with(propertyName, values);
       }
     }
   }
   if (resultCurrency == null) {
     return null;
   }
   builder
       .with(ValuePropertyNames.CURRENCY, resultCurrency)
       .with(
           ValuePropertyNames.PROPERTY_PNL_CONTRIBUTIONS,
           ValueRequirementNames.FX_CURRENCY_EXPOSURE);
   return ImmutableSet.of(
       new ValueSpecification(
           ValueRequirementNames.PNL_SERIES, target.toSpecification(), builder.get()));
 }
 /**
  * Creates a new specification to satisfy the given requirement.
  *
  * <p>The properties must include the function identifier and be able to satisfy the constraints
  * of the original requirement.
  *
  * @param requirementSpecification a requirement, not null
  * @param properties the value properties, not null and must include the function identifier
  */
 public ValueSpecification(
     final ValueRequirement requirementSpecification, final ValueProperties properties) {
   ArgumentChecker.notNull(requirementSpecification, "requirementSpecification");
   ArgumentChecker.notNull(properties, "properties");
   ArgumentChecker.notNull(
       properties.getValues(ValuePropertyNames.FUNCTION), "properties.FUNCTION");
   assert requirementSpecification.getConstraints().isSatisfiedBy(properties);
   // requirement specification interns its valueName
   _valueName = requirementSpecification.getValueName();
   _targetSpecification = requirementSpecification.getTargetSpecification();
   _properties = properties;
 }
 /**
  * Simplifies the type based on the associated {@link ComputationTargetResolver}.
  *
  * @param valueReq the requirement to process, not null
  * @return the possibly simplified requirement, not null
  */
 public ValueRequirement simplifyType(final ValueRequirement valueReq) {
   final ComputationTargetReference oldTargetRef = valueReq.getTargetReference();
   final ComputationTargetReference newTargetRef =
       ComputationTargetResolverUtils.simplifyType(
           oldTargetRef, getCompilationContext().getComputationTargetResolver());
   if (newTargetRef == oldTargetRef) {
     return valueReq;
   } else {
     return MemoryUtils.instance(
         new ValueRequirement(valueReq.getValueName(), newTargetRef, valueReq.getConstraints()));
   }
 }
 @Override
 protected PresentValueNodeSensitivityCalculator getNodeSensitivityCalculator(
     final ValueRequirement desiredValue) {
   final Double cutoff =
       Double.parseDouble(
           desiredValue.getConstraint(SABRRightExtrapolationFunction.PROPERTY_CUTOFF_STRIKE));
   final Double mu =
       Double.parseDouble(
           desiredValue.getConstraint(
               SABRRightExtrapolationFunction.PROPERTY_TAIL_THICKNESS_PARAMETER));
   return PresentValueNodeSensitivityCalculator.using(
       new PresentValueCurveSensitivitySABRExtrapolationCalculator(cutoff, mu));
 }
 private ValueProperties getResultProperties(final ValueRequirement desiredValue) {
   return createValueProperties()
       .with(
           ValuePropertyNames.SAMPLING_PERIOD,
           desiredValue.getConstraint(ValuePropertyNames.SAMPLING_PERIOD))
       .with(
           ValuePropertyNames.SCHEDULE_CALCULATOR,
           desiredValue.getConstraint(ValuePropertyNames.SCHEDULE_CALCULATOR))
       .with(
           ValuePropertyNames.SAMPLING_FUNCTION,
           desiredValue.getConstraint(ValuePropertyNames.SAMPLING_FUNCTION))
       .with(
           ValuePropertyNames.RETURN_CALCULATOR,
           desiredValue.getConstraint(ValuePropertyNames.RETURN_CALCULATOR))
       .with(
           ValuePropertyNames.STD_DEV_CALCULATOR,
           desiredValue.getConstraint(ValuePropertyNames.STD_DEV_CALCULATOR))
       .with(
           ValuePropertyNames.EXCESS_RETURN_CALCULATOR,
           desiredValue.getConstraint(ValuePropertyNames.EXCESS_RETURN_CALCULATOR))
       .with(
           ValuePropertyNames.COVARIANCE_CALCULATOR,
           desiredValue.getConstraint(ValuePropertyNames.COVARIANCE_CALCULATOR))
       .with(
           ValuePropertyNames.VARIANCE_CALCULATOR,
           desiredValue.getConstraint(ValuePropertyNames.VARIANCE_CALCULATOR))
       .get();
 }
 /**
  * Creates a new specification to satisfy the the given requirement.
  *
  * <p>The properties of the new specification are the constraints from the requirement with the
  * function identifier added.
  *
  * @param requirementSpecification a value requirement, not null
  * @param functionIdentifier the unique identifier of the function producing this value, not null
  */
 public ValueSpecification(
     final ValueRequirement requirementSpecification, final String functionIdentifier) {
   ArgumentChecker.notNull(requirementSpecification, "requirementSpecification");
   ArgumentChecker.notNull(functionIdentifier, "functionIdentifier");
   // requirement specification interns its valueName
   _valueName = requirementSpecification.getValueName();
   _targetSpecification = requirementSpecification.getTargetSpecification();
   _properties =
       requirementSpecification
           .getConstraints()
           .copy()
           .with(ValuePropertyNames.FUNCTION, functionIdentifier)
           .get();
 }
 @Override
 protected LocalDateDoubleTimeSeries getReturnSeries(
     LocalDateDoubleTimeSeries ts, ValueRequirement desiredValue) {
   LocalDateDoubleTimeSeries differenceSeries = super.getReturnSeries(ts, desiredValue);
   double lambda =
       Double.parseDouble(
           desiredValue.getConstraint(
               VolatilityWeightingFunctionUtils.VOLATILITY_WEIGHTING_LAMBDA_PROPERTY));
   TimeSeriesWeightedVolatilityOperator weightedVol =
       new TimeSeriesWeightedVolatilityOperator(lambda);
   LocalDateDoubleTimeSeries weightedVolSeries =
       (LocalDateDoubleTimeSeries) weightedVol.evaluate(ts);
   int n = weightedVolSeries.size();
   double endDateWeightedVol = weightedVolSeries.getLatestValueFast();
   double[] volWeightedDifferences = new double[n];
   for (int i = 0; i < n; i++) {
     System.out.println(
         differenceSeries.getTimeAtIndex(i)
             + ","
             + differenceSeries.getValueAtIndexFast(i)
             + ","
             + weightedVolSeries.getValueAtIndexFast(i));
     volWeightedDifferences[i] =
         differenceSeries.getValueAtIndexFast(i)
             * endDateWeightedVol
             / weightedVolSeries.getValueAtIndexFast(i);
   }
   LocalDateDoubleTimeSeries volWeightedDifferenceSeries =
       ImmutableLocalDateDoubleTimeSeries.of(
           weightedVolSeries.timesArrayFast(), volWeightedDifferences);
   return volWeightedDifferenceSeries;
 }
  @Override
  public Set<ValueRequirement> getRequirements(
      final FunctionCompilationContext context,
      final ComputationTarget target,
      final ValueRequirement desiredValue) {
    final ValueProperties constraints = desiredValue.getConstraints();
    final Set<String> forwardCurveCalculationMethods =
        constraints.getValues(CURVE_CALCULATION_METHOD);
    if (forwardCurveCalculationMethods == null || forwardCurveCalculationMethods.size() != 1) {
      return null;
    }

    final Set<String> surfaceNames = constraints.getValues(SURFACE);
    if (surfaceNames == null || surfaceNames.size() != 1) {
      return null;
    }

    final String surfaceName = surfaceNames.iterator().next();
    final ValueRequirement forwardCurveRequirement =
        getForwardCurveRequirement(target, desiredValue);
    final ValueRequirement volatilitySurfaceRequirement =
        getVolatilityDataRequirement(
            target,
            surfaceName,
            getInstrumentType(),
            getSurfaceQuoteType(),
            getSurfaceQuoteUnits());
    final ValueRequirement interpolatorRequirement =
        getInterpolatorRequirement(target, desiredValue);
    return Sets.newHashSet(
        interpolatorRequirement, forwardCurveRequirement, volatilitySurfaceRequirement);
  }
 @Override
 public Set<ValueRequirement> getRequirements(
     final FunctionCompilationContext context,
     final ComputationTarget target,
     final ValueRequirement desiredValue) {
   final ValueProperties constraints = desiredValue.getConstraints();
   final Set<String> curveNames = constraints.getValues(CURVE);
   if (curveNames == null || curveNames.size() != 1) {
     return null;
   }
   final Set<String> curveExposureConfigs = constraints.getValues(CURVE_EXPOSURES);
   if (curveExposureConfigs == null) {
     return null;
   }
   final Set<String> curveType = constraints.getValues(PROPERTY_CURVE_TYPE);
   if (curveType == null) {
     return null;
   }
   if (super.getRequirements(context, target, desiredValue) == null) {
     return null;
   }
   final Set<ValueRequirement> requirements = new HashSet<>();
   final ValueProperties curveProperties = ValueProperties.with(CURVE, curveNames).get();
   final ValueProperties properties =
       ValueProperties.with(PROPERTY_CURVE_TYPE, curveType)
           .with(CURVE_EXPOSURES, curveExposureConfigs)
           .get();
   requirements.add(
       new ValueRequirement(
           CURVE_DEFINITION, ComputationTargetSpecification.NULL, curveProperties));
   requirements.add(
       new ValueRequirement(BLOCK_CURVE_SENSITIVITIES, target.toSpecification(), properties));
   return requirements;
 }
 @Override
 protected Object getResult(
     final InstrumentDerivative derivative,
     final SABRInterestRateDataBundle data,
     final ValueRequirement desiredValue) {
   final Double cutoff =
       Double.parseDouble(
           desiredValue.getConstraint(SABRRightExtrapolationFunction.PROPERTY_CUTOFF_STRIKE));
   final Double mu =
       Double.parseDouble(
           desiredValue.getConstraint(
               SABRRightExtrapolationFunction.PROPERTY_TAIL_THICKNESS_PARAMETER));
   final PresentValueSABRSensitivitySABRRightExtrapolationCalculator calculator =
       new PresentValueSABRSensitivitySABRRightExtrapolationCalculator(cutoff, mu);
   return getResultAsMatrix(derivative.accept(calculator, data));
 }
 @Override
 public Set<ValueRequirement> getRequirements(
     final FunctionCompilationContext context,
     final ComputationTarget target,
     final ValueRequirement desiredValue) {
   final ValueProperties constraints = desiredValue.getConstraints();
   Set<String> values = constraints.getValues(VALUE_PROPERTY_NAME);
   final String inputValue;
   if ((values == null) || values.isEmpty()) {
     inputValue = DEFAULT_VALUE_NAME;
   } else if (values.size() == 1) {
     inputValue = values.iterator().next();
   } else {
     return null;
   }
   // Propogate the desired value constraints onto the requirements, removing those specific to
   // this function and adding a unit homogeneity clause
   final ValueProperties.Builder requirementConstraintsBuilder =
       constraints.copy().withoutAny(VALUE_PROPERTY_NAME);
   for (String unit : UnitProperties.unitPropertyNames()) {
     values = constraints.getValues(unit);
     if (values == null) {
       // Unit was not specified on the output, but we specify it on the inputs so we can check
       // homogeneity to ensure the division is valid
       requirementConstraintsBuilder.withOptional(unit);
     }
   }
   // Request value on the value and parent
   final ValueProperties requirementConstraints = requirementConstraintsBuilder.get();
   return ImmutableSet.of(
       new ValueRequirement(inputValue, getValueTarget(target), requirementConstraints),
       new ValueRequirement(inputValue, getParentTarget(target), requirementConstraints));
 }
  public Set<ValueRequirement> getRequirements(
      final FunctionCompilationContext context,
      final ComputationTarget target,
      final ValueRequirement desiredValue) {
    Set<ValueRequirement> superReqs = super.getRequirements(context, target, desiredValue);
    if (superReqs == null) {
      return null;
    }

    // Test constraints are provided, else set to ""
    final ValueProperties constraints = desiredValue.getConstraints();
    ValueProperties.Builder scenarioDefaults = null;

    final Set<String> priceShiftSet = constraints.getValues(s_priceShift);
    if (priceShiftSet == null || priceShiftSet.isEmpty()) {
      scenarioDefaults = constraints.copy().withoutAny(s_priceShift).with(s_priceShift, "");
    }
    final Set<String> priceShiftTypeSet = constraints.getValues(s_priceShiftType);
    if (priceShiftTypeSet == null || priceShiftTypeSet.isEmpty()) {
      if (scenarioDefaults == null) {
        scenarioDefaults =
            constraints
                .copy()
                .withoutAny(s_priceShiftType)
                .with(s_priceShiftType, "Multiplicative");
      } else {
        scenarioDefaults =
            scenarioDefaults.withoutAny(s_priceShiftType).with(s_priceShiftType, "Multiplicative");
      }
    }
    final Set<String> volShiftSet = constraints.getValues(s_volShift);
    if (volShiftSet == null || volShiftSet.isEmpty()) {
      if (scenarioDefaults == null) {
        scenarioDefaults = constraints.copy().withoutAny(s_volShift).with(s_volShift, "");
      } else {
        scenarioDefaults = scenarioDefaults.withoutAny(s_volShift).with(s_volShift, "");
      }
    }
    final Set<String> volShiftSetType = constraints.getValues(s_volShiftType);
    if (volShiftSetType == null || volShiftSetType.isEmpty()) {
      if (scenarioDefaults == null) {
        scenarioDefaults =
            constraints.copy().withoutAny(s_volShiftType).with(s_volShiftType, "Multiplicative");
      } else {
        scenarioDefaults =
            scenarioDefaults.withoutAny(s_volShiftType).with(s_volShiftType, "Multiplicative");
      }
    }

    // If defaults have been added, this adds additional copy of the Function into dep graph with
    // the adjusted constraints
    if (scenarioDefaults != null) {
      return Collections.singleton(
          new ValueRequirement(
              getValueRequirementName(), target.toSpecification(), scenarioDefaults.get()));
    } else { // Scenarios are defined, so we're satisfied
      return superReqs;
    }
  }
 @Override
 public Set<ValueRequirement> getRequirements(
     final FunctionCompilationContext context,
     final ComputationTarget target,
     final ValueRequirement desiredValue) {
   final ValueProperties constraints = desiredValue.getConstraints();
   final Set<String> payCurveNames = constraints.getValues(ValuePropertyNames.PAY_CURVE);
   if (payCurveNames == null || payCurveNames.size() != 1) {
     return null;
   }
   final Set<String> receiveCurveNames = constraints.getValues(ValuePropertyNames.RECEIVE_CURVE);
   if (receiveCurveNames == null || receiveCurveNames.size() != 1) {
     return null;
   }
   final Set<String> payCurveConfigNames =
       constraints.getValues(ValuePropertyNames.PAY_CURVE_CALCULATION_CONFIG);
   if (payCurveConfigNames == null || payCurveConfigNames.size() != 1) {
     return null;
   }
   final Set<String> receiveCurveConfigNames =
       constraints.getValues(ValuePropertyNames.RECEIVE_CURVE_CALCULATION_CONFIG);
   if (receiveCurveConfigNames == null || receiveCurveConfigNames.size() != 1) {
     return null;
   }
   final Set<String> daysForwardNames = constraints.getValues(PROPERTY_DAYS_TO_MOVE_FORWARD);
   if (daysForwardNames == null || daysForwardNames.size() != 1) {
     return null;
   }
   final String payCurveName = payCurveNames.iterator().next();
   final String receiveCurveName = receiveCurveNames.iterator().next();
   final String payCurveCalculationConfig = payCurveConfigNames.iterator().next();
   final String receiveCurveCalculationConfig = receiveCurveConfigNames.iterator().next();
   final FinancialSecurity security = (FinancialSecurity) target.getSecurity();
   final Currency payCurrency = security.accept(ForexVisitors.getPayCurrencyVisitor());
   final Currency receiveCurrency = security.accept(ForexVisitors.getReceiveCurrencyVisitor());
   final ValueRequirement payFundingCurve =
       YieldCurveFunctionUtils.getCurveRequirementForFXForward(
           ComputationTargetSpecification.of(payCurrency),
           payCurveName,
           payCurveCalculationConfig,
           true);
   final ValueRequirement receiveFundingCurve =
       YieldCurveFunctionUtils.getCurveRequirementForFXForward(
           ComputationTargetSpecification.of(receiveCurrency),
           receiveCurveName,
           receiveCurveCalculationConfig,
           false);
   final ValueProperties optionalProperties =
       ValueProperties.builder()
           .with(PROPERTY_DAYS_TO_MOVE_FORWARD, daysForwardNames)
           .withOptional(PROPERTY_DAYS_TO_MOVE_FORWARD)
           .get();
   final ValueRequirement pairQuoteRequirement =
       new ValueRequirement(
           ValueRequirementNames.CURRENCY_PAIRS,
           ComputationTargetSpecification.NULL,
           optionalProperties);
   return Sets.newHashSet(payFundingCurve, receiveFundingCurve, pairQuoteRequirement);
 }
 @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;
 }
 @Override
 public Set<ComputedValue> execute(
     final FunctionExecutionContext executionContext,
     final FunctionInputs inputs,
     final ComputationTarget target,
     final Set<ValueRequirement> desiredValues) {
   final FinancialSecurity security = (FinancialSecurity) target.getSecurity();
   final Currency currency = FinancialSecurityUtils.getCurrency(security);
   final Clock snapshotClock = executionContext.getValuationClock();
   final ZonedDateTime now = snapshotClock.zonedDateTime();
   final HistoricalTimeSeriesBundle timeSeries =
       HistoricalTimeSeriesFunctionUtils.getHistoricalTimeSeriesInputs(executionContext, inputs);
   final ValueRequirement desiredValue = desiredValues.iterator().next();
   final String curveCalculationConfigName =
       desiredValue.getConstraint(ValuePropertyNames.CURVE_CALCULATION_CONFIG);
   final ConfigSource configSource = OpenGammaExecutionContext.getConfigSource(executionContext);
   final ConfigDBCurveCalculationConfigSource curveCalculationConfigSource =
       new ConfigDBCurveCalculationConfigSource(configSource);
   final MultiCurveCalculationConfig curveCalculationConfig =
       curveCalculationConfigSource.getConfig(curveCalculationConfigName);
   if (curveCalculationConfig == null) {
     throw new OpenGammaRuntimeException(
         "Could not find curve calculation configuration named " + curveCalculationConfigName);
   }
   final String[] curveNames = curveCalculationConfig.getYieldCurveNames();
   final String[] yieldCurveNames =
       curveNames.length == 1 ? new String[] {curveNames[0], curveNames[0]} : curveNames;
   final String[] curveNamesForSecurity =
       FixedIncomeInstrumentCurveExposureHelper.getCurveNamesForSecurity(
           security, yieldCurveNames[0], yieldCurveNames[1]);
   final YieldCurveBundle bundle =
       YieldCurveFunctionUtils.getAllYieldCurves(
           inputs, curveCalculationConfig, curveCalculationConfigSource);
   final InstrumentDefinition<?> definition = security.accept(_visitor);
   if (definition == null) {
     throw new OpenGammaRuntimeException("Definition for security " + security + " was null");
   }
   final InstrumentDerivative derivative =
       getDerivative(
           security, now, timeSeries, curveNamesForSecurity, definition, _definitionConverter);
   return getComputedValues(
       derivative, bundle, security, target, curveCalculationConfigName, currency.getCode());
 }
 @Override
 protected ValueProperties.Builder getResultProperties(
     final ComputationTarget target, final ValueRequirement desiredValue) {
   final String daysForward = desiredValue.getConstraint(PROPERTY_DAYS_TO_MOVE_FORWARD);
   final ValueProperties.Builder properties =
       super.getResultProperties(target, desiredValue)
           .with(PROPERTY_THETA_CALCULATION_METHOD, THETA_CONSTANT_SPREAD)
           .with(PROPERTY_DAYS_TO_MOVE_FORWARD, daysForward);
   return properties;
 }
 @Override
 public Set<ValueRequirement> getRequirements(
     final FunctionCompilationContext context,
     final ComputationTarget target,
     final ValueRequirement desiredValue) {
   final ValueProperties constraints = desiredValue.getConstraints();
   final Set<String> surfaceNames = constraints.getValues(ValuePropertyNames.SURFACE);
   if (surfaceNames == null || surfaceNames.size() != 1) {
     return null;
   }
   final Set<String> curveCalculationConfigNames =
       constraints.getValues(ValuePropertyNames.CURVE_CALCULATION_CONFIG);
   if (curveCalculationConfigNames == null || curveCalculationConfigNames.size() != 1) {
     return null;
   }
   final String curveCalculationConfigName = curveCalculationConfigNames.iterator().next();
   final ConfigSource configSource = OpenGammaCompilationContext.getConfigSource(context);
   final ConfigDBCurveCalculationConfigSource curveCalculationConfigSource =
       new ConfigDBCurveCalculationConfigSource(configSource);
   final MultiCurveCalculationConfig curveCalculationConfig =
       curveCalculationConfigSource.getConfig(curveCalculationConfigName);
   if (curveCalculationConfig == null) {
     s_logger.error(
         "Could not find curve calculation configuration named " + curveCalculationConfigName);
     return null;
   }
   final Currency currency = FinancialSecurityUtils.getCurrency(target.getSecurity());
   if (!ComputationTargetSpecification.of(currency).equals(curveCalculationConfig.getTarget())) {
     s_logger.error(
         "Security currency and curve calculation config id were not equal; have {} and {}",
         currency,
         curveCalculationConfig.getTarget());
     return null;
   }
   final String surfaceName = surfaceNames.iterator().next();
   final Set<ValueRequirement> requirements = new HashSet<>();
   requirements.addAll(
       YieldCurveFunctionUtils.getCurveRequirements(
           curveCalculationConfig, curveCalculationConfigSource));
   requirements.add(getVolatilityRequirement(surfaceName, currency));
   final FinancialSecurity security = (FinancialSecurity) target.getSecurity();
   try {
     final Set<ValueRequirement> timeSeriesRequirements =
         _definitionConverter.getConversionTimeSeriesRequirements(
             security, security.accept(_visitor));
     if (timeSeriesRequirements == null) {
       return null;
     }
     requirements.addAll(timeSeriesRequirements);
     return requirements;
   } catch (final Exception e) {
     s_logger.error(e.getMessage());
     return null;
   }
 }
  @Override
  public Set<ComputedValue> execute(
      final FunctionExecutionContext executionContext,
      final FunctionInputs inputs,
      final ComputationTarget target,
      final Set<ValueRequirement> desiredValues) {
    final ValueRequirement desiredValue = Iterables.getOnlyElement(desiredValues);
    final String curveName = desiredValue.getConstraint(ValuePropertyNames.CURVE);
    final String curveCalculationConfig =
        desiredValue.getConstraint(ValuePropertyNames.CURVE_CALCULATION_CONFIG);
    // 1. Get the expiry _time_ from the trade
    final EquityVarianceSwapSecurity security = (EquityVarianceSwapSecurity) target.getSecurity();
    final double expiry =
        TimeCalculator.getTimeBetween(
            executionContext.getValuationClock().zonedDateTime(),
            security.getLastObservationDate());

    // 2. Get the discount curve and spot value
    final Object discountObject =
        inputs.getValue(getDiscountRequirement(security, curveName, curveCalculationConfig));
    if (discountObject == null) {
      throw new OpenGammaRuntimeException("Could not get Discount Curve");
    }
    final YieldAndDiscountCurve discountCurve = (YieldAndDiscountCurve) discountObject;

    final Object spotObject = inputs.getValue(getSpotRequirement(security));
    if (spotObject == null) {
      throw new OpenGammaRuntimeException("Could not get Underlying's Spot value");
    }
    final double spot = (Double) spotObject;

    // 3. Compute the forward
    final double discountFactor = discountCurve.getDiscountFactor(expiry);
    Validate.isTrue(
        discountFactor != 0,
        "The discount curve has returned a zero value for a discount bond. Check rates.");
    final double forward = spot / discountFactor;

    final ValueSpecification valueSpec = getValueSpecification(security);
    return Collections.singleton(new ComputedValue(valueSpec, forward));
  }
 @Override
 public Set<ValueRequirement> getRequirements(
     final FunctionCompilationContext context,
     final ComputationTarget target,
     final ValueRequirement desiredValue) {
   final Set<String> daysForwardNames =
       desiredValue.getConstraints().getValues(PROPERTY_DAYS_TO_MOVE_FORWARD);
   if (daysForwardNames == null || daysForwardNames.size() != 1) {
     return null;
   }
   return super.getRequirements(context, target, desiredValue);
 }