public static double ValueSwap(IRSwap swap, Date valueDate, IDiscountingSource curve) { // Get the required objects off the map var index = swap.GetFloatingIndex(); // Calculate the first fixing off the curve to use at all past dates. var df1 = curve.GetDF(valueDate); var laterDate = valueDate.AddTenor(index.Tenor); var df2 = curve.GetDF(laterDate); var dt = (laterDate - valueDate) / 365.0; var rate = (df1 / df2 - 1) / dt; //Set up the valuation engine. IFloatingRateSource forecastCurve = new ForecastCurveFromDiscount(curve, index, new FloatingRateFixingCurve1Rate(valueDate, rate, index)); var curveSim = new DeterministicCurves(curve); curveSim.AddRateForecast(forecastCurve); var coordinator = new Coordinator(curveSim, new List <Simulator>(), 1); // Run the valuation var value = coordinator.Value(new Product[] { swap }, valueDate); return(value); }
public static double ValueZARSwap1Curve([ExcelArgument(Description = "The name of the swap.")] IRSwap swap, [ExcelArgument(Description = "The date on which valuation is required. Cannot be before the anchor date of the curve.")] Date valueDate, [ExcelArgument(Description = "The discounting curve. Will also be used for forecasting Jibar and providing the most recent required Jibar fix.")] IDiscountingSource curve) { // Get the required objects off the map FloatingIndex index = swap.GetFloatingIndex(); // Calculate the first fixing off the curve to use at all past dates. double df1 = curve.GetDF(valueDate); Date laterDate = valueDate.AddTenor(index.tenor); double df2 = curve.GetDF(laterDate); double dt = (laterDate - valueDate) / 365.0; double rate = (df1 / df2 - 1) / dt; //Set up the valuation engine. IFloatingRateSource forecastCurve = new ForecastCurveFromDiscount(curve, index, new FloatingRateFixingCurve1Rate(rate, index)); DeterminsiticCurves curveSim = new DeterminsiticCurves(curve); curveSim.AddRateForecast(forecastCurve); Coordinator coordinator = new Coordinator(curveSim, new List <Simulator>(), 1); // Run the valuation double value = coordinator.Value(new Product[] { swap }, valueDate); return(value); }
/// <summary> /// Run a simulation and store the results for later use by <see cref="GetIndices(MarketObservable, List{Date})"/> /// </summary> /// <param name="simNumber"></param> public override void RunSimulation(int simNumber) { simulation = new Dictionary <int, double[]>(); acculatedDivi = new Dictionary <int, double[]>(); var simPrices = prices.Copy(); double oldDF = 1; double newDF; for (var timeCounter = 0; timeCounter < allRequiredDates.Count; timeCounter++) { double dt = timeCounter > 0 ? allRequiredDates[timeCounter] - allRequiredDates[timeCounter - 1] : allRequiredDates[timeCounter] - anchorDate.value; newDF = discountCurve.GetDF(allRequiredDates[timeCounter]); var rateDrift = oldDF / newDF; oldDF = newDF; dt = dt / 365.0; var sdt = Math.Sqrt(dt); var dW = normal.Generate(); acculatedDivi[allRequiredDates[timeCounter]] = Vector.Zeros(shares.Length); for (var s = 0; s < shares.Length; s++) { acculatedDivi[allRequiredDates[timeCounter]][s] = simPrices[s] * divYields[s] * dt; simPrices[s] = simPrices[s] * rateDrift * Math.Exp((-divYields[s] - 0.5 * vols[s] * vols[s]) *dt + vols[s] *sdt *dW[s]); } simulation[allRequiredDates[timeCounter]] = simPrices.Copy(); } }
public double GetForwardRate(Date date) { Date endDate = date.AddTenor(index.tenor); double df1 = discountingSource.GetDF(date); double df2 = discountingSource.GetDF(endDate); double yearFrac = (endDate - date) / 365.0; return((df1 / df2 - 1) / yearFrac); }
/// <summary> /// </summary> /// <param name="date"></param> /// <returns></returns> public double GetForwardRate(Date date) { //TODO: Index should store the business day and daycount conventions of the index. if (date > discountCurve.GetAnchorDate()) { var df1 = discountCurve.GetDF(date); var laterDate = date.AddTenor(index.tenor); var df2 = discountCurve.GetDF(laterDate); var dt = (laterDate - date) / 365.0; var fwdRate = (df1 / df2 - 1) / dt; return(fwdRate); } return(fixingCurve.GetForwardRate(date)); }
public static object GetSpecialDF([QuantSAExcelArgument(Description = "The discounting curve.")] IDiscountingSource discountingSource, [QuantSAExcelArgument(Description = "date")] Date date) { return(discountingSource.GetDF(date)); }
public static IFloatingRateSource CreateRateForecastCurveFromDiscount( [ExcelArgument(Description = "The floating rate that this curve will be used to forecast.")] FloatRateIndex floatingRateIndex, [ExcelArgument(Description = "The name of the discount curve that will be used to obtain the forward rates.")] IDiscountingSource discountCurve, [QuantSAExcelArgument( Description = "Optional: The name of the fixing curve for providing floating rates at dates before the anchor date of the discount curve. If it is left out then the first floating rate implied by the discount curve will be used for all historical fixes.", Default = null)] IFloatingRateSource fixingCurve) { if (fixingCurve == null) { // Calculate the first fixing off the curve to use at all past dates. var df1 = 1.0; var laterDate = discountCurve.GetAnchorDate().AddTenor(floatingRateIndex.Tenor); var df2 = discountCurve.GetDF(laterDate); var dt = (laterDate - discountCurve.GetAnchorDate()) / 365.0; var rate = (df1 / df2 - 1) / dt; fixingCurve = new FloatingRateFixingCurve1Rate(discountCurve.GetAnchorDate(), rate, floatingRateIndex); } return(new ForecastCurveFromDiscount(discountCurve, floatingRateIndex, fixingCurve)); }
public double GetDF(Date date) { double rate = spline.Interpolate(date); double df = Math.Exp(-rate * (date - anchorDate.value) / 365.0); return(underlyingCurve.GetDF(date) * df); }
public void TestEquitySimulatorForwardAndVol() { var N = 100000; var sharePrices = Matrix.Zeros(N, 3); var sim = new EquitySimulator(shares, prices, vols, divYields, correlations, discountCurve, rateForecastCurves); sim.Reset(); var simDate = new List <Date> { anchorDate.AddMonths(120) }; double dt = (simDate[0] - anchorDate) / 365; sim.SetRequiredDates(shares[0], simDate); sim.Prepare(); for (var i = 0; i < N; i++) { sim.RunSimulation(i); sharePrices[i, 0] = sim.GetIndices(shares[0], simDate)[0]; sharePrices[i, 1] = sim.GetIndices(shares[1], simDate)[0]; sharePrices[i, 2] = sim.GetIndices(shares[2], simDate)[0]; } var mean = sharePrices.GetColumn(0).Mean(); var refValue = prices[0] * Math.Exp(-divYields[0] * dt) / discountCurve.GetDF(simDate[0]); Assert.AreEqual(refValue, mean, 2.0); var corr = sharePrices.Log().Correlation(); Assert.AreEqual(corr[1, 0], 0.4, 0.05); Assert.AreEqual(corr[2, 0], 0.5, 0.05); Assert.AreEqual(corr[2, 1], 0.6, 0.05); }
public static double GetDF([ExcelArgument(Description = "The curve from which the DF is required.")] IDiscountingSource curve, [ExcelArgument(Description = "The date on which the discount factor is required. Cannot be before the anchor date of the curve.")] Date date) { return(curve.GetDF(date)); }
public static double GetSimpleForward([ExcelArgument(Description = "The curve from which the forward is required.")] IDiscountingSource curve, [ExcelArgument(Description = "The start date of the required forward. Cannot be before the " + "anchor date of the curve.")] Date startDate, [ExcelArgument(Description = "The end date of the required forward. Must be after the startDate.")] Date endDate, [QuantSAExcelArgument(Description = "The convention that the simple rate will be used with.", Default = "ACT365")] IDayCountConvention daycountConvention) { var df1 = curve.GetDF(startDate); var df2 = curve.GetDF(endDate); var yf = daycountConvention.YearFraction(startDate, endDate); var fwdDf = df2 / df1; var rate = CompoundingStore.Simple.RateFromDf(fwdDf, yf); return(rate); }
/// <summary> /// Discount and add all the cashflows to the anchor date of <paramref name="discountingSource"/>. /// <para> /// Assumes all cashflows are in the future and in the same currency as <paramref name="discountingSource"/>. /// </para> /// </summary> /// <param name="cfs"></param> /// <param name="discountingSource"></param> /// <returns></returns> public static double PV(this List <Cashflow> cfs, IDiscountingSource discountingSource) { var pv = 0.0; foreach (var cf in cfs) { pv += cf.Amount * discountingSource.GetDF(cf.Date); } return(pv); }
public static HullWhite1F CreateHWModelDemo([ExcelArgument(Description = "The constant rate of mean reversion.")] double meanReversion, [ExcelArgument(Description = "The constant short rate volatility. Note that this is a Gaussian vol and will in general be lower than the vol that would be used in Black.")] double flatVol, [ExcelArgument(Description = "The curve to which zero coupon bond prices will be calibrated.")] IDiscountingSource baseCurve, [ExcelArgument(Description = "The indices that should be forecast with this same cuve. No spreads are added.")] FloatingIndex forecastIndices) { Date anchorDate = baseCurve.GetAnchorDate(); double flatCurveRate = -Math.Log(baseCurve.GetDF(anchorDate.AddTenor(Tenor.Years(1)))); HullWhite1F model = new HullWhite1F(baseCurve.GetCurrency(), meanReversion, flatVol, flatCurveRate, flatCurveRate, anchorDate); model.AddForecast(forecastIndices); return(model); }
public static object GetSpecialDF([ExcelArgument(Description = "Name of discounting curve.")] String name, [ExcelArgument(Description = "date")] object[,] date) { try { IDiscountingSource discountCurve = PluginConnection.objectMap.GetObjectFromID <IDiscountingSource>(name); return(discountCurve.GetDF(ExcelUtilities.GetDate0D(date, "date"))); } catch (Exception e) { return(ExcelUtilities.Error0D(e)); } }
public double GetDF(Date date) { var df = underlyingCurve.GetDF(date); double adjustedDF; if (hasParallelShift) { adjustedDF = df * Math.Exp(effectiveRateBump * (date - underlyingCurve.GetAnchorDate()) / 365.0); } else { adjustedDF = df * 1.0; } return(adjustedDF); }
public double GetDF(Date date) { double df = underlyingCurve.GetDF(date); double adjustedDF; if (hasParallelShift) { adjustedDF = df * Math.Exp(effectiveRateBump * (date - underlyingCurve.GetAnchorDate()) / 365.0); } else { //TODO: get the interpolated shift size from the dates and bumps adjustedDF = df * 1.0; } return(adjustedDF); }
private Dictionary <int, double[]> simulation; // stores the simulated spot rates at each required date /// <summary> /// Initializes a new instance of the <see cref="MultiHWAndFXToy"/> class. /// </summary> /// <param name="anchorDate">The anchor date.</param> /// <param name="numeraireCurve">The numeraire curve.</param> /// <param name="numeraireHWParams"></param> /// <param name="otherCcys">The other currencies that will be simulated.</param> /// <param name="otherCcySpots">The exchange rates at the anchor date. Discounted from the spot values. Quoted in units of the numeraire currency per unit of the foreign currency.</param> /// <param name="otherCcyVols"></param> /// <param name="otherCcyCurves"></param> /// <param name="otherCcyHwParams"></param> /// <param name="correlations">The correlation matrix ordered by: numeraireRate, otherCcy1Rate, ..., otherCcyFX1, ...</param> /// <exception cref="System.ArgumentException">A rate simulator must be provided for the numeraire currency: " + numeraireCcy.ToString()</exception> public MultiHWAndFXToy(Date anchorDate, IDiscountingSource numeraireCurve, List <FloatingIndex> numeraireCcyRequiredIndices, HWParams numeraireHWParams, List <Currency> otherCcys, List <double> otherCcySpots, List <double> otherCcyVols, List <IDiscountingSource> otherCcyCurves, List <List <FloatingIndex> > otherCcyRequiredIndices, List <HWParams> otherCcyHwParams, double[,] correlations) { this.anchorDate = anchorDate; numeraireCcy = numeraireCurve.GetCurrency(); List <HullWhite1F> rateSimulatorsList = new List <HullWhite1F>(); ccySimMap = new Dictionary <Currency, HullWhite1F>(); double rate = -Math.Log(numeraireCurve.GetDF(anchorDate.AddMonths(12))); numeraireSimulator = new HullWhite1F(numeraireCcy, numeraireHWParams.meanReversionSpeed, numeraireHWParams.vol, rate, rate, anchorDate); foreach (FloatingIndex index in numeraireCcyRequiredIndices) { numeraireSimulator.AddForecast(index); } rateSimulatorsList.Add(numeraireSimulator); ccySimMap[numeraireCcy] = numeraireSimulator; for (int i = 0; i < otherCcys.Count; i++) { rate = -Math.Log(otherCcyCurves[i].GetDF(anchorDate.AddMonths(12))); HullWhite1F thisSim = new HullWhite1F(otherCcys[i], otherCcyHwParams[i].meanReversionSpeed, otherCcyHwParams[i].vol, rate, rate, anchorDate); foreach (FloatingIndex index in otherCcyRequiredIndices[i]) { thisSim.AddForecast(index); } rateSimulatorsList.Add(thisSim); ccySimMap[otherCcys[i]] = thisSim; } currencyPairs = otherCcys.Select(ccy => new CurrencyPair(ccy, numeraireCcy)).ToArray(); spots = otherCcySpots.ToArray(); vols = otherCcyVols.ToArray(); this.correlations = Matrix.Identity(otherCcys.Count); normal = new MultivariateNormalDistribution(Vector.Zeros(currencyPairs.Length), correlations); rateSimulators = rateSimulatorsList.ToArray(); }
public override double Numeraire(Date valueDate) { return(1 / discountCurve.GetDF(valueDate)); }
public static AssetSwap CreateAssetSwap(double payFixed, BesaJseBond besaJseBond, Date settleDate, FloatRateIndex index, double spread, Calendar calendar, Currency ccy, IDiscountingSource discountCurve) { //Design floating leg inputs var dayCount = Actual365Fixed.Instance; var unAdjResetDatesFloating = new List <Date>(); var unAdjPaymentDatesFloating = new List <Date>(); var resetDatesFloating = new List <Date>(); var paymentDatesFloating = new List <Date>(); var accrualFractions = new List <double>(); var endDate = besaJseBond.maturityDate; var paymentDateFloating = new Date(endDate); var resetDateFloating = paymentDateFloating.SubtractTenor(index.Tenor); while (resetDateFloating >= settleDate) { unAdjPaymentDatesFloating.Add(paymentDateFloating); unAdjResetDatesFloating.Add(resetDateFloating); resetDatesFloating.Add(BusinessDayStore.ModifiedFollowing.Adjust(resetDateFloating, calendar)); paymentDatesFloating.Add(BusinessDayStore.ModifiedFollowing.Adjust(paymentDateFloating, calendar)); accrualFractions.Add(dayCount.YearFraction(BusinessDayStore.ModifiedFollowing.Adjust(resetDateFloating, calendar), BusinessDayStore.ModifiedFollowing.Adjust(paymentDateFloating, calendar))); paymentDateFloating = new Date(resetDateFloating); resetDateFloating = paymentDateFloating.SubtractTenor(index.Tenor); } resetDatesFloating.Reverse(); paymentDatesFloating.Reverse(); accrualFractions.Reverse(); resetDatesFloating[0] = new Date(settleDate); var firstResetDate = resetDatesFloating.First(); var firstPaymentDate = paymentDatesFloating.First(); accrualFractions[0] = dayCount.YearFraction(firstResetDate, firstPaymentDate); //Design Fixed leg inputs var unAdjPaymentDatesFixed = new List <Date>(); var paymentDatesFixed = new List <Date>(); var thisYearCpn1 = new Date(settleDate.Year, besaJseBond.couponMonth1, besaJseBond.couponDay1); var thisYearCpn2 = new Date(settleDate.Year, besaJseBond.couponMonth2, besaJseBond.couponDay2); var lastYearCpn2 = new Date(settleDate.Year - 1, besaJseBond.couponMonth2, besaJseBond.couponDay2); Date lcd; //lcd stands for last coupon date if (settleDate > thisYearCpn2) { lcd = new Date(thisYearCpn2.Year, thisYearCpn2.Month, thisYearCpn2.Day); } if (settleDate > thisYearCpn1) { lcd = new Date(thisYearCpn1.Year, thisYearCpn1.Month, thisYearCpn1.Day); } lcd = new Date(lastYearCpn2.Year, lastYearCpn2.Month, lastYearCpn2.Day); Date ncd; //ncd stands for next coupon date if (lcd.Month == besaJseBond.couponMonth2) { ncd = new Date(lcd.Year + 1, besaJseBond.couponMonth1, besaJseBond.couponDay1); } else { ncd = new Date(lcd.Year, besaJseBond.couponMonth2, besaJseBond.couponDay2); } var paymentDateFixed = new Date(ncd.AddTenor(Tenor.FromMonths(6))); while (paymentDateFixed <= endDate) { unAdjPaymentDatesFixed.Add(paymentDateFixed); paymentDatesFixed.Add(BusinessDayStore.ModifiedFollowing.Adjust(paymentDateFixed, calendar)); paymentDateFixed = paymentDateFixed.AddTenor(Tenor.FromMonths(6)); } //create new instance of asset swap var assetSwap = new AssetSwap(payFixed, index, besaJseBond, resetDatesFloating, paymentDatesFloating, paymentDatesFixed, spread, accrualFractions, calendar, ccy); //Create trade date of the swap var effectiveDateDays = 3; var unAdjTradeDate = settleDate.AddDays(-effectiveDateDays); var tradeDate = BusinessDayStore.ModifiedFollowing.Adjust(unAdjTradeDate, assetSwap.zaCalendar); //Set value date assetSwap.SetValueDate(tradeDate); // Calculate the first fixing off the curve to use at all past dates. var df1 = discountCurve.GetDF(tradeDate); var laterDate = tradeDate.AddTenor(assetSwap.index.Tenor); var df2 = discountCurve.GetDF(laterDate); var dt = (laterDate - tradeDate) / 365.0; var rate = (df1 / df2 - 1) / dt; // Create the forecast curve from the discount curve IFloatingRateSource forecastCurve = new ForecastCurveFromDiscount(discountCurve, assetSwap.index, new FloatingRateFixingCurve1Rate(tradeDate, rate, assetSwap.index)); //Setting index values var indexValues = new double[assetSwap.indexDates.Count]; for (var i = 0; i < assetSwap.indexDates.Count; i++) { indexValues[i] = forecastCurve.GetForwardRate(assetSwap.indexDates[i]); } assetSwap.SetIndexValues(assetSwap.index, indexValues); return(assetSwap); }
public double Objective() { var df = _curve.GetDF(_maturityDate); return(df * _cf - 1e6); }
public static ResultStore AssetSwapMeasures(this AssetSwap assetSwap, Date settleDate, double ytm, IDiscountingSource discountCurve) { //Create Asset Swap var swap = CreateAssetSwap(assetSwap.payFixed, assetSwap.underlyingBond, settleDate, assetSwap.index, assetSwap.spread, assetSwap.zaCalendar, assetSwap.ccy, discountCurve); //Create trade date of the swap var effectiveDateDays = 3; var unAdjTradeDate = settleDate.AddDays(-effectiveDateDays); var tradeDate = BusinessDayStore.ModifiedFollowing.Adjust(unAdjTradeDate, assetSwap.zaCalendar); //Set value date assetSwap.SetValueDate(tradeDate); // Calculate the first fixing off the curve to use at all past dates. var df1 = discountCurve.GetDF(tradeDate); var laterDate = tradeDate.AddTenor(assetSwap.index.Tenor); var df2 = discountCurve.GetDF(laterDate); var noOfDays = 365; var dt = (laterDate - tradeDate) / noOfDays; var rate = (df1 / df2 - 1) / dt; // Create the forecast curve from the discount curve IFloatingRateSource forecastCurve = new ForecastCurveFromDiscount(discountCurve, assetSwap.index, new FloatingRateFixingCurve1Rate(tradeDate, rate, assetSwap.index)); //Setting index values var indexValues = new double[swap.indexDates.Count]; for (var i = 0; i < swap.indexDates.Count; i++) { indexValues[i] = forecastCurve.GetForwardRate(swap.indexDates[i]); } assetSwap.SetIndexValues(assetSwap.index, indexValues); //Calculate present value of fixed and floating cashflows var numeratorCFs = swap.GetCFs().PV(discountCurve); //Calculate present value of denominator cashflows for spread equation var denomCFs = new List <Cashflow>(); var nominalAmount = 100; for (var i = 0; i < swap.paymentDatesFloating.Count; i++) { if (i <= swap.paymentDatesFloating.Count) { denomCFs.Add(new Cashflow(swap.paymentDatesFloating[i], -nominalAmount * swap.accrualFractions[i], swap.ccy)); } } var bondresults = assetSwap.underlyingBond.GetSpotMeasures(settleDate, ytm); var roundedAip = (double)bondresults.GetScalar(BesaJseBondEx.Keys.RoundedAip); var denominatorCFs = denomCFs.PV(discountCurve); var firstCF = new List <Cashflow>(); for (var i = 0; i < 1; i++) { if (i <= 1) { firstCF.Add(new Cashflow(settleDate, (roundedAip - 100), swap.ccy)); } } var pvFirstCF = firstCF.PV(discountCurve); //This is the assetSwapSpread calculation var assetSwapSpread = (pvFirstCF + numeratorCFs) / denominatorCFs; var results = new ResultStore(); results.Add(Keys.RoundedAip, roundedAip); results.Add(Keys.PVFirstCF, pvFirstCF); results.Add(Keys.NumeratorCashFlowsPrice, numeratorCFs); results.Add(Keys.DenominatorCashFlowsPrice, denominatorCFs); results.Add(Keys.AssetSwapSpread, assetSwapSpread); return(results); }
public double GetRate(Date date) { return(fxRateAtAnchorDate * baseCurrencyFXBasisCurve.GetDF(date) / counterCurrencyFXBasisCurve.GetDF(date)); }
public override double Numeraire(Date valueDate) { return(1.0 / valueCurrencyDiscount.GetDF(valueDate)); }