Package it.unimi.dsi.fastutil.doubles

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


      shiftMultiplier = 1;
    }
    for (int i = 0; i < tenors.length; i++) {
      final Tenor tenor = tenors[i];
      final double t = getTime(tenor);
      final DoubleArrayList deltas = new DoubleArrayList();
      final DoubleArrayList volatilities = new DoubleArrayList();
      for (int j = 0; j < nSmileValues; j++) {
        final Double delta = deltaValues[j];
        if (delta != null) {
          Double volatility = fxVolatilitySurface.getVolatility(tenor, delta);
          if (volatility != null) {
            volatility *= shiftMultiplier;
            if (delta < 50) {
              deltas.add(getTransformedDelta(delta));
            }
            volatilities.add(volatility);
          }
        } else {
          s_logger.info("Had a null value for tenor number " + j);
        }
      }
      smile[i] = new SmileDeltaParameters(t, deltas.toDoubleArray(), volatilities.toDoubleArray());
    }
    final Interpolator1D interpolator = CombinedInterpolatorExtrapolatorFactory.getInterpolator(interpolatorName, leftExtrapolatorName, rightExtrapolatorName);
    final SmileDeltaTermStructureParametersStrikeInterpolation smiles = new SmileDeltaTermStructureParametersStrikeInterpolation(smile, interpolator);
    final ValueProperties.Builder resultProperties = createValueProperties()
        .with(ValuePropertyNames.SURFACE, surfaceName)
View Full Code Here


        final Double firstMeanReversion = (Double) firstMeanReversionObject;
        final Double secondMeanReversion = (Double) secondMeanReversionObject;
        final Double firstInitialVolatility = (Double) firstInitialVolatilityObject;
        final Double secondInitialVolatility = (Double) secondInitialVolatilityObject;
        final Double correlation = (Double) correlationObject;
        final DoubleArrayList firstVolatility = new DoubleArrayList();
        firstVolatility.add(firstInitialVolatility);
        final DoubleArrayList secondVolatility = new DoubleArrayList();
        secondVolatility.add(secondInitialVolatility);
        final DoubleArrayList volatilityTime = new DoubleArrayList();
        for (final Map.Entry<Tenor, Pair<ExternalId, ExternalId>> entry : volatilityTermStructure.entrySet()) {
          final ExternalScheme firstScheme = entry.getValue().getFirst().getScheme();
          final ExternalScheme secondScheme = entry.getValue().getSecond().getScheme();
          final String firstId = entry.getValue().getFirst().getValue();
          final String secondId = entry.getValue().getSecond().getValue();
          final ExternalId firstTenorAppendedId = ExternalId.of(firstScheme, createId(entry.getKey(), firstId));
          final ExternalId secondTenorAppendedId = ExternalId.of(secondScheme, createId(entry.getKey(), secondId));
          final Object firstVolatilityObject = inputs.getValue(new ValueRequirement(MarketDataRequirementNames.MARKET_VALUE,
              ComputationTargetType.PRIMITIVE, firstTenorAppendedId));
          final Object secondVolatilityObject = inputs.getValue(new ValueRequirement(MarketDataRequirementNames.MARKET_VALUE,
              ComputationTargetType.PRIMITIVE, secondTenorAppendedId));
          if (firstVolatilityObject == null) {
            s_logger.error("Could not get value for " + firstTenorAppendedId);
            continue;
          }
          if (secondVolatilityObject == null) {
            s_logger.error("Could not get value for " + secondTenorAppendedId);
          } else {
            final double t = TimeCalculator.getTimeBetween(now, now.plus(entry.getKey().getPeriod()));
            firstVolatility.add((Double) firstVolatilityObject);
            secondVolatility.add((Double) secondVolatilityObject);
            volatilityTime.add(t);
          }
        }
        final G2ppPiecewiseConstantParameters g2ppParameters = new G2ppPiecewiseConstantParameters(new double[] {firstMeanReversion, secondMeanReversion},
            new double[][] {firstVolatility.toDoubleArray(), secondVolatility.toDoubleArray()}, volatilityTime.toDoubleArray(), correlation);
        return Collections.singleton(new ComputedValue(result, g2ppParameters));
      }

      @Override
      public ComputationTargetType getTargetType() {
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(definition.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 = desiredValues.iterator().next().getConstraints().copy()
        .with(ValuePropertyNames.FUNCTION, getUniqueId())
        .get();
    return getComputedValue(definition, yieldCurve, volatility, calibrationTimes.toArray(new ZonedDateTime[calibrationTimes.size()]),
        marketSpreads.toDoubleArray(), hazardRateCurve, valuationTime, target, properties);
  }
View Full Code Here

    final ConfigSource configSource = OpenGammaExecutionContext.getConfigSource(executionContext);
    final MultiCurveCalculationConfig curveCalculationConfig = new ConfigDBCurveCalculationConfigSource(configSource).getConfig(curveCalculationConfigName);
    final ComputationTargetSpecification targetSpec = target.toSpecification();
    final YieldCurveBundle knownCurves = getKnownCurves(curveCalculationConfig, targetSpec, inputs);
    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 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.getSecurityIdentifier());
        }
        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) {
            final InterestRateFutureSecurityDefinition securityDefinition = (InterestRateFutureSecurityDefinition) definition;
            InterestRateFutureTransactionDefinition unitNotional = new InterestRateFutureTransactionDefinition(securityDefinition, now, marketValue, 1);
            unitNotional = unitNotional.withNewNotionalAndTransactionPrice(1, marketValue);
            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 double absoluteTolerance = Double.parseDouble(absoluteToleranceName);
    final double relativeTolerance = Double.parseDouble(relativeToleranceName);
    final int iterations = Integer.parseInt(iterationsName);
View Full Code Here

        final String rightExtrapolatorName = interpolatedDefinition.getRightExtrapolatorName();
        final Interpolator1D interpolator = CombinedInterpolatorExtrapolatorFactory.getInterpolator(interpolatorName, leftExtrapolatorName, rightExtrapolatorName);
        if (definition instanceof FixedDateInterpolatedCurveDefinition) {
          final FixedDateInterpolatedCurveDefinition fixedDateDefinition = (FixedDateInterpolatedCurveDefinition) definition;
          final List<LocalDate> fixedDates = fixedDateDefinition.getFixedDates();
          final DoubleArrayList nodePoints = new DoubleArrayList(fixedDates.size()); //TODO what about equal node points?
          for (final LocalDate fixedDate : fixedDates) {
            nodePoints.add(TimeCalculator.getTimeBetween(valuationDate, fixedDate)); //TODO what to do if the fixed date is before the valuation date?
          }
          final double anchor = nodePoints.get(0); //TODO should the anchor go into the definition?
          return new GeneratorCurveYieldInterpolatedAnchorNode(nodePoints.toDoubleArray(), anchor, interpolator);
        }
        return new GeneratorCurveYieldInterpolated(getMaturityCalculator(), interpolator);
      }
      throw new OpenGammaRuntimeException("Cannot handle curves of type " + definition.getClass());
    }
