Package it.unimi.dsi.fastutil.doubles

Examples of it.unimi.dsi.fastutil.doubles.DoubleArrayList


      public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues) {
        final Clock snapshotClock = executionContext.getValuationClock();
        final ValueRequirement desiredValue = desiredValues.iterator().next();
        final String curveName = desiredValue.getConstraint(ValuePropertyNames.CURVE);
        final ZonedDateTime now = ZonedDateTime.now(snapshotClock);
        final DoubleArrayList expiries = new DoubleArrayList();
        final DoubleArrayList forwards = new DoubleArrayList();
        final UnorderedCurrencyPair currencyPair = UnorderedCurrencyPair.of(target.getUniqueId());
        final FXForwardCurveDefinition definition = curveDefinitionSource.getDefinition(curveName, currencyPair.toString());
        if (definition == null) {
          throw new OpenGammaRuntimeException("Couldn't find FX forward curve definition called " + curveName + " for target " + target);
        }
        final FXForwardCurveSpecification specification = curveSpecificationSource.getSpecification(curveName, currencyPair.toString());
        if (specification == null) {
          throw new OpenGammaRuntimeException("Couldn't find FX forward curve specification called " + curveName + " for target " + target);
        }
        final FXForwardCurveInstrumentProvider provider = specification.getCurveInstrumentProvider();
        final Object dataObject = inputs.getValue(ValueRequirementNames.FX_FORWARD_CURVE_MARKET_DATA);
        if (dataObject == null) {
          throw new OpenGammaRuntimeException("Could not get market data");
        }
        @SuppressWarnings("unchecked")
        final Map<ExternalId, Double> data = (Map<ExternalId, Double>) dataObject;
        final String interpolatorName = desiredValue.getConstraint(PROPERTY_FORWARD_CURVE_INTERPOLATOR);
        final String leftExtrapolatorName = desiredValue.getConstraint(PROPERTY_FORWARD_CURVE_LEFT_EXTRAPOLATOR);
        final String rightExtrapolatorName = desiredValue.getConstraint(PROPERTY_FORWARD_CURVE_RIGHT_EXTRAPOLATOR);
        for (final Tenor tenor : definition.getTenors()) {
          final ExternalId identifier = provider.getInstrument(now.toLocalDate(), tenor);
          if (data.containsKey(identifier)) {
            expiries.add(TimeCalculator.getTimeBetween(now, now.plus(tenor.getPeriod())));
            forwards.add(data.get(identifier));
          }
        }
        if (expiries.size() == 0) {
          throw new OpenGammaRuntimeException("Could not get any values for FX forwards");
        }
View Full Code Here


    final MultiCurveCalculationConfig curveCalculationConfig = new ConfigDBCurveCalculationConfigSource(configSource).getConfig(curveCalculationConfigName);
    if (curveCalculationConfig == null) {
      throw new OpenGammaRuntimeException("Could not find curve calculation configuration named " + curveCalculationConfigName);
    }
    final List<InstrumentDerivative> derivatives = new ArrayList<>();
    final DoubleArrayList marketValues = new DoubleArrayList();
    final DoubleArrayList initialRatesGuess = new DoubleArrayList();
    final LinkedHashSet<String> curveNames = new LinkedHashSet<>();
    for (final String curveName : curveCalculationConfig.getYieldCurveNames()) {
      curveNames.add(curveName);
    }
    final LinkedHashMap<String, double[]> curveNodes = new LinkedHashMap<>();
    final LinkedHashMap<String, Interpolator1D> interpolators = new LinkedHashMap<>();
    final ComputationTargetSpecification targetSpec = target.toSpecification();
    final Map<String, Integer> nodesPerCurve = new HashMap<>();
    final HistoricalTimeSeriesBundle timeSeries = getTimeSeriesBundle(inputs, targetSpec, curveCalculationConfigName);
    for (final String curveName : curveNames) {
      final InterpolatedYieldCurveSpecificationWithSecurities spec = getYieldCurveSpecification(inputs, targetSpec, curveName);
      if (spec == null) {
        continue;
      }
      int nInstruments = 0;
      final Interpolator1D interpolator = spec.getInterpolator();
      final SnapshotDataBundle marketData = getMarketData(inputs, targetSpec, curveName);
      final DoubleArrayList nodeTimes = new DoubleArrayList();
      FixedIncomeStripWithSecurity previousStrip = null;
      for (final FixedIncomeStripWithSecurity strip : spec.getStrips()) {
        final Double marketValue = marketData.getDataPoint(strip.getSecurityIdentifier());
        if (marketValue == null) {
          throw new OpenGammaRuntimeException("Could not get market data for " + strip);
        }
        final Security security = strip.getSecurity();
        final String[] curveNamesForSecurity = curveCalculationConfig.getCurveExposureForInstrument(curveName, strip.getInstrumentType());
        final InstrumentDefinition<?> definition = _securityConverter.visit(security);
        final InstrumentDerivative derivative = _definitionConverter.convert(security, definition, now, curveNamesForSecurity, timeSeries);
        if (derivative != null) {
          if (strip.getInstrumentType() == StripInstrumentType.FUTURE) {
            InstrumentDefinition<?> unitNotional;
            if (definition instanceof InterestRateFutureSecurityDefinition) {
              final InterestRateFutureSecurityDefinition securityDefinition = (InterestRateFutureSecurityDefinition) definition;
              unitNotional = new InterestRateFutureTransactionDefinition(securityDefinition, now, marketValue, 1);
            } else {
              unitNotional = ((InterestRateFutureTransactionDefinition) definition).withNewNotionalAndTransactionPrice(1, marketValue);
              // Implementation note: to have the same notional for OTC and futures (and thus not near-singular Jacobian)
            }
            final InstrumentDerivative unitNotionalDerivative = _definitionConverter.convert(security, unitNotional, now, curveNamesForSecurity, timeSeries);
            derivatives.add(unitNotionalDerivative);
            initialRatesGuess.add(1 - marketValue);
          } else {
            derivatives.add(derivative);
            initialRatesGuess.add(marketValue);
          }
          final double t = derivative.accept(LAST_TIME_CALCULATOR);
          if (nInstruments > 0 && CompareUtils.closeEquals(nodeTimes.get(nInstruments - 1), t, 1e-12)) {
            throw new OpenGammaRuntimeException("Strip " + strip + " has same maturity as one already added (" + previousStrip + ") - will lead to" +
                "equal nodes in the curve. Remove one of these strips.");
          }
          nodeTimes.add(t);
          marketValues.add(0.0);
          previousStrip = strip;
          nInstruments++;
        }
      }
      nodesPerCurve.put(curveName, nInstruments);
      curveNodes.put(curveName, nodeTimes.toDoubleArray());
      interpolators.put(curveName, interpolator);
    }
    final YieldCurveBundle knownCurves = getKnownCurves(curveCalculationConfig, targetSpec, inputs);
    final double absoluteTolerance = Double.parseDouble(absoluteToleranceName);
    final double relativeTolerance = Double.parseDouble(relativeToleranceName);
View Full Code Here

      final String shift = shifts.iterator().next();
      shiftMultiplier = 1 + Double.parseDouble(shift);
    } else {
      shiftMultiplier = 1;
    }
    final DoubleArrayList timesList = new DoubleArrayList();
    final DoubleArrayList volsList = new DoubleArrayList();
    for (final Tenor tenor : tenors) {
      final double t = getTime(tenor);
      for (final Pair<Number, FXVolQuoteType> y : fxVolatilitySurface.getYs()) {
        Double volatility = fxVolatilitySurface.getVolatility(tenor, y);
        if (volatility != null) {
          volatility *= shiftMultiplier;
          if (y.getSecond().equals(FXVolQuoteType.ATM)) {
            volsList.add(volatility);
            timesList.add(t);
          }
        }
      }
    }
    if (volsList.size() == 0) {
      throw new OpenGammaRuntimeException("No volatility surface data for FX surface " + target.getUniqueId());
    }
    final ValueProperties.Builder resultProperties = createValueProperties()
        .with(ValuePropertyNames.SURFACE, surfaceName)
        .with(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE, InstrumentTypeProperties.FOREX)
        .with(InterpolatedDataProperties.X_INTERPOLATOR_NAME, interpolatorName)
        .with(InterpolatedDataProperties.LEFT_X_EXTRAPOLATOR_NAME, leftExtrapolatorName)
        .with(InterpolatedDataProperties.RIGHT_X_EXTRAPOLATOR_NAME, rightExtrapolatorName);
    if (shifts != null) {
      resultProperties.with(VolatilitySurfaceShiftFunction.SHIFT, shifts);
    }
    final Interpolator1D interpolator = CombinedInterpolatorExtrapolatorFactory.getInterpolator(interpolatorName, leftExtrapolatorName, rightExtrapolatorName);
    final DoublesCurve volatility = InterpolatedDoublesCurve.fromSorted(timesList.toDoubleArray(), volsList.toDoubleArray(), interpolator);
    final BlackForexTermStructureParameters termStructure = new BlackForexTermStructureParameters(volatility);
    return Collections.singleton(new ComputedValue(new ValueSpecification(ValueRequirementNames.STANDARD_VOLATILITY_SURFACE_DATA, target.toSpecification(),
        resultProperties.get()), termStructure));
  }
