예제 #1
0
        public void TestCoordinatorAllData()
        {
            // Make the swap
            double rate      = 0.07;
            bool   payFixed  = true;
            double notional  = 1000000;
            Date   startDate = new Date(2016, 9, 17);
            Tenor  tenor     = Tenor.Years(5);
            IRSwap swap      = IRSwap.CreateZARSwap(rate, payFixed, notional, startDate, tenor);

            // Set up the model
            Date        valueDate     = new Date(2016, 9, 17);
            double      a             = 0.05;
            double      vol           = 0.01;
            double      flatCurveRate = 0.07;
            HullWhite1F hullWiteSim   = new HullWhite1F(Currency.ZAR, a, vol, flatCurveRate, flatCurveRate, valueDate);

            hullWiteSim.AddForecast(FloatingIndex.JIBAR3M);
            Coordinator coordinator = new Coordinator(hullWiteSim, new List <Simulator>(), 5000);

            Date        date          = valueDate;
            Date        endDate       = valueDate.AddTenor(tenor);
            List <Date> fwdValueDates = new List <Date>();

            while (date < endDate)
            {
                fwdValueDates.Add(date);
                date = date.AddTenor(Tenor.Days(10));
            }
            ResultStore allDetails = coordinator.GetValuePaths(new Product[] { swap }, valueDate, fwdValueDates.ToArray());

            allDetails.GetNames();
        }
예제 #2
0
        public ResultStore GetResultStore()
        {
            var result = new ResultStore();

            result.Add("maturityDate", maturityDate);
            result.Add("annualCouponRate", annualCouponRate);
            return(result);
        }
예제 #3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="bondforward"></param>
        /// <param name="settleDate"></param>
        /// <param name="ytm"></param>
        /// <param name="repo"></param>
        /// <returns></returns>
        public static ResultStore ForwardPrice(this JSEBondForward bondforward, Date settleDate, double ytm, double repo)
        {
            var N            = 100.0;
            var couponamount = N * bondforward.underlyingBond.annualCouponRate / 2;
            var forwardDate  = bondforward.forwardDate;

            if (settleDate > forwardDate)
            {
                throw new ArgumentException("settlement date must be before forward date.");
            }

            // get all-in price of underlying bond
            var results = bondforward.underlyingBond.GetSpotMeasures(settleDate, ytm);
            var AIP     = (double)results.GetScalar(BesaJseBondEx.Keys.RoundedAip);

            // calculate Unadjusted Forward Price
            var dt           = (double)(forwardDate - settleDate) / 365;
            var ForwardPrice = AIP * (1 + repo * dt);

            // get coupon dates between settlement and forward date and calculate equivalent value function
            var CouponDates = GetCouponDates(bondforward.underlyingBond, settleDate, forwardDate);

            // adjust forward price for any coupons the counterparty might receive
            var EV = new List <double>();

            double AdjustedForwardPrice = 0;

            if (CouponDates.Any())
            {
                foreach (var date in CouponDates)
                {
                    if (date <= forwardDate)
                    {
                        EV.Add(1 + repo * (forwardDate - date) / 365);
                    }
                    else
                    {
                        EV.Add(Math.Pow(1 + repo * (date - forwardDate) / 365, -1));
                    }
                }

                AdjustedForwardPrice = ForwardPrice - couponamount * EV.Sum();
            }
            else
            {
                AdjustedForwardPrice = ForwardPrice;
            }

            var resultStore = new ResultStore();

            resultStore.Add(Keys.ForwardPrice, AdjustedForwardPrice);
            return(resultStore);
        }
예제 #4
0
        public static ResultStore GetRiskMeasures(this BesaJseBond bond, Date settleDate, double ytm)
        {
            var riskmeasures = new ResultStore();

            riskmeasures.Add(Keys.Delta, bond.Delta(settleDate, ytm));
            riskmeasures.Add(Keys.RandsPerPoint, bond.RandsPerPoint(settleDate, ytm));
            riskmeasures.Add(Keys.Duration, bond.Duration(settleDate, ytm));
            riskmeasures.Add(Keys.ModifiedDuration, bond.ModefiedDuration(settleDate, ytm));
            riskmeasures.Add(Keys.Convexity, bond.Convexity(settleDate, ytm));

            return(riskmeasures);
        }
