List of usage examples for java.lang Math exp
@HotSpotIntrinsicCandidate public static double exp(double a)
From source file:com.opengamma.analytics.financial.model.volatility.local.DermanKaniImpliedBinomialTreeModel.java
@Override public ImpliedTreeResult getImpliedTrees(final OptionDefinition definition, final StandardOptionDataBundle data) { Validate.notNull(definition, "definition"); Validate.notNull(data, "data"); final int m1 = RecombiningBinomialTree.NODES.evaluate(_n); final int m2 = RecombiningBinomialTree.NODES.evaluate(_n - 1); final double[][] impliedTree = new double[_n + 1][m1]; //TODO this wastes space final double[] transitionProbabilities = new double[m2]; double[] arrowDebreu = new double[m1]; final double[][] localVolatilityTree = new double[_n][m2]; final double dt = definition.getTimeToExpiry(data.getDate()) / _n; double t = 0; final double spot = data.getSpot(); impliedTree[0][0] = spot;/*from w w w .j av a2 s. c om*/ arrowDebreu[0] = 1; int previousNodes = 1; final ZonedDateTime date = data.getDate(); for (int i = 1; i < _n + 1; i++) { final int nodes = RecombiningBinomialTree.NODES.evaluate(i); final BinomialOptionModel<StandardOptionDataBundle> crrModel = new BinomialOptionModel<>(CRR, i); t += dt; final double df1 = Math.exp(dt * data.getInterestRate(t)); final double df2 = Math.exp(dt * data.getCostOfCarry()); final Expiry expiry = new Expiry(DateUtils.getDateOffsetWithYearFraction(date, t)); final int mid = i / 2; if (i % 2 == 0) { impliedTree[i][mid] = spot; addUpperNodes(data, impliedTree, arrowDebreu, i, crrModel, df1, df2, expiry, mid + 1); addLowerNodes(data, impliedTree, arrowDebreu, i, crrModel, df1, df2, expiry, mid - 1); } else { final double c = crrModel .getTreeGeneratingFunction(new EuropeanVanillaOptionDefinition(spot, expiry, true)) .evaluate(data).getNode(0, 0).second; final double sigma = getUpperSigma(impliedTree, arrowDebreu, i - 1, df2, mid + 1); impliedTree[i][mid + 1] = spot * (df1 * c + arrowDebreu[mid] * spot - sigma) / (arrowDebreu[mid] * impliedTree[i - 1][mid] * df2 - df1 * c + sigma); impliedTree[i][mid] = spot * spot / impliedTree[i][mid + 1]; addUpperNodes(data, impliedTree, arrowDebreu, i, crrModel, df1, df2, expiry, mid + 2); addLowerNodes(data, impliedTree, arrowDebreu, i, crrModel, df1, df2, expiry, mid - 1); } for (int j = 0; j < previousNodes; j++) { final double f = impliedTree[i - 1][j] * df2; transitionProbabilities[j] = (f - impliedTree[i][j]) / (impliedTree[i][j + 1] - impliedTree[i][j]); //TODO emcleod 31-8-10 Need to check that transition probabilities are positive - use adjustment suggested in "The Volatility Smile and its Implied Tree" localVolatilityTree[i - 1][j] = Math .sqrt(transitionProbabilities[j] * (1 - transitionProbabilities[j])) * Math.log(impliedTree[i][j + 1] / impliedTree[i][j]); //TODO need 1/sqrt(dt) here } final double[] temp = new double[m1]; temp[0] = (1 - transitionProbabilities[0]) * arrowDebreu[0] / df1; temp[nodes - 1] = (transitionProbabilities[previousNodes - 1] * arrowDebreu[previousNodes - 1]) / df1; for (int j = 1; j < nodes - 1; j++) { temp[j] = (transitionProbabilities[j - 1] * arrowDebreu[j - 1] + (1 - transitionProbabilities[j]) * arrowDebreu[j]) / df1; } arrowDebreu = temp; previousNodes = nodes; } final Double[][] impliedTreeResult = new Double[_n + 1][m1]; final Double[][] localVolResult = new Double[_n][m2]; for (int i = 0; i < impliedTree.length; i++) { for (int j = 0; j < impliedTree[i].length; j++) { impliedTreeResult[i][j] = impliedTree[i][j]; if (i < _n && j < m2) { localVolResult[i][j] = localVolatilityTree[i][j]; } } } return new ImpliedTreeResult(new RecombiningBinomialTree<>(impliedTreeResult), new RecombiningBinomialTree<>(localVolResult)); }
From source file:com.datumbox.framework.statistics.distributions.ContinuousDistributions.java
/** * It estimates a numeric approximation of gamma function. * //from www .j a va 2s . com * @param x The input x * @return The value of gamma(x) */ public static double gamma(double x) { return Math.exp(LogGamma(x)); }
From source file:edu.stanford.cfuller.imageanalysistools.fitting.GaussianFitter3D.java
private static double gaussian(double x, double y, double z, double[] parameters) { double xmx0 = x - parameters[3]; double ymy0 = y - parameters[4]; double zmz0 = z - parameters[5]; double vxy = parameters[1]; double vz = parameters[2]; double A = parameters[0]; double b = parameters[6]; return (A * Math.exp(-(xmx0 * xmx0 + ymy0 * ymy0) / (2 * vxy * vxy) - zmz0 * zmz0 / (2 * vz * vz)) + b); }
From source file:com.opengamma.analytics.financial.model.volatility.BlackScholesFormulaRepository.java
/** * The <b>spot</b> price// ww w .j av a2 s. com * @param spot The spot value of the underlying * @param strike The Strike * @param timeToExpiry The time-to-expiry * @param lognormalVol The log-normal volatility * @param interestRate The interest rate * @param costOfCarry The cost-of-carry rate * @param isCall True for calls, false for puts * @return The <b>spot</b> price */ @ExternalFunction public static double price(final double spot, final double strike, final double timeToExpiry, final double lognormalVol, final double interestRate, final double costOfCarry, final boolean isCall) { ArgumentChecker.isTrue(spot >= 0.0, "negative/NaN spot; have {}", spot); ArgumentChecker.isTrue(strike >= 0.0, "negative/NaN strike; have {}", strike); ArgumentChecker.isTrue(timeToExpiry >= 0.0, "negative/NaN timeToExpiry; have {}", timeToExpiry); ArgumentChecker.isTrue(lognormalVol >= 0.0, "negative/NaN lognormalVol; have {}", lognormalVol); ArgumentChecker.isFalse(Double.isNaN(interestRate), "interestRate is NaN"); ArgumentChecker.isFalse(Double.isNaN(costOfCarry), "costOfCarry is NaN"); if (interestRate > LARGE) { return 0.; } if (-interestRate > LARGE) { return Double.POSITIVE_INFINITY; } double discount = Math.abs(interestRate) < SMALL ? 1. : Math.exp(-interestRate * timeToExpiry); if (costOfCarry > LARGE) { return isCall ? Double.POSITIVE_INFINITY : 0.; } if (-costOfCarry > LARGE) { final double res = isCall ? 0. : (discount > SMALL ? strike * discount : 0.); return Double.isNaN(res) ? discount : res; } double factor = Math.exp(costOfCarry * timeToExpiry); if (spot > LARGE * strike) { final double tmp = Math.exp((costOfCarry - interestRate) * timeToExpiry); return isCall ? (tmp > SMALL ? spot * tmp : 0.) : 0.; } if (LARGE * spot < strike) { return (isCall || discount < SMALL) ? 0. : strike * discount; } if (spot > LARGE && strike > LARGE) { final double tmp = Math.exp((costOfCarry - interestRate) * timeToExpiry); return isCall ? (tmp > SMALL ? spot * tmp : 0.) : (discount > SMALL ? strike * discount : 0.); } final double rootT = Math.sqrt(timeToExpiry); double sigmaRootT = lognormalVol * rootT; if (Double.isNaN(sigmaRootT)) { sigmaRootT = 1.; //ref value is returned } final int sign = isCall ? 1 : -1; final double rescaledSpot = factor * spot; if (sigmaRootT < SMALL) { final double res = isCall ? (rescaledSpot > strike ? discount * (rescaledSpot - strike) : 0.) : (rescaledSpot < strike ? discount * (strike - rescaledSpot) : 0.); return Double.isNaN(res) ? sign * (spot - discount * strike) : res; } double d1 = 0.; double d2 = 0.; if (Math.abs(spot - strike) < SMALL || sigmaRootT > LARGE) { final double coefD1 = (costOfCarry / lognormalVol + 0.5 * lognormalVol); final double coefD2 = (costOfCarry / lognormalVol - 0.5 * lognormalVol); final double tmpD1 = coefD1 * rootT; final double tmpD2 = coefD2 * rootT; d1 = Double.isNaN(tmpD1) ? 0. : tmpD1; d2 = Double.isNaN(tmpD2) ? 0. : tmpD2; } else { final double tmp = costOfCarry * rootT / lognormalVol; final double sig = (costOfCarry >= 0.) ? 1. : -1.; final double scnd = Double.isNaN(tmp) ? ((lognormalVol < LARGE && lognormalVol > SMALL) ? sig / lognormalVol : sig * rootT) : tmp; d1 = Math.log(spot / strike) / sigmaRootT + scnd + 0.5 * sigmaRootT; d2 = d1 - sigmaRootT; } // if (Double.isNaN(d1) || Double.isNaN(d2)) { // throw new IllegalArgumentException("NaN found"); // } final double res = sign * discount * (rescaledSpot * NORMAL.getCDF(sign * d1) - strike * NORMAL.getCDF(sign * d2)); return Double.isNaN(res) ? 0. : Math.max(res, 0.); }
From source file:com.qaant.optionModels.QWhaley.java
private void wWhaley() { pModelName = "Whaley QAANT"; modelNumber = 2;//from w w w . j av a 2 s . c om tipoEjercicio = AMERICAN; // q=(tipoContrato==STOCK) ? dividendRate:rate; //q: si es una accion q es el dividendo, si es un futuro q se toma la rate para descontar el valor futr a presente //Se hace este reemplazo para poder usar la misma form en STOCK y FUTURO double xx; switch (tipoContrato) { case STOCK: q = dividendRate; b = rate; break; case FUTURES: q = rate; b = 0; break; } double vlt2 = volatModel * volatModel; double VltSqrDayYear = volatModel * sqrDayYear; double h = 1 - z; //descuento para valor presente double alfa = 2 * rate / vlt2; double beta = 2 * (b - q) / vlt2; double lambda = (-(beta - 1) + cpFlag * Math.sqrt((beta - 1) * (beta - 1) + 4 * alfa / h)) / 2; double eex = Math.exp(-q * dayYear);//descuento por dividendos double s1 = strike; double zz = 1 / Math.sqrt(2 * Math.PI); double zerror = 1; do { double d1 = (Math.log(s1 / strike) + ((rate - q) + vlt2 / 2) * dayYear) / VltSqrDayYear; xx = (1 - eex * new NormalDistribution().cumulativeProbability(cpFlag * d1)); double corr = s1 / lambda * xx; QBlackScholes option = new QBlackScholes(tipoContrato, s1, volatModel, dividendRate, callPut, strike, daysToExpiration, rate, 0); double mBlackScholes = option.getPrima(); double rhs = mBlackScholes + cpFlag * corr; double lhs = cpFlag * (s1 - strike); zerror = lhs - rhs; double nd1 = zz * Math.exp(-0.5 * d1 * d1); //standard normal prob? double slope = cpFlag * (1 - 1 / lambda) * xx + 1 / lambda * (eex * nd1) * 1 / VltSqrDayYear; s1 = s1 - zerror / slope; } while (Math.abs(zerror) > 0.000001); double a = cpFlag * s1 / lambda * xx; switch (callPut) { case CALL: //Call if (underlyingValue >= s1) { prima = underlyingValue - strike; } else { prima += a * Math.pow((underlyingValue / s1), lambda); } break; case PUT: //Put if (underlyingValue <= s1) { prima = strike - underlyingValue; } else { prima += a * Math.pow((underlyingValue / s1), lambda); } //prima=10.1; break; } }
From source file:com.datumbox.framework.core.statistics.distributions.ContinuousDistributions.java
/** * It estimates a numeric approximation of gamma function. * //from w w w.j av a 2s .c om * @param x The input x * @return The value of gamma(x) */ public static double gamma(double x) { return Math.exp(logGamma(x)); }
From source file:com.opengamma.analytics.financial.equity.future.pricing.EquityFutureCostOfCarry.java
/** * @param future EquityFuture derivative * @param dataBundle Contains funding curve, spot value and continuous dividend yield * @return The change in the present value given a unit value change in the discount rate *///from w ww .j a v a 2s .c o m @Override public double ratesDelta(final EquityFuture future, final EquityFutureDataBundle dataBundle) { Validate.notNull(future, "Future"); Validate.notNull(dataBundle); Validate.notNull(dataBundle.getCostOfCarry()); Validate.notNull(dataBundle.getSpotValue()); double fwdPrice = dataBundle.getSpotValue() * Math.exp(dataBundle.getCostOfCarry() * future.getTimeToSettlement()); return future.getTimeToSettlement() * fwdPrice * future.getUnitAmount(); }
From source file:com.opengamma.analytics.financial.model.option.pricing.analytic.AsymmetricPowerOptionModel.java
/** * {@inheritDoc}/*from ww w. jav a 2 s . c o m*/ */ @Override public Function1D<StandardOptionDataBundle, Double> getPricingFunction( final AsymmetricPowerOptionDefinition definition) { Validate.notNull(definition); final Function1D<StandardOptionDataBundle, Double> pricingFunction = new Function1D<StandardOptionDataBundle, Double>() { @SuppressWarnings("synthetic-access") @Override public Double evaluate(final StandardOptionDataBundle data) { Validate.notNull(data); final double s = data.getSpot(); final double k = definition.getStrike(); final double t = definition.getTimeToExpiry(data.getDate()); final double sigma = data.getVolatility(t, k); final double r = data.getInterestRate(t); final double b = data.getCostOfCarry(); final double power = definition.getPower(); final double sigmaT = sigma * Math.sqrt(t); final double d1 = (Math.log(s / Math.pow(k, 1. / power)) + t * (b + sigma * sigma * (power - 0.5))) / sigmaT; final double d2 = d1 - power * sigmaT; final int sign = definition.isCall() ? 1 : -1; final double df1 = Math .exp(((power - 1) * (r + power * sigma * sigma * 0.5) - power * (r - b)) * t); final double df2 = Math.exp(-r * t); return sign * (Math.pow(s, power) * df1 * NORMAL.getCDF(sign * d1) - df2 * k * NORMAL.getCDF(sign * d2)); } }; return pricingFunction; }
From source file:com.opengamma.analytics.financial.interestrate.annuity.ZSpreadCalculator.java
public double calculatePriceForZSpread(final Annuity<? extends Payment> annuity, final YieldCurveBundle curves, final double zSpread) { Validate.notNull(annuity, "annuity"); Validate.notNull(curves, "curves"); double sum = 0; final int n = annuity.getNumberOfPayments(); Payment payment;//from w w w .j a va 2 s .com for (int i = 0; i < n; i++) { payment = annuity.getNthPayment(i); final double temp = PRESENT_VALUE_CALCULATOR.visit(payment, curves); sum += temp * Math.exp(-zSpread * payment.getPaymentTime()); } return sum; }
From source file:br.ufrgs.enq.jcosmo.test.VLEdiagrams.java
@SuppressWarnings("deprecation") public JPanel calcEthTol() throws Exception { super.setTitle("P vs x1"); double T = 60; setLayout(new BorderLayout()); COSMOSACDataBase db = COSMOSACDataBase.getInstance(); COSMOSACCompound comps[] = new COSMOSACCompound[2]; comps[0] = db.getComp("ethanol"); comps[1] = db.getComp("toluene"); COSMOSAC cosmosac = new COSMOSAC(); cosmosac.setComponents(comps);// ww w . j av a 2 s . c o m cosmosac.setTemperature(T + 273.15); double[] x1 = new double[n]; double[] x2 = new double[n]; double[] gamma1 = new double[n]; double[] gamma2 = new double[n]; double[] z = new double[2]; double[] lnGamma = new double[2]; z[0] = 0.00; int j = 0; while (z[0] < 1.0001) { z[1] = 1 - z[0]; x1[j] = z[0]; x2[j] = z[1]; cosmosac.setComposition(z); cosmosac.activityCoefficient(lnGamma); gamma1[j] = Math.exp(lnGamma[0]); gamma2[j] = Math.exp(lnGamma[1]); z[0] += 0.05; j++; } double[][] parAntoine = new double[3][3]; parAntoine[0][0] = 16.8958; parAntoine[0][1] = 3795.17; parAntoine[0][2] = 230.918; parAntoine[1][0] = 13.9320; parAntoine[1][1] = 3056.96; parAntoine[1][2] = 217.625; double[] Psat = pSat(parAntoine, T); double[] P = calcPx(x1, x2, gamma1, gamma2, Psat); double[] y1 = calcY(x1, gamma1, Psat, P); XYPlot plot1; XYSeriesCollection dataset = new XYSeriesCollection(); XYSeries liq = new XYSeries("liquid"); XYSeries vap = new XYSeries("vapor"); XYSeries raoult = new XYSeries("Raoult's Law"); for (int i = 0; i < n; i++) { liq.add(x1[i], P[i]); vap.add(y1[i], P[i]); } raoult.add(0, Psat[1]); raoult.add(1, Psat[0]); dataset.addSeries(liq); dataset.addSeries(vap); dataset.addSeries(raoult); JFreeChart chart = ChartFactory.createXYLineChart(null, "Mole Fraction: x1, y1", "P/KPa", null, PlotOrientation.VERTICAL, true, true, false); plot1 = (XYPlot) chart.getPlot(); plot1.getDomainAxis().setRange(new Range(0.0, 1.0)); plot1.getRangeAxis().setRange(new Range(15.0, 50.0)); plot1.setDataset(dataset); XYSplineRenderer r = new XYSplineRenderer(); BasicStroke stroke = new BasicStroke(2f); r.setStroke(stroke); plot1.setRenderer(r); r.setBaseShapesVisible(false); ChartPanel chartPanel = new ChartPanel(chart); JPanel jp = new JPanel(new BorderLayout()); jp.add(chartPanel); add(jp, BorderLayout.CENTER); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400, 500); return jp; }