View Full Code Here

    //assumes that the sorting is first x, then y
    if (volatilitySurfaceData.size() == 0) {
      throw new OpenGammaRuntimeException("Interest rate future option volatility surface definition name=" + _definitionName + " contains no data");
    }
    final SortedSet<Double> x = volatilitySurfaceData.getUniqueXValues();
    final DoubleArrayList fittedOptionExpiryList = new DoubleArrayList();
    final DoubleArrayList futureDelayList = new DoubleArrayList();
    final DoubleArrayList kappaList = new DoubleArrayList();
    final DoubleArrayList thetaList = new DoubleArrayList();
    final DoubleArrayList vol0List = new DoubleArrayList();
    final DoubleArrayList omegaList = new DoubleArrayList();
    final DoubleArrayList rhoList = new DoubleArrayList();
    final DoubleArrayList chiSqList = new DoubleArrayList();
    final Map<DoublesPair, DoubleMatrix2D> inverseJacobians = new HashMap<DoublesPair, DoubleMatrix2D>();
    for (final Double t : x) {
      final List<ObjectsPair<Double, Double>> strip = volatilitySurfaceData.getYValuesForX(t);
      // FIXME This is bound to break. I changed x/t from an ordinal to an OG-Analytics Year,
      // via TimeCalculator.getTimeBetween(now, IRFutureOptionUtils.getTime(x,now)) where now is the valuationTime. See IRFutureOptionVolatilitySurfaceDataFunction
      final int n = strip.size();
      final DoubleArrayList strikesList = new DoubleArrayList(n);
      final DoubleArrayList sigmaList = new DoubleArrayList(n);
      final DoubleArrayList errorsList = new DoubleArrayList(n);
      final Double futurePrice = futurePriceData.getYValue(t);
      if (strip.size() > 4 && futurePrice != null) {
        final double forward = 1 - futurePrice;
        for (final ObjectsPair<Double, Double> value : strip) {
          if (value.first != null && value.second != null) {
            strikesList.add(1 - value.first / 100);
            sigmaList.add(value.second);
            errorsList.add(ERROR);
          }
        }
        if (!strikesList.isEmpty()) {
          final double[] strikes = strikesList.toDoubleArray();
          final double[] sigma = sigmaList.toDoubleArray();
          final double[] errors = errorsList.toDoubleArray();
          ArrayUtils.reverse(strikes);
          ArrayUtils.reverse(sigma);
          ArrayUtils.reverse(errors);
          final LeastSquareResultsWithTransform fittedResult = new HestonModelFitter(forward, strikes, t, sigma, errors, HESTON_FUNCTION).solve(HESTON_INITIAL_VALUES);
          final DoubleMatrix1D parameters = fittedResult.getModelParameters();
View Full Code Here

    if (fxForwardCurveObject == null) {
      throw new OpenGammaRuntimeException("Could not get FX forward curve data");
    }
    @SuppressWarnings("unchecked")
    final Map<ExternalId, Double> dataPoints = (Map<ExternalId, Double>) fxForwardCurveObject;
    final DoubleArrayList tList = new DoubleArrayList();
    final DoubleArrayList fxList = new DoubleArrayList();
    for (final Tenor tenor : definition.getTenors()) {
      final Double fxForward = dataPoints.get(specification.getCurveInstrumentProvider().getInstrument(now, tenor));
      if (fxForward == null) {
        throw new OpenGammaRuntimeException("Could not get FX forward rate for " + tenor);
      }
      tList.add(DateUtils.getDifferenceInYears(now, now.plus(tenor.getPeriod())));
      fxList.add(fxForward);
    }
    final Interpolator1D interpolator = CombinedInterpolatorExtrapolatorFactory.getInterpolator(Interpolator1DFactory.LINEAR,
        Interpolator1DFactory.LINEAR_EXTRAPOLATOR, Interpolator1DFactory.LINEAR_EXTRAPOLATOR);
    return InterpolatedDoublesCurve.from(tList.toDoubleArray(), fxList.toDoubleArray(), interpolator);
  }
View Full Code Here

          s_logger.warn("Using default initial volatility");
          //throw new OpenGammaRuntimeException("Could not get initial volatility value");
        }
        final Double meanReversion = (Double) meanReversionObject;
        final Double initialVolatility = (Double) initialVolatilityObject;
        final DoubleArrayList volatility = new DoubleArrayList();
        volatility.add(initialVolatility);
        final DoubleArrayList volatilityTime = new DoubleArrayList();
        for (final Map.Entry<Tenor, ExternalId> entry : volatilityTermStructure.entrySet()) {
          final ExternalScheme scheme = entry.getValue().getScheme();
          final String id = entry.getValue().getValue();
          final ExternalId tenorAppendedId = ExternalId.of(scheme, createId(entry.getKey(), id));
          Object volatilityObject = inputs.getValue(new ValueRequirement(MarketDataRequirementNames.MARKET_VALUE,
              ComputationTargetType.PRIMITIVE, tenorAppendedId));
          // Jim - next block is a hack that should be removed.
          if (volatilityObject == null) {
            volatilityObject = VOLATILITY_TERMS.get(entry.getKey());
          }
          if (volatilityObject == null) {
            s_logger.error("Could not get value for " + tenorAppendedId);
          } else {
            final double t = TimeCalculator.getTimeBetween(now, now.plus(entry.getKey().getPeriod()));
            volatility.add((Double) volatilityObject);
            volatilityTime.add(t);
          }
        }
        final HullWhiteOneFactorPiecewiseConstantParameters hullWhiteParameters = new HullWhiteOneFactorPiecewiseConstantParameters(meanReversion, volatility.toDoubleArray(),
            volatilityTime.toDoubleArray());
        return Collections.singleton(new ComputedValue(result, hullWhiteParameters));
      }

      @Override
      public ComputationTargetType getTargetType() {
View Full Code Here

    @SuppressWarnings("unchecked")
    final VolatilitySurfaceData<Double, Double> volatilityData = (VolatilitySurfaceData<Double, Double>) volatilityDataObject;
    if (volatilityData.size() == 0) {
      throw new OpenGammaRuntimeException("Volatility surface data for requirement " + volatilityDataRequirement + " was empty");
    }
    final DoubleArrayList x = new DoubleArrayList();
    final DoubleArrayList y = new DoubleArrayList();
    final DoubleArrayList sigma = new DoubleArrayList();
    final Double[] xData = volatilityData.getXs();
    final Double[] yData = volatilityData.getYs();
    final int n = xData.length;
    for (int i = 0; i < n; i++) {
      final Double vol = volatilityData.getVolatility(xData[i], yData[i]);
      if (vol != null && !CompareUtils.closeEquals(vol, 0)) {
        x.add(xData[i]);
        y.add(yData[i]);
        sigma.add(vol);
      }
    }
    if (x.isEmpty()) {
      throw new OpenGammaRuntimeException("Could not get any data for " + volatilityDataRequirement);
    }
    final Interpolator1D xInterpolator = CombinedInterpolatorExtrapolatorFactory.getInterpolator(xInterpolatorName, leftXExtrapolatorName, rightXExtrapolatorName);
    final Interpolator1D yInterpolator = CombinedInterpolatorExtrapolatorFactory.getInterpolator(yInterpolatorName, leftYExtrapolatorName, rightYExtrapolatorName);
    final GridInterpolator2D interpolator = new GridInterpolator2D(xInterpolator, yInterpolator);
    final Surface<Double, Double, Double> surface = InterpolatedDoublesSurface.from(x.toDoubleArray(), y.toDoubleArray(), sigma.toDoubleArray(), interpolator);
    final VolatilitySurface volatilitySurface = new VolatilitySurface(surface);
    final ValueProperties properties = getResultProperties(surfaceName, instrumentType, leftXExtrapolatorName, rightXExtrapolatorName, xInterpolatorName, leftYExtrapolatorName,
        rightYExtrapolatorName, yInterpolatorName);
    final ValueSpecification spec = new ValueSpecification(ValueRequirementNames.INTERPOLATED_VOLATILITY_SURFACE, target.toSpecification(), properties);
    return Collections.singleton(new ComputedValue(spec, volatilitySurface));
View Full Code Here

    if (volatilitySurfaceData.size() == 0) {
      throw new OpenGammaRuntimeException("Interest rate future option volatility surface definition name=" + futurePriceData.getName() + " contains no data");
    }

    final SortedSet<Double> x = volatilitySurfaceData.getUniqueXValues();
    final DoubleArrayList fittedOptionExpiryList = new DoubleArrayList();
    final DoubleArrayList futureDelayList = new DoubleArrayList();
    final DoubleArrayList kappaList = new DoubleArrayList();
    final DoubleArrayList thetaList = new DoubleArrayList();
    final DoubleArrayList vol0List = new DoubleArrayList();
    final DoubleArrayList omegaList = new DoubleArrayList();
    final DoubleArrayList rhoList = new DoubleArrayList();
    final DoubleArrayList chiSqList = new DoubleArrayList();
    final Map<DoublesPair, DoubleMatrix2D> inverseJacobians = new HashMap<DoublesPair, DoubleMatrix2D>();
    for (final Double t : x) {
      final List<ObjectsPair<Double, Double>> strip = volatilitySurfaceData.getYValuesForX(t);
      final int n = strip.size();
      final DoubleArrayList strikesList = new DoubleArrayList(n);
      final DoubleArrayList sigmaList = new DoubleArrayList(n);
      final DoubleArrayList errorsList = new DoubleArrayList(n);
      final Double futurePrice = futurePriceData.getYValue(t);
      if (strip.size() > 4 && futurePrice != null) {
        final double forward = 1 - futurePrice / 100;
        for (final ObjectsPair<Double, Double> value : strip) {
          if (value.first != null && value.second != null) {
            strikesList.add(1 - value.first / 100);
            sigmaList.add(value.second);
            errorsList.add(ERROR);
          }
        }
        if (!strikesList.isEmpty()) {
          final double[] strikes = strikesList.toDoubleArray();
          final double[] sigma = sigmaList.toDoubleArray();
          final double[] errors = errorsList.toDoubleArray();
          ArrayUtils.reverse(strikes);
          ArrayUtils.reverse(sigma);
          ArrayUtils.reverse(errors);
          final LeastSquareResultsWithTransform fittedResult = new HestonModelFitter(forward, strikes, t, sigma, errors, HESTON_FUNCTION).solve(HESTON_INITIAL_VALUES);
          final DoubleMatrix1D parameters = fittedResult.getModelParameters();
View Full Code Here

    final Double error = Double.parseDouble(desiredValue.getConstraint(PROPERTY_ERROR));
    final DoubleMatrix1D sabrInitialValues = SABRFittingPropertyUtils.getStartingValues(desiredValue);
    final BitSet fixed = SABRFittingPropertyUtils.getFixedValues(desiredValue);
    final Interpolator2D interpolator = SABRFittingPropertyUtils.getInterpolator(desiredValue);
    final SortedSet<Number> timeValues = volatilitySurfaceData.getUniqueXValues();
    final DoubleArrayList fittedOptionExpiryList = new DoubleArrayList();
    final DoubleArrayList futureDelayList = new DoubleArrayList();
    final DoubleArrayList alphaList = new DoubleArrayList();
    final DoubleArrayList betaList = new DoubleArrayList();
    final DoubleArrayList nuList = new DoubleArrayList();
    final DoubleArrayList rhoList = new DoubleArrayList();
    final DoubleArrayList chiSqList = new DoubleArrayList();
    final Map<DoublesPair, DoubleMatrix2D> inverseJacobians = new HashMap<DoublesPair, DoubleMatrix2D>();
    final Map<Double, List<Double>> dataPointsForStrip = new HashMap<Double, List<Double>>();
    for (final Number ttm : timeValues) {
      final List<Double> fittedPointsForStrip = new ArrayList<Double>();
      final List<ObjectsPair<Double, Double>> strip = volatilitySurfaceData.getYValuesForX(ttm);
      final DoubleArrayList errors = new DoubleArrayList();
      final DoubleArrayList strikes = new DoubleArrayList();
      final DoubleArrayList blackVols = new DoubleArrayList();
      if (strip.size() > 4) {
        try {
          final Double forward = futurePriceData.getYValue(ttm.doubleValue());
          for (final ObjectsPair<Double, Double> value : strip) {
            if (value.second != null) {
              strikes.add(1 - value.first);
              blackVols.add(value.second);
              errors.add(error);
              fittedPointsForStrip.add(value.first);
            }
          }
          if (blackVols.size() > 4) {
            final LeastSquareResultsWithTransform fittedResult = new SABRModelFitter(forward, strikes.toDoubleArray(), ttm.doubleValue(), blackVols.toDoubleArray(),
                errors.toDoubleArray(), SABR_FUNCTION).solve(sabrInitialValues, fixed);
            final DoubleMatrix1D parameters = fittedResult.getModelParameters();
            fittedOptionExpiryList.add(ttm.doubleValue());
            futureDelayList.add(0);
            alphaList.add(parameters.getEntry(0));
View Full Code Here

    final Tenor[] tenors = CreditFunctionUtils.getTenors(spreadCurve.getXData());
    final Double[] marketSpreadObjects = CreditFunctionUtils.getSpreads(spreadCurve.getYData());
    ParallelArrayBinarySort.parallelBinarySort(tenors, marketSpreadObjects);
    final int n = tenors.length;
    final List<ZonedDateTime> calibrationTimes = new ArrayList<>();
    final DoubleArrayList marketSpreads = new DoubleArrayList();
    for (int i = 0; i < n; i++) {
      final ZonedDateTime nextIMMDate = IMMDateGenerator.getNextIMMDate(valuationTime, tenors[i]).withHour(0).withMinute(0).withSecond(0).withNano(0);
      if (nextIMMDate.isAfter(cdsOption.getOptionExerciseDate())) {
        calibrationTimes.add(IMMDateGenerator.getNextIMMDate(valuationTime, tenors[i]).withHour(0).withMinute(0).withSecond(0).withNano(0));
        marketSpreads.add(marketSpreadObjects[i]);
      }
    }
    if (calibrationTimes.size() < 2) {
      throw new OpenGammaRuntimeException("Need at least two credit spread points for pricing");
    }
    final ValueProperties properties = Iterables.getOnlyElement(desiredValues).getConstraints().copy()
        .with(ValuePropertyNames.FUNCTION, getUniqueId())
        .get();
    final ISDAYieldCurveAndSpreadsProvider data = new ISDAYieldCurveAndSpreadsProvider(calibrationTimes.toArray(new ZonedDateTime[calibrationTimes.size()]),
        marketSpreads.toDoubleArray(), yieldCurve);
    final HazardRateCurve curve = CALCULATOR.calibrateHazardRateCurve(cdsOption.getUnderlyingCDS(), data, valuationTime);
    final ValueSpecification spec = new ValueSpecification(ValueRequirementNames.HAZARD_RATE_CURVE, target.toSpecification(), properties);
    return Collections.singleton(new ComputedValue(spec, curve));
  }
View Full Code Here

TOP

Related Classes of it.unimi.dsi.fastutil.doubles.DoubleArrayList

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.