예제 #5
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="bond"></param>
        /// <param name="settleDate"></param>
        /// <param name="ytm"></param>
        /// <returns></returns>

        public static ResultStore GetSpotMeasures(this BesaJseBond bond, Date settleDate, double ytm)
        {
            var spotmeasures = new ResultStore();

            spotmeasures.Add(Keys.RoundedAip, bond.RoundedAIP(settleDate, ytm));
            spotmeasures.Add(Keys.RoundedClean, bond.RoundedClean(settleDate, ytm));
            spotmeasures.Add(Keys.UnroundedAip, bond.UnroundedAIP(settleDate, ytm));
            spotmeasures.Add(Keys.UnroundedClean, bond.UnroundedClean(settleDate, ytm));
            spotmeasures.Add(Keys.UnroundedAccrued, bond.UnroundedAccruedInterest(settleDate));

            return(spotmeasures);
        }
예제 #6
0
        public static object[,] GetAvailableResults(
            [ExcelArgument(Description = "The results object as returned by call to another QuantSA function")]
            ResultStore resultStore)
        {
            var temp   = resultStore.GetNames();
            var column = new object[temp.Length, 1];

            for (var i = 0; i < temp.Length; i++)
            {
                column[i, 0] = temp[i];
            }
            return(column);
        }
예제 #7
0
        public static ResultStore Value([ExcelArgument(Description = "A list of products.")] Product[] products,
                                        [QuantSAExcelArgument(Description = "The value date.")] Date valueDate,
                                        [QuantSAExcelArgument(Description = "A model able to handle all the market observables required to calculate the cashflows in the portfolio.")] NumeraireSimulator model,
                                        [QuantSAExcelArgument(Description = "Optional.  The number of simulations required if the model requires simulation.  If left blank will use a default value depending on the model.", Default = "1")] int nSims)
        {
            //int N = (nSims[0, 0] is ExcelMissing) ? 1 : XU.GetInt0D(nSims, "nSims");

            Coordinator coordinator = new Coordinator(model, new List <Simulator>(), nSims);
            double      value       = coordinator.Value(products, valueDate);
            ResultStore result      = new ResultStore();

            result.Add("value", value);
            return(result);
        }
예제 #8
0
        public ResultStore GetResultStore()
        {
            var result = new ResultStore();

            result.Add("notional", notional);
            result.Add("accrualFraction", accrualFraction);
            result.Add("rate", rate);
            result.Add("nearDate", nearDate);
            result.Add("farDate", farDate);
            result.Add("floatIndex", floatIndex.ToString());
            result.Add("payFixed", payFixed.ToString());
            result.Add("ccy", ccy.ToString());
            return(result);
        }
        public void StoreResult(string key, byte[] value, List <KeyValuePair <string, string> > extraParams = null)
        {
            List <ParameterInfo> extraParamsToAdd = extraParams == null
                ? null
                : extraParams.Select(c => new ParameterInfo()
            {
                Name  = c.Key,
                Value = c.Value
            }).ToList();

            ResultStore.Store(new ResultInfo()
            {
                Key = key, Data = value, ExtraParams = extraParamsToAdd
            });
        }
예제 #10
0
        public static ResultStore BlackOption(JSEBondOption bondoption, double strike, double vol, double repo, JSEBondForward bond, double yieldToMaturity)
        {
            var settleDate        = bondoption.settleDate;
            var timeToMaturity    = bondoption.timeToMaturity;
            var ytm               = yieldToMaturity;
            var bondforwardprice1 = (double)bond.ForwardPrice(settleDate, ytm, repo).GetScalar(JSEBondForwardEx.Keys.ForwardPrice);

            var discountFactor = Math.Exp(-repo * timeToMaturity);

            var optionPrice = BlackEtc.Black(PutOrCall.Call, strike, timeToMaturity, bondforwardprice1, vol, discountFactor);

            var resultStore = new ResultStore();

            resultStore.Add(Keys.BlackOption, optionPrice);
            return(resultStore);
        }
예제 #11
0
 public static object[,] GetResults([ExcelArgument(Description =
                                                       "The results object as returned by a call to another QuantSA function")]
                                    ResultStore resultStore,
                                    [ExcelArgument(Description =
                                                       "The name of the result required.  Use QSA.GetAvailableResults to get a list of all available results in this object.")]
                                    string resultName)
 {
     if (resultStore.IsDate(resultName))
     {
         return(resultStore.GetDates(resultName));
     }
     if (resultStore.IsString(resultName))
     {
         return(resultStore.GetStrings(resultName));
     }
     return(resultStore.Get(resultName));
 }