View Full Code Here

      throw new OpenGammaRuntimeException("Could not get FX forward market data");
    }
    final YieldAndDiscountCurve foreignCurve = (YieldAndDiscountCurve) foreignCurveObject;
    @SuppressWarnings("unchecked")
    final Map<ExternalId, Double> fxForwardData = (Map<ExternalId, Double>) dataObject;
    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;
    final HolidaySource holidaySource = OpenGammaExecutionContext.getHolidaySource(executionContext);
    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 ExternalId conventionSettlementRegion = fxSpotConvention.getSettlementRegion();
    ZonedDateTime spotDate;
    if (spotLag == 0 && conventionSettlementRegion == null) {
      spotDate = now; //This preserves the old behaviour that ignored holidays and settlement days.
    } else {
      spotDate = ScheduleCalculator.getAdjustedDate(now, spotLag, calendar);
    }
    for (final Tenor tenor : definition.getTenors()) {
      final ExternalId identifier = provider.getInstrument(now.toLocalDate(), tenor);
      if (fxForwardData.containsKey(identifier)) {
        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 {
          paymentDate = ScheduleCalculator.getAdjustedDate(spotDate, tenor.getPeriod(), MOD_FOL, calendar, true);
        }
        final double paymentTime = TimeCalculator.getTimeBetween(now, paymentDate);
        final double forwardFX = invertFXQuotes ? 1 / fxForwardData.get(identifier) : fxForwardData.get(identifier);
        derivatives.add(getFXForward(domesticCurrency, foreignCurrency, paymentTime, spotFX, forwardFX, fullDomesticCurveName, fullForeignCurveName));
        marketValues.add(forwardFX);
        nodeTimes.add(paymentTime);
        if (nInstruments > 1 && CompareUtils.closeEquals(nodeTimes.get(nInstruments - 1), paymentTime, 1e-12)) {
          throw new OpenGammaRuntimeException("FX forward with tenor " + tenor + " has already been added - will lead to equal nodes in the curve. Remove one of these tenors.");
        }
        nInstruments++;
        initialRatesGuess.add(0.02);
      }
    }
    final YieldCurveBundle knownCurve = new YieldCurveBundle(new String[] {fullForeignCurveName }, new YieldAndDiscountCurve[] {foreignCurve });
    final LinkedHashMap<String, double[]> curveKnots = new LinkedHashMap<>();
    curveKnots.put(fullDomesticCurveName, nodeTimes.toDoubleArray());
    final LinkedHashMap<String, double[]> curveNodes = new LinkedHashMap<>();
    final LinkedHashMap<String, Interpolator1D> interpolators = new LinkedHashMap<>();
    final CombinedInterpolatorExtrapolator interpolator = CombinedInterpolatorExtrapolatorFactory.getInterpolator(interpolatorName, leftExtrapolatorName,
        rightExtrapolatorName);
    curveNodes.put(fullDomesticCurveName, nodeTimes.toDoubleArray());
    interpolators.put(fullDomesticCurveName, interpolator);
    final FXMatrix fxMatrix = new FXMatrix();
    fxMatrix.addCurrency(foreignCurrency, domesticCurrency, spotFX);
    final MultipleYieldCurveFinderDataBundle data = new MultipleYieldCurveFinderDataBundle(derivatives, marketValues.toDoubleArray(), knownCurve, curveNodes,
        interpolators, useFiniteDifference, fxMatrix);
    final NewtonVectorRootFinder rootFinder = new BroydenVectorRootFinder(absoluteTolerance, relativeTolerance, iterations, decomposition);
    final Function1D<DoubleMatrix1D, DoubleMatrix1D> curveCalculator = new MultipleYieldCurveFinderFunction(data, PAR_RATE_CALCULATOR);
    final Function1D<DoubleMatrix1D, DoubleMatrix2D> jacobianCalculator = new MultipleYieldCurveFinderJacobian(data, PAR_RATE_SENSITIVITY_CALCULATOR);
    final double[] fittedYields = rootFinder.getRoot(curveCalculator, jacobianCalculator, new DoubleMatrix1D(initialRatesGuess.toDoubleArray())).getData();
    final DoubleMatrix2D jacobianMatrix = jacobianCalculator.evaluate(new DoubleMatrix1D(fittedYields));
    final YieldCurve curve = YieldCurve.from(InterpolatedDoublesCurve.from(nodeTimes.toDoubleArray(), fittedYields, interpolator));
    final ComputationTargetSpecification targetSpec = target.toSpecification();
    final ValueProperties curveProperties = getCurveProperties(curveCalculationConfigName, domesticCurveName, absoluteToleranceName, relativeToleranceName,
        iterationsName, decompositionName, useFiniteDifferenceName, interpolatorName, leftExtrapolatorName, rightExtrapolatorName);