예제 #12
0
        public static ResultStore InflationLinkedSwapMeasures(this InflationLinkedSwap inflationLinkedSwap, Date[] cpiDates, double[] cpiRates, IFloatingRateSource forecastCurve)
        {
            //Create Inflation Swap
            var swap = CreateInflationLinkedSwap(inflationLinkedSwap.payFixed, inflationLinkedSwap.startDate, inflationLinkedSwap.nominal, inflationLinkedSwap.tenor,
                                                 inflationLinkedSwap.fixedRate, inflationLinkedSwap.index, inflationLinkedSwap.spread, inflationLinkedSwap.zaCalendar, inflationLinkedSwap.ccy);

            //Set value date
            swap.SetValueDate(inflationLinkedSwap.startDate);

            //Set index values
            var indexValues = new double[swap.indexDates.Length];

            for (var i = 0; i < swap.indexDates.Length; i++)
            {
                indexValues[i] = forecastCurve.GetForwardRate(swap.indexDates[i]);
            }
            swap.SetIndexValues(swap.index, indexValues);

            //Determine swap end date
            var unAdjEndDate = inflationLinkedSwap.startDate.AddMonths(12 * inflationLinkedSwap.tenor.Years);
            var endDate      = BusinessDayStore.ModifiedFollowing.Adjust(unAdjEndDate, inflationLinkedSwap.zaCalendar);

            //Calculate value of fixed and floating cashflows
            var floatingCashFlows    = swap.GetCFs();
            var floatingLegCashFlows = floatingCashFlows.Last().Amount;

            var cpiStartDate = LaggedCPI.GetCPI(inflationLinkedSwap.startDate, cpiDates, cpiRates);
            var cpiEndDate   = LaggedCPI.GetCPI(endDate, cpiDates, cpiRates);

            var fixedCashFlows = inflationLinkedSwap.payFixed * inflationLinkedSwap.nominal * Math.Pow((1 + inflationLinkedSwap.fixedRate / 2),
                                                                                                       2 * (endDate - inflationLinkedSwap.startDate) / 365) * cpiEndDate / cpiStartDate;

            var netCashFlows = floatingLegCashFlows + fixedCashFlows;

            // Store results
            var results = new ResultStore();

            results.Add(Keys.FloatingLegCashFlows, floatingLegCashFlows);
            results.Add(Keys.FixedLegCashFlows, fixedCashFlows);
            results.Add(Keys.NetCashFlows, netCashFlows);

            return(results);
        }
예제 #13
0
        /// <summary>
        /// Gets all the data that might be of interest after a simulation.
        /// </summary>
        /// <param name="portfolioIn">The portfolio in.</param>
        /// <param name="valueDate">The value date.</param>
        /// <param name="fwdValueDates">The forward value dates.</param>
        /// <returns></returns>
        public ResultStore GetValuePaths(Product[] portfolioIn, Date valueDate, Date[] fwdValueDates)
        {
            CalculateAll(portfolioIn, valueDate, fwdValueDates);
            ResultStore results = new ResultStore();

            results.Add("regressedFwdsPVs", regressedValues);
            double[,] fwdCashflowPVs = new double[N, fwdValueDates.Count()];
            for (int i = 0; i < fwdValueDates.Count(); i++)
            {
                fwdCashflowPVs.SetColumn(i, simulatedCFs.GetPathwisePV(fwdValueDates[i], originalTrades));
            }
            results.Add("fwdCashflowPVs", fwdCashflowPVs);

            for (int regressorNumber = 0; regressorNumber < simulatedRegs.GetNumberOfRegressors(); regressorNumber++)
            {
                results.Add("regressor" + regressorNumber.ToString(), simulatedRegs.GetRegressors(regressorNumber, fwdValueDates));
            }
            return(results);
        }
예제 #14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="bond"></param>
        /// <param name="settleDate"></param>
        /// <param name="ytm"></param>
        /// <returns></returns>
        public static ResultStore GetSpotMeasures(this BesaJseBond bond, Date settleDate, double ytm)
        {
            var N                     = 100.0;
            var typicalCoupon         = N * bond.annualCouponRate / 2;
            var t0                    = bond.GetLastCouponDateOnOrBefore(settleDate);
            var t1                    = bond.GetNextCouponDate(t0);
            var n                     = (int)Math.Round((bond.maturityDate - t1) / 182.625);
            var tradingWithNextCoupon = t1 - settleDate > bond.booksCloseDateDays;
            var d                     = tradingWithNextCoupon ? settleDate - t0 : settleDate - t1;
            var unroundedAccrued      = N * bond.annualCouponRate * d / 365.0;
            var roundedAccrued        = Math.Round(unroundedAccrued, 5);
            var couponAtT1            = tradingWithNextCoupon ? typicalCoupon : 0.0;
            var v                     = 1 / (1 + ytm / 2);

            double brokenPeriodDf;

            if (n > 0)
            {
                brokenPeriodDf = Math.Pow(v, ((double)t1 - settleDate) / (t1 - t0));
            }
            else
            {
                brokenPeriodDf = 1 / (1 + ytm * ((double)t1 - settleDate) / 365.0);
            }

            var unroundedAip = brokenPeriodDf *
                               (couponAtT1 + typicalCoupon * v * (1 - Math.Pow(v, n)) / (1 - v) + N * Math.Pow(v, n));

            var unroundedClean = unroundedAip - unroundedAccrued;
            var roundedClean   = Math.Round(unroundedClean, 5);
            var roundedAip     = roundedClean + roundedAccrued;

            var results = new ResultStore();

            results.Add(Keys.RoundedAip, roundedAip);
            results.Add(Keys.RoundedClean, roundedClean);
            results.Add(Keys.UnroundedAip, unroundedAip);
            results.Add(Keys.UnroundedClean, unroundedClean);
            results.Add(Keys.UnroundedAccrued, unroundedAccrued);
            results.Add(Keys.TradingWithNextCoupon, tradingWithNextCoupon ? 1.0 : 0.0);

            return(results);
        }