View Full Code Here

    }
    final VolatilityCubeData volatilityCubeData = (VolatilityCubeData) objectCubeData;
    final SortedMap<Tenor, SortedMap<Tenor, Pair<double[], double[]>>> smiles = volatilityCubeData.getSmiles();
    final SortedMap<Tenor, SortedMap<Tenor, ExternalId[]>> smileIds = volatilityCubeData.getSmileIds();
    final SortedMap<Tenor, SortedMap<Tenor, Double[]>> smileRelativeStrikes = volatilityCubeData.getSmileRelativeStrikes();
    final DoubleArrayList swapMaturitiesList = new DoubleArrayList();
    final DoubleArrayList swaptionExpiriesList = 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<>();
    final Map<Pair<Tenor, Tenor>, ExternalId[]> fittedSmileIds = new HashMap<>();
    final Map<Pair<Tenor, Tenor>, Double[]> fittedRelativeStrikes = new HashMap<>();
    for (final Map.Entry<Tenor, SortedMap<Tenor, Pair<double[], double[]>>> swapMaturityEntry : smiles.entrySet()) {
      final double maturity = getTime(swapMaturityEntry.getKey());
      for (final Map.Entry<Tenor, Pair<double[], double[]>> swaptionExpiryEntry : swapMaturityEntry.getValue().entrySet()) {
        final double swaptionExpiry = getTime(swaptionExpiryEntry.getKey());
        final double[] strikes = swaptionExpiryEntry.getValue().getFirst();
        final double[] blackVols = swaptionExpiryEntry.getValue().getSecond();
        final int n = strikes.length;
        if (n != blackVols.length) {
          throw new OpenGammaRuntimeException("Strike and Black volatility arrays were not the same length; should never happen");
        }
        ExternalId[] externalIds = new ExternalId[0];
        if (smileIds != null) {
          externalIds = smileIds.get(swapMaturityEntry.getKey()).get(swaptionExpiryEntry.getKey());
          if (n != externalIds.length) {
            throw new OpenGammaRuntimeException("Strike and id arrays were not the same length; should never happen");
          }
        }
        Double[] relativeStrikes = new Double[0];
        if (smileRelativeStrikes != null) {
          relativeStrikes = smileRelativeStrikes.get(swapMaturityEntry.getKey()).get(swaptionExpiryEntry.getKey());
          if (n != relativeStrikes.length) {
            throw new OpenGammaRuntimeException("Strike and relative strike arrays were not the same length; should never happen");
          }
        }
        final double[] errors = new double[n];
        final Pair<Tenor, Tenor> tenorPair = Pair.of(swapMaturityEntry.getKey(), swaptionExpiryEntry.getKey());
        if (volatilityCubeData.getATMStrikes() != null && volatilityCubeData.getATMStrikes().containsKey(tenorPair)) {
          final double forward = volatilityCubeData.getATMStrikes().get(tenorPair);
          for (int k = 0; k < n; k++) {
            errors[k] = ERROR;
          }
          if (strikes.length > 4 && forward > 0) { //don't fit those smiles with insufficient data
            final LeastSquareResultsWithTransform fittedResult = new SABRModelFitter(forward, strikes, swaptionExpiry, blackVols, errors, SABR_FUNCTION).solve(SABR_INITIAL_VALUES, FIXED);
            final DoubleMatrix1D parameters = fittedResult.getModelParameters();
            swapMaturitiesList.add(maturity);
            swaptionExpiriesList.add(swaptionExpiry);
            alphaList.add(parameters.getEntry(0));
            betaList.add(parameters.getEntry(1));
            rhoList.add(parameters.getEntry(2));
            nuList.add(parameters.getEntry(3));
            final DoublesPair expiryMaturityPair = new DoublesPair(swaptionExpiry, maturity);
            inverseJacobians.put(expiryMaturityPair, fittedResult.getModelParameterSensitivityToData());
            chiSqList.add(fittedResult.getChiSq());
            fittedSmileIds.put(tenorPair, externalIds);
            fittedRelativeStrikes.put(tenorPair, relativeStrikes);
          }
        }
      }
View Full Code Here

    ArgumentChecker.isTrue(meanReversion.length == 2, "Two mean reversions required");
    ArgumentChecker.isTrue(volatility.length == 2, "Two volatility arrays required");
    ArgumentChecker.isTrue(volatility[0].length == volatility[1].length, "Volatility length");
    ArgumentChecker.isTrue(volatility[0].length == volatilityTime.length + 1, "Number of times incorrect; had {}, need {}", volatilityTime.length + 1, volatility[0].length);
    _meanReversion = meanReversion;
    _volatility[0] = new DoubleArrayList(volatility[0]);
    _volatility[1] = new DoubleArrayList(volatility[1]);
    final double[] volatilityTimeArray = new double[volatilityTime.length + 2];
    volatilityTimeArray[0] = 0.0;
    volatilityTimeArray[volatilityTime.length + 1] = VOLATILITY_TIME_INFINITY;
    System.arraycopy(volatilityTime, 0, volatilityTimeArray, 1, volatilityTime.length);
    _volatilityTime = new DoubleArrayList(volatilityTimeArray);
    // TODO: check that the time are increasing.
    _correlation = correlation;
  }
View Full Code Here

   */
  public void setVolatility(final double[][] volatility) {
    ArgumentChecker.isTrue(volatility.length == 2, "Two volatility arrays required");
    ArgumentChecker.isTrue(volatility[0].length == volatility[1].length, "Volatility length");
    ArgumentChecker.isTrue(volatility[0].length == _volatilityTime.size() - 1, "Volatility length");
    _volatility[0] = new DoubleArrayList(volatility[0]);
    _volatility[1] = new DoubleArrayList(volatility[1]);
  }
View Full Code Here

   */
  public HullWhiteOneFactorPiecewiseConstantParameters(final double meanReversion, final double[] volatility, final double[] volatilityTime) {
    ArgumentChecker.notNull(volatility, "volatility time");
    ArgumentChecker.notNull(volatilityTime, "volatility time");
    _meanReversion = meanReversion;
    _volatility = new DoubleArrayList(volatility);
    final double[] volatilityTimeArray = new double[volatilityTime.length + 2];
    volatilityTimeArray[0] = 0.0;
    volatilityTimeArray[volatilityTime.length + 1] = VOLATILITY_TIME_INFINITY;
    System.arraycopy(volatilityTime, 0, volatilityTimeArray, 1, volatilityTime.length);
    _volatilityTime = new DoubleArrayList(volatilityTimeArray);
    // TODO: check that the time are increasing.
  }
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.