예제 #15
0
 public static object _Value(string objectName,
                             object[,] products,
                             object[,] valueDate,
                             object[,] model,
                             object[,] nSims)
 {
     try
     {
         Product[]          _products  = XU.GetObject1D <Product>(products, "products");
         Date               _valueDate = XU.GetDate0D(valueDate, "valueDate");
         NumeraireSimulator _model     = XU.GetObject0D <NumeraireSimulator>(model, "model");
         Int32              _nSims     = XU.GetInt320D(nSims, "nSims", 1);
         ResultStore        _result    = XLValuation.Value(_products, _valueDate, _model, _nSims);
         return(XU.AddObject(objectName, _result));
     }
     catch (Exception e)
     {
         return(XU.Error0D(e));
     }
 }
예제 #16
0
        /// <summary>
        /// Gets all the data that might be of interest after a simulation.
        /// </summary>
        /// <param name="portfolioIn">The portfolio in.</param>
        /// <param name="valueDate">The value date.</param>
        /// <param name="fwdValueDates">The forward value dates.</param>
        /// <returns></returns>
        public ResultStore GetValuePaths(IProduct[] portfolioIn, Date valueDate, Date[] fwdValueDates)
        {
            CalculateAll(portfolioIn, valueDate, fwdValueDates);
            var results = new ResultStore();

            results.Add("regressedFwdsPVs", _regressedValues);
            var fwdCashflowPVs = new double[_numberOfPaths, fwdValueDates.Count()];

            for (var i = 0; i < fwdValueDates.Length; i++)
            {
                fwdCashflowPVs.SetColumn(i, _simulatedCFs.GetPathwisePV(fwdValueDates[i], _originalTrades));
            }
            results.Add("fwdCashflowPVs", fwdCashflowPVs);

            for (var regressorNumber = 0; regressorNumber < _simulatedRegs.GetNumberOfRegressors(); regressorNumber++)
            {
                results.Add("regressor" + regressorNumber,
                            _simulatedRegs.GetRegressors(regressorNumber, fwdValueDates));
            }
            return(results);
        }
예제 #17
0
        public void TestAllInPrice()
        {
            Date     settleDate       = new Date(2016, 3, 3);
            Date     maturityDate     = new Date(2030, 1, 31);
            double   notional         = 1000000;
            double   annualCouponRate = 0.08;
            int      couponMonth1     = 1;
            int      couponDay1       = 31;
            int      couponMonth2     = 7;
            int      couponDay2       = 31;
            Calendar zaCalendar       = new Calendar("Test");
            var      bondR2030        = new BesaJseBond(maturityDate, notional, annualCouponRate, couponMonth1,
                                                        couponDay1, couponMonth2, couponDay2, zaCalendar, TestHelpers.ZAR);

            double      ytm     = 0.097;
            ResultStore results = bondR2030.GetSpotMeasures(settleDate, ytm);

            Assert.AreEqual(87.85607808, (double)results.GetScalar(BesaJseBondEx.Keys.unroundedAip), 1e-8);
            Assert.AreEqual(87.85608, (double)results.GetScalar(BesaJseBondEx.Keys.roundedAip), 1e-8);
            Assert.AreEqual(87.15470822, (double)results.GetScalar(BesaJseBondEx.Keys.unroundedClean), 1e-8);
            Assert.AreEqual(87.15471, (double)results.GetScalar(BesaJseBondEx.Keys.roundedClean), 1e-8);
            Assert.AreEqual(0.701369836, (double)results.GetScalar(BesaJseBondEx.Keys.unroundedAccrued), 1e-7);
        }
 public bool FinishedProcessing(string key)
 {
     return(ResultStore.ResultExists(key));
 }
 public ResultInfo GetResult(string key)
 {
     return(ResultStore.Get(key));
 }
예제 #20
0
        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);
        }