/// <summary>
        /// Calculate valuation profiles.
        /// </summary>
        public override void Value(ValuationResults valuationResults, PriceFactorList factors, BaseTimeGrid baseTimes)
        {
            PreValue(factors);

            TimeGridIterator tgi              = new TimeGridIterator(fT);
            PVProfiles       result           = valuationResults.Profile;
            CashAccumulators cashAccumulators = valuationResults.Cash;

            FixedCashflowBaseDeal deal = (FixedCashflowBaseDeal)fDeal;
            double payDate             = deal.Payment_Date;
            double tPay = CalcUtils.DaysToYears(payDate - factors.BaseDate);

            VectorEngine.For(tgi, () =>
            {
                if (tgi.Date == payDate)
                {
                    result.AppendVector(tgi.Date, fFxRate.Get(tgi.T) * fAmount);
                }
                else
                {
                    result.AppendVector(tgi.Date, fFxRate.Get(tgi.T) * fDiscountRate.Get(tgi.T, tPay) * fAmount);
                }
            });

            if (!cashAccumulators.Ignore && factors.BaseDate <= payDate && payDate <= fT.fHorizon)
            {
                cashAccumulators.Accumulate(fFxRate, payDate, fAmount);
            }

            result.Complete(fT);
        }
        /// <summary>
        /// Calculate valuation profiles.
        /// </summary>
        public override void Value(ValuationResults valuationResults, PriceFactorList factors, BaseTimeGrid baseTimes)
        {
            PreValue(factors);

            TimeGridIterator tgi              = new TimeGridIterator(fT);
            PVProfiles       result           = valuationResults.Profile;
            CashAccumulators cashAccumulators = valuationResults.Cash;

            BaseCliquetOption deal = (BaseCliquetOption)Deal;

            double scale = (deal.Buy_Sell == BuySell.Buy ? +1 : -1) * deal.GetUnits();

            VectorEngine.For(tgi, () =>
            {
                using (var cache = Vector.Cache(factors.NumScenarios))
                {
                    Vector pv   = cache.Get();
                    Vector cash = cache.Get();

                    PricingFunctions.CliquetOption(pv, cash, deal.Option_Type, tgi.T, fTimes, deal.Moneyness,
                                                   fKnownPrices, fAssetPrice, fFxRate, fPayoffFxRate,
                                                   fDiscountRate, fAssetPriceVol, fQuantoCompo, fPayoffType,
                                                   factors.PathDependent);
                    cashAccumulators.Accumulate(fPayoffFxRate, tgi.Date, scale * cash);
                    result.AppendVector(tgi.Date, scale * pv * fPayoffFxRate.Get(tgi.T));
                }
            }
                             );

            result.Complete(fT);
        }
Example #3
0
        /// <summary>
        /// Collect cashflows realised along the scenario path up to endDate.
        /// </summary>
        public override void CollectCashflows(CashAccumulators cashAccumulators, double baseDate, double endDate)
        {
            var deal         = (CFEquityFloatingInterestListDeal)Deal;
            var equityParams = new EquityCashflowParams((IEquityPrice)fEquity, (EquityPriceVol)fEquityVol, fEquityFXRate, fEquityPayoffFXRate, deal.GetEquityPayoffType(), fEquityQuantoCompo, null, null);

            deal.Cashflows.CollectCashflows(cashAccumulators, fFxRate, equityParams, baseDate, endDate, fBuySellSign, fForecastRate, fCutoffDate);
        }
Example #4
0
        /// <inheritdoc />
        public override void Value(ValuationResults valuationResults, PriceFactorList factors, BaseTimeGrid baseTimes)
        {
            PreValue(factors);
            CashAccumulators cashResults = valuationResults.Cash;
            PVProfiles       pvResults   = valuationResults.Profile;

            Value(pvResults, cashResults, factors.BaseDate, fDiscountRate, fForecastRate, fForecastRate2, fFxRate, fT, factors.NumScenarios);
        }
Example #5
0
        /// <summary>
        /// Collect cashflows realised along the scenario path up to endDate.
        /// </summary>
        public override void CollectCashflows(CashAccumulators cashAccumulators, double baseDate, double endDate)
        {
            CFFixedInterestListDeal deal = (CFFixedInterestListDeal)Deal;

            deal.Cashflows.CollectCashflows(cashAccumulators, fFxRate, fRateFxRate, baseDate, endDate, fBuySellSign, fCutoffDate);

            double settlementDate = deal.Settlement_Date;

            if (settlementDate >= baseDate && settlementDate <= endDate)
            {
                cashAccumulators.Accumulate(fFxRate, settlementDate, -fBuySellSign * fSettlementAmount);
            }
        }
Example #6
0
        /// <summary>
        /// Calculate valuation profiles.
        /// </summary>
        public override void Value(ValuationResults valuationResults, PriceFactorList factors, BaseTimeGrid baseTimes)
        {
            base.PreValue(factors);

            IAssetPrice     commodityPrice;
            ISpotProcessVol dummyAssetPriceVol;

            ((BaseAssetFxDealHelper)GetDealHelper()).PreValueAsset(out commodityPrice, out dummyAssetPriceVol, out fBasketPricer, ref fQuantoCompo, factors);

            CommodityForwardDealBase deal = (CommodityForwardDealBase)fDeal;

            double scale     = (deal.Buy_Sell == BuySell.Buy ? +1 : -1) * deal.Units;
            double tMaturity = CalcUtils.DaysToYears(deal.Maturity_Date - factors.BaseDate);

            TimeGridIterator tgi    = new TimeGridIterator(fT);
            CashAccumulators cash   = valuationResults.Cash;
            PVProfiles       result = valuationResults.Profile;

            VectorEngine.For(tgi, () =>
            {
                using (var cache = Vector.Cache(factors.NumScenarios))
                {
                    Vector pv = cache.Get();

                    if (tgi.Date <= deal.Maturity_Date)
                    {
                        pv.Assign(commodityPrice.ForwardFactor(tgi.T, tMaturity, fFxRate) * commodityPrice.Get(tgi.T));     // assign forward * fxRate to pv
                        pv.Assign((pv - deal.Forward_Price * fFxRate.Get(tgi.T)) * fDiscountRate.Get(tgi.T, tMaturity) * scale);
                    }
                    else
                    {
                        pv.Clear();
                    }

                    result.AppendVector(tgi.Date, pv);

                    if (tgi.Date == deal.Maturity_Date)
                    {
                        cash.Accumulate(fFxRate, deal.Maturity_Date, (commodityPrice.Get(tMaturity) / fFxRate.Get(tMaturity) - deal.Forward_Price) * scale);
                    }
                }
            });

            result.Complete(fT);
        }
Example #7
0
        /// <summary>
        /// Collect cashflows realised along the scenario path up to endDate.
        /// </summary>
        public override void CollectCashflows(CashAccumulators cashAccumulators, double baseDate, double endDate)
        {
            var deal = (CFFloatingInterestListDeal)Deal;

            if (!fForecastIsForeign && fCharacteristics.HasSwaplet && !fCharacteristics.HasOptionlet && fCharacteristics.IsStandardPayoff && fCharacteristics.IsStandardLibor &&
                fCashflows.Compounding_Method != CompoundingMethod.Exponential)
            {
                if (fCharacteristics.IsOIS)
                {
                    fCashflows.CollectCashflowsOIS(cashAccumulators, fFxRate, baseDate, endDate, fBuySellSign, fForecastRate, fCutoffDate);
                }
                else
                {
                    fCashflows.CollectCashflowsSwap(cashAccumulators, fFxRate, baseDate, endDate, fBuySellSign, fForecastRate, fCutoffDate);
                }
            }
            else
            {
                fCashflows.CollectCashflows(cashAccumulators, fFxRate, fForecastFxRate, baseDate, endDate, fBuySellSign, fForecastRate, fCutoffDate);
            }

            double settlementDate = deal.Settlement_Date;

            if (settlementDate >= baseDate && settlementDate <= endDate)
            {
                using (var cache = Vector.Cache(cashAccumulators.NumScenarios))
                {
                    Vector settlementAmount = cache.GetClear();
                    if (deal.Settlement_Amount_Is_Clean == YesNo.Yes)
                    {
                        fCashflows.CalculateAccrual(settlementAmount, baseDate, settlementDate, false, deal.AccrualHolidayCalendar(), fForecastRate);
                    }

                    settlementAmount.Add(deal.Settlement_Amount);
                    cashAccumulators.Accumulate(fFxRate, settlementDate, -fBuySellSign * settlementAmount);
                }
            }
        }
        /// <summary>
        /// Calculate a valuation profile for a range of scenarios.
        /// </summary>
        public override void Value(ValuationResults valuationResults, PriceFactorList factors, BaseTimeGrid baseTimes)
        {
            IAssetPrice price  = GetAssetPrice(factors);
            PVProfiles  result = valuationResults.Profile;

            double scale = fDeal.Units * (fDeal.Buy_Sell == BuySell.Buy ? +1 : -1);

            var tgi = new TimeGridIterator(fT);

            VectorEngine.For(tgi, () => result.AppendVector(tgi.Date, scale * price.Get(tgi.T)));

            result.Complete(fT);

            CashAccumulators cashAccumulators = valuationResults.Cash;
            double           endDate          = Deal.EndDate();

            if (!cashAccumulators.Ignore && endDate <= fT.fHorizon)
            {
                double  tEnd   = CalcUtils.DaysToYears(endDate - factors.BaseDate);
                IFxRate fxRate = factors.GetInterface <IFxRate>(fDeal.Currency);
                cashAccumulators.Accumulate(fxRate, endDate, scale * price.Get(tEnd) / fxRate.Get(tEnd));
            }
        }
 /// <summary>
 /// Collect cashflows realised along the scenario path up to endDate.
 /// </summary>
 public abstract void CollectCashflows(CashAccumulators cashAccumulators, double baseDate, double endDate);
Example #10
0
 /// <inheritdoc />
 public override void CollectCashflows(CashAccumulators cashAccumulators, double baseDate, double endDate)
 {
     fCashflows.CollectCashflows(cashAccumulators, fFxRate, null, baseDate, endDate, fBuySellSign, fForecastRate, fCutoffDate);
 }
Example #11
0
        /// <summary>
        /// Generic Deal Valuation - derived objects override the ValueFn() method.
        /// </summary>
        public override void Value(ValuationResults valuationResults, PriceFactorList factors, BaseTimeGrid baseTimes)
        {
            PreValue(factors);

            var              deal        = (CalendarSpreadOption)Deal;
            var              tgi         = new TimeGridIterator(fT);
            PVProfiles       result      = valuationResults.Profile;
            CashAccumulators accumulator = valuationResults.Cash;

            fTimeToSettlement = CalcUtils.DaysToYears(deal.Settlement_Date - factors.BaseDate);
            fPeriodEnd1       = CalcUtils.DaysToYears(deal.Period_End_1 - factors.BaseDate);
            fPeriodEnd2       = CalcUtils.DaysToYears(deal.Period_End_2 - factors.BaseDate);

            // The time to expiry is the time to the end of the first expiring contract.
            fTimeToExpiry = CalcUtils.DaysToYears(deal.Period_End_1 - factors.BaseDate);

            using (var cache = Vector.Cache(factors.NumScenarios))
            {
                EnergySpreadOptionPricer pricer1 = GetEnergyOptionPricer(fForwardSample,
                                                                         fReferencePrice1,
                                                                         fReferenceVol1,
                                                                         factors.BaseDate,
                                                                         fPeriodEnd1,
                                                                         deal.Period_Start_1,
                                                                         deal.Period_End_1,
                                                                         deal.Realized_Average_1,
                                                                         deal.Realized_Average_Date_1,
                                                                         cache);

                EnergySpreadOptionPricer pricer2 = GetEnergyOptionPricer(fForwardSample,
                                                                         fReferencePrice2,
                                                                         fReferenceVol2,
                                                                         factors.BaseDate,
                                                                         fPeriodEnd2,
                                                                         deal.Period_Start_2,
                                                                         deal.Period_End_2,
                                                                         deal.Realized_Average_2,
                                                                         deal.Realized_Average_Date_2,
                                                                         cache);

                Vector pv               = cache.Get();
                Vector realizedPrice1   = cache.Get();
                Vector realizedPrice2   = cache.Get();
                Vector unrealizedPrice1 = cache.Get();
                Vector unrealizedPrice2 = cache.Get();
                Vector vol1             = cache.Get();
                Vector vol2             = cache.Get();
                Vector correlation      = cache.Get();
                Vector discountFactor   = cache.Get();

                // Calculate correlation between forward prices for two different (dereferenced) maturities (e.g. Apr2012 and Jan2013).
                TDate forwardDate1 = fReferencePrice1.GetPriceDate(deal.Period_End_1, 0);
                TDate forwardDate2 = fReferencePrice2.GetPriceDate(deal.Period_End_2, 0);
                fCorrelations.GetValue(correlation, tgi.T, forwardDate1, forwardDate2);

                while (tgi.Next())
                {
                    pv.Clear();

                    if (tgi.T <= fTimeToExpiry)
                    {
                        // Get unrealised reference forward prices (which also age the pricer to time t and update the realized average at time t)
                        pricer1.GetUnrealizedPrice(tgi.T, unrealizedPrice1);
                        pricer2.GetUnrealizedPrice(tgi.T, unrealizedPrice2);

                        // Get the realized averages for both reference prices.
                        pricer1.GetRealizedPrice(realizedPrice1);
                        pricer2.GetRealizedPrice(realizedPrice2);

                        int numSamples1           = pricer1.GetNumSamples();
                        int numRealizedSamples1   = pricer1.GetNumRealizedSamples();
                        int numUnrealizedSamples1 = pricer1.GetNumUnrealizedSamples();

                        int numSamples2           = pricer2.GetNumSamples();
                        int numRealizedSamples2   = pricer2.GetNumRealizedSamples();
                        int numUnrealizedSamples2 = pricer2.GetNumUnrealizedSamples();

                        // Modify the strike
                        Vector kStar = cache.Get(deal.Strike_Price
                                                 - realizedPrice1 * numRealizedSamples1 / numSamples1
                                                 + realizedPrice2 * numRealizedSamples2 / numSamples2);
                        Vector refPriceStar1 = cache.Get(unrealizedPrice1 * numUnrealizedSamples1 / numSamples1);
                        Vector refPriceStar2 = cache.Get(unrealizedPrice2 * numUnrealizedSamples2 / numSamples2);

                        // Get ATM volatilities of the forward price at different maturities (given as time in years with respect to base date).
                        pricer1.GetVol(tgi.T, unrealizedPrice2, vol1);
                        pricer2.GetVol(tgi.T, unrealizedPrice1, vol2);

                        // value is intrinsic - pricing with volatility 0 and realized price if there are no future sample.
                        if (numUnrealizedSamples1 == 0)
                        {
                            vol1.Clear();
                        }

                        // value is intrinsic - pricing with volatility 0 and realized price if there are no future sample.
                        if (numUnrealizedSamples2 == 0)
                        {
                            vol2.Clear();
                        }

                        // CSO pricing: exp(-rT) * E{max(F1(T) - F2(T) - K, 0)}
                        // For the European CSO,  we set multiplier1 = sign, multiplier2 = -sign, constant = -sign * strike,
                        // where sign = +1 for a call and -1 for a put in the SpreadOptionBS function.
                        double rootTime = Math.Sqrt(fTimeToExpiry - tgi.T);
                        Vector volStar1 = cache.Get(vol1 * rootTime);
                        Vector volStar2 = cache.Get(vol2 * rootTime);
                        PricingFunctions.SpreadOptionBS(pv, fCallPutSign, -fCallPutSign, cache.Get(-fCallPutSign * kStar), fCallPutSign,
                                                        refPriceStar1, refPriceStar2, kStar, volStar1, volStar2, correlation);

                        // The option itself cannot be worth less than zero (for long positions).
                        // However, due to that the Bjerksund & Stensland is a type of non-optimal exercise, it is possible to end up with negative PV via
                        // its pricing formula.
                        pv.AssignMax(pv, 0.0);

                        // Discount payment made at settlement date
                        pv.MultiplyBy(fScale * fDiscountRate.Get(tgi.T, fTimeToSettlement));
                    }

                    // Cash settlement at settlement date
                    if (tgi.T == fTimeToSettlement && accumulator != null && !accumulator.Ignore)
                    {
                        accumulator.Accumulate(fFxPayoffRate, tgi.Date, pv);
                    }

                    result.AppendVector(tgi.Date, pv * fFxPayoffRate.Get(tgi.T));
                }

                result.Complete(fT);
            }
        }
Example #12
0
 /// <summary>
 /// Age the option by updating its status to reflect the market state on a given day.
 /// </summary>
 protected override void Age(CashAccumulators cashAccumulators, double time, double date)
 {
 }
Example #13
0
        /// <summary>
        /// Valuation method.
        /// </summary>
        public override void Value(ValuationResults valuationResults, PriceFactorList factors, BaseTimeGrid baseTimes)
        {
            CDOValuationParameters parameters = GetValuationParameters(factors);

            double scale       = (fDeal.Buy_Sell == BuySell.Buy) ? +fDeal.Principal : -fDeal.Principal;
            double trancheSize = fDeal.Detachment - fDeal.Attachment;

            if (trancheSize < CalcUtils.TINY)
            {
                return;
            }

            double tUpfront = CalcUtils.DaysToYears(fDeal.Upfront_Date - factors.BaseDate);

            TimeGridIterator tgi         = new TimeGridIterator(fT);
            CashAccumulators accumulator = valuationResults.Cash;
            PVProfiles       result      = valuationResults.Profile;

            using (IntraValuationDiagnosticsHelper.StartDeal(fIntraValuationDiagnosticsWriter, Deal))
            {
                VectorEngine.For(tgi, () =>
                {
                    using (var cache = Vector.Cache(factors.NumScenarios))
                    {
                        Vector npv = cache.Get();
                        Vector expectedWritedownPremiumNotional = cache.Get();
                        Vector expectedLoss          = cache.Get();
                        Vector expectedRecovery      = cache.Get();
                        Vector discountFactor        = cache.Get();
                        Vector realizedIndexLoss     = cache.Get();
                        Vector realizedIndexRecovery = cache.Get();
                        Vector adjustedAttachment    = cache.Get();
                        Vector adjustedDetachment    = cache.Get();
                        Vector trancheRemainder      = cache.Get();

                        // Handle upfront payment
                        if (fDeal.Upfront_Date >= tgi.Date)
                        {
                            npv.Assign(scale * parameters.DF.Get(tgi.T, tUpfront) * fDeal.Upfront_Amount);
                        }
                        else
                        {
                            npv.Clear();
                        }

                        // reinitialise running variables
                        expectedWritedownPremiumNotional.Clear();
                        expectedLoss.Clear();
                        expectedRecovery.Clear();
                        discountFactor.Assign(parameters.DF.Get(tgi.T, tgi.T));

                        if (accumulator != null && tgi.Date == fDeal.Upfront_Date)
                        {
                            accumulator.Accumulate(parameters.X, tgi.Date, fDeal.Upfront_Amount);
                        }

                        // Check for realized loss and recovery and adjust the attachment and detachment accordingly
                        parameters.RealizedLoss(realizedIndexLoss, realizedIndexRecovery, tgi.T, fDeal.Payoff_Is_Digital == YesNo.Yes, fDeal.Digital_Payoff_Percentage);

                        adjustedDetachment.Assign(VectorMath.Max(0.0, VectorMath.Min(1.0 - realizedIndexRecovery, fDeal.Detachment) - realizedIndexLoss));
                        adjustedAttachment.Assign(VectorMath.Max(0.0, VectorMath.Min(1.0 - realizedIndexRecovery, fDeal.Attachment) - realizedIndexLoss));

                        trancheRemainder.Assign((adjustedDetachment - adjustedAttachment) / trancheSize);

                        if (adjustedDetachment.MaxElement() > CalcUtils.TINY)
                        {
                            // Diagnostics
                            double sumDefaultAccrual = 0;
                            double sumPVPremium      = 0;
                            double sumPVProtection   = 0;

                            bool needDiagnostics = tgi.T == 0.0 && fIntraValuationDiagnosticsWriter.Level > IntraValuationDiagnosticsLevel.None;

                            using (needDiagnostics ? IntraValuationDiagnosticsHelper.StartCDO(fIntraValuationDiagnosticsWriter, tgi.Date, fDeal.Principal) : null)
                            {
                                // Value future coupon periods
                                VectorEngine.For(0, PayDates.Count, i =>
                                {
                                    if (PayDates[i] < tgi.Date)
                                    {
                                        return(LoopAction.Continue);
                                    }

                                    double tPay = CalcUtils.DaysToYears(PayDates[i] - factors.BaseDate);

                                    using (var innerCache = Vector.CacheLike(npv))
                                    {
                                        Vector oldExpectedLoss   = innerCache.Get(expectedLoss);
                                        Vector oldDiscountFactor = innerCache.Get(discountFactor);
                                        Vector oldExpectedWritedownPremiumNotional = innerCache.Get(expectedWritedownPremiumNotional);

                                        Vector expectedLossAttachment     = innerCache.Get();
                                        Vector expectedLossDetachment     = innerCache.Get();
                                        Vector premiumLeg                 = innerCache.Get();
                                        Vector defaultLeg                 = innerCache.Get();
                                        Vector accruedInDefault           = innerCache.Get();
                                        Vector expectedRecoveryAttachment = innerCache.Get();
                                        Vector expectedRecoveryDetachment = innerCache.Get();
                                        Vector avgDiscountFactor          = innerCache.Get();
                                        Vector pv = innerCache.Get();

                                        // Get the expected loss and recovery for the tranche detachment and attachment
                                        parameters.ExpectedLossAndRecovery(expectedLossDetachment, expectedRecoveryDetachment, tgi.T, tPay, adjustedDetachment, realizedIndexLoss, realizedIndexRecovery);
                                        parameters.ExpectedLossAndRecovery(expectedLossAttachment, expectedRecoveryAttachment, tgi.T, tPay, adjustedAttachment, realizedIndexLoss, realizedIndexRecovery);

                                        expectedLoss.Assign((expectedLossDetachment - expectedLossAttachment) / trancheSize);
                                        expectedRecovery.Assign((expectedRecoveryDetachment - expectedRecoveryAttachment) / trancheSize);
                                        expectedWritedownPremiumNotional.Assign(expectedLoss + expectedRecovery);

                                        // Premium leg approximation: Accrued in default pays half the accrued. Remove expected loss and recovery (top down writeoff)
                                        premiumLeg.Assign(fDeal.Spread * (trancheRemainder - expectedWritedownPremiumNotional) * Accruals[i]);
                                        accruedInDefault.Assign(fDeal.Spread * (expectedWritedownPremiumNotional - oldExpectedWritedownPremiumNotional) * 0.5 * Accruals[i]);

                                        // Default leg approximation: account for default with bullet payment at end of period
                                        defaultLeg.Assign(expectedLoss - oldExpectedLoss);

                                        // Convention: bought CDO pays the premium to the buyer
                                        discountFactor.Assign(parameters.DF.Get(tgi.T, tPay));
                                        avgDiscountFactor.Assign(0.5 * (discountFactor + oldDiscountFactor));

                                        pv.Assign(scale * (premiumLeg * discountFactor + (accruedInDefault - defaultLeg) * avgDiscountFactor));
                                        npv.Add(pv);

                                        if (accumulator != null && tgi.T == tPay)
                                        {
                                            accumulator.Accumulate(parameters.X, tgi.Date, scale * (premiumLeg + accruedInDefault - defaultLeg));
                                        }

                                        if (needDiagnostics)
                                        {
                                            using (var innerCache1 = Vector.CacheLike(npv))
                                            {
                                                Vector expectedPremium        = innerCache1.Get(scale * premiumLeg);
                                                Vector expectedDefaultAccrual = innerCache1.Get(scale * accruedInDefault);
                                                Vector expectedDefaultLoss    = innerCache1.Get(scale * defaultLeg);

                                                Vector pvDefaultAccrual = innerCache1.Get(expectedDefaultAccrual * avgDiscountFactor);
                                                Vector pvPremium        = innerCache1.Get(expectedPremium * discountFactor);
                                                Vector pvProctection    = innerCache1.Get(-expectedDefaultLoss * avgDiscountFactor);

                                                // accumulate sums
                                                if (i >= 0)
                                                {
                                                    sumDefaultAccrual += pvDefaultAccrual[0];
                                                    sumPVPremium      += pvPremium[0];
                                                    sumPVProtection   += pvProctection[0];
                                                }

                                                using (IntraValuationDiagnosticsHelper.StartCashflow(fIntraValuationDiagnosticsWriter, PayDates[i]))
                                                {
                                                    var remainingPool = cache.Get(1.0 - realizedIndexLoss - realizedIndexRecovery);
                                                    AddIntraValuationDiagnostics(fIntraValuationDiagnosticsWriter, parameters, adjustedAttachment, adjustedDetachment,
                                                                                 remainingPool, tgi.T, tPay);
                                                    IntraValuationDiagnosticsHelper.AddDetailedCDOCashflow(fIntraValuationDiagnosticsWriter,
                                                                                                           expectedPremium, expectedRecovery, expectedDefaultAccrual, expectedDefaultLoss, discountFactor, pv);
                                                }
                                            }
                                        }
                                    }

                                    return(LoopAction.Continue);
                                });

                                if (needDiagnostics)
                                {
                                    IntraValuationDiagnosticsHelper.AddSummaryCDOAmounts(fIntraValuationDiagnosticsWriter, npv, sumDefaultAccrual,
                                                                                         sumPVPremium, sumPVProtection);
                                }
                            }

                            result.AppendVector(tgi.Date, npv * parameters.X.Get(tgi.T));
                        }
                    }
                });
            }

            // After maturity
            result.Complete(fT);
        }
Example #14
0
        /// <summary>
        /// Calculate valuation profiles.
        /// </summary>
        public override void Value(ValuationResults valuationResults, PriceFactorList factors, BaseTimeGrid baseTimes)
        {
            PreValue(factors);

            TimeGridIterator tgi              = new TimeGridIterator(fT);
            PVProfiles       result           = valuationResults.Profile;
            CashAccumulators cashAccumulators = valuationResults.Cash;

            BondOptionDeal deal = (BondOptionDeal)Deal;

            double baseDate  = factors.BaseDate;
            double notional  = deal.Notional;
            double interval  = deal.Coupon_Interval;
            double buySign   = (deal.Buy_Sell == BuySell.Buy) ? +1 : -1;
            double paySign   = (deal.Option_Type == OptionType.Call) ? +1 : -1;
            double coupon    = Percentage.PercentagePoint * deal.Coupon_Rate;
            double tExpiry   = CalcUtils.DaysToYears(deal.Expiry_Date - baseDate);
            double tMaturity = CalcUtils.DaysToYears(deal.Bond_Maturity_Date - baseDate);

            IInterestYieldVol interestYieldVol = InterestVolBase.GetYieldVol(factors, deal.Yield_Volatility, fCurrency);

            if ((deal.Amortisation) != null && (deal.Amortisation.Count > 0))
            {
                notional = deal.Amortisation.GetPrincipal(notional, deal.Expiry_Date);
            }

            bool respectDefault = Respect_Default == YesNo.Yes && fCreditRating != null;

            using (IntraValuationDiagnosticsHelper.StartDeal(fIntraValuationDiagnosticsWriter, Deal))
            {
                using (var pricerCache = Vector.Cache(factors.NumScenarios))
                {
                    Vector defaultTime        = null;
                    Vector bondIsAlive        = null;
                    Vector historicalRecovery = null;

                    if (respectDefault)
                    {
                        defaultTime        = pricerCache.Get();
                        bondIsAlive        = pricerCache.Get(1.0);
                        historicalRecovery = pricerCache.GetClear();

                        fCreditRating.DefaultTime(defaultTime);
                    }

                    var defaultedBeforeBaseDate = respectDefault && CreditRating.DefaultedBeforeBaseDate(fCreditRating, baseDate);

                    VectorEngine.For(tgi, () =>
                    {
                        using (IntraValuationDiagnosticsHelper.StartValuation(fIntraValuationDiagnosticsWriter, tgi.Date))
                        {
                            using (var cache = Vector.Cache(factors.NumScenarios))
                            {
                                Vector optionValue      = cache.GetClear();
                                Vector stdDev           = cache.Get(); // Std.Dev of Price
                                Vector stdDevYield      = cache.Get(); //Std.Dev of Yield
                                Vector price            = cache.Get();
                                Vector yield            = cache.Get();
                                Vector macaulayDuration = cache.Get();
                                Vector bondValue        = cache.Get();
                                Vector df  = cache.Get();
                                Vector dfr = fRepoIsDiscount ? null : cache.Get();

                                if (defaultedBeforeBaseDate)
                                {
                                    result.AppendVector(tgi.Date, optionValue);
                                    return(LoopAction.Break);
                                }

                                // This BondPrice function returns the value of the bond cashflows after ExpiryDate, including accrual, discounted back to T.date
                                double accrual, cash;
                                PricingFunctions.BondPrice(bondValue, out accrual, out cash, baseDate, tgi.Date, deal.Expiry_Date, deal.Issue_Date, deal.Bond_Maturity_Date, notional, coupon, fPayDates, fAccruals, fDiscountRate, deal.Amortisation, fPrincipals, fFinalPrincipal, fSurvivalProb, +1.0);

                                // Now check scenario by scenario for defaults, overwriting bondValue as necessary
                                if (respectDefault)
                                {
                                    AdjustBondValueForDefault(notional, tExpiry, bondValue, bondIsAlive, historicalRecovery, defaultTime, tgi.T, fDiscountRate, fRecoveryRate);
                                }

                                // convert price and duration to forward (tExpiry) basis
                                if (tgi.Date == deal.Expiry_Date)
                                {
                                    optionValue.Assign(buySign * VectorMath.Max(0.0, paySign * (bondValue - notional * fStrike)));
                                    cashAccumulators.Accumulate(fFxRate, tgi.Date, optionValue);
                                }
                                else
                                {
                                    fDiscountRate.GetValue(df, tgi.T, tExpiry);

                                    if (fRepoIsDiscount)
                                    {
                                        dfr = df;
                                    }
                                    else
                                    {
                                        fRepoRate.GetValue(dfr, tgi.T, tExpiry);
                                    }

                                    // Need yield and duration to convert yield vol to price vol.
                                    PricingFunctions.BondForwardPriceAndAdjustedMacaulayDuration(price, macaulayDuration, tgi.T, tExpiry, tMaturity, coupon, interval, df, fDiscountRate, fSurvivalProb);
                                    PricingFunctions.BondYieldFromPrice(yield, tExpiry, tMaturity, coupon, interval, price);

                                    // Calculate Modified Duration from Macaulay Duration.
                                    Vector modifiedDuration = cache.GetClear();
                                    PricingFunctions.GetModifiedDuration(modifiedDuration, macaulayDuration, yield, interval);

                                    // Calculate Std.Dev of Yield and Price
                                    interestYieldVol.GetStdDev(stdDevYield, tgi.T, yield, fStrikeYield, tExpiry, tMaturity - tExpiry);
                                    stdDev.Assign(modifiedDuration * stdDevYield);

                                    if (interestYieldVol.GetDistributionType() == ProbabilityDistribution.Lognormal)
                                    {
                                        stdDev.MultiplyBy(yield);
                                    }

                                    price.AssignQuotient(bondValue, df);
                                    PricingFunctions.BlackFunction(optionValue, deal.Option_Type, price, notional * fStrike, stdDev);

                                    optionValue.MultiplyBy(buySign * dfr);

                                    if (fIntraValuationDiagnosticsWriter.Level > IntraValuationDiagnosticsLevel.None)
                                    {
                                        // Add Intra-valuation Diagnostics
                                        using (var volatilitiesAtDateStore = IntraValuationDiagnosticsHelper.CreateVolatilitiesAtDateStore(fIntraValuationDiagnosticsWriter, factors.NumScenarios))
                                            using (var volatilitiesYieldAtDateStore = IntraValuationDiagnosticsHelper.CreateVolatilitiesAtDateStore(fIntraValuationDiagnosticsWriter, factors.NumScenarios))
                                            {
                                                volatilitiesAtDateStore.Add(tgi.Date, tgi.TimeGrid.fEndDate, stdDev);
                                                volatilitiesYieldAtDateStore.Add(tgi.Date, tgi.TimeGrid.fEndDate, stdDevYield);
                                                IntraValuationDiagnosticsHelper.AddBondOptionProperties(fIntraValuationDiagnosticsWriter, price, dfr, bondValue, accrual,
                                                                                                        volatilitiesAtDateStore, volatilitiesYieldAtDateStore);
                                                IntraValuationDiagnosticsHelper.AddCashflowsPV(fIntraValuationDiagnosticsWriter, optionValue);
                                            }
                                    }
                                }

                                result.AppendVector(tgi.Date, fFxRate.Get(tgi.T) * optionValue);
                                return(LoopAction.Continue);
                            }
                        }
                    });
                }

                result.Complete(fT);
            }
        }
Example #15
0
        /// <summary>
        /// Value the deal from given base date, price factors and time grid.
        /// </summary>
        public void Value(PVProfiles pvResults, CashAccumulators cashResults, double baseDate, IInterestRate discountRate, IInterestRate forecastRate1, IInterestRate forecastRate2, IFxRate fxRate, TimeGrid timeGrid, int numScenarios)
        {
            var tgi  = new TimeGridIterator(timeGrid);
            var deal = (FloatingInterestCashflowInterpolatedDeal)Deal;

            bool   hasRate1          = deal.HasRate1();
            bool   hasRate2          = deal.HasRate2();
            double scale             = deal.Buy_Sell == BuySell.Buy ? +deal.Principal : -deal.Principal;
            double tPay              = CalcUtils.DaysToYears(fPaymentDate - baseDate);
            double tReset            = CalcUtils.DaysToYears(deal.Reset_Date - baseDate);
            double tRateStart        = CalcUtils.DaysToYears(deal.Rate_Start_Date - baseDate);
            double tRateEnd1         = hasRate1 ? CalcUtils.DaysToYears(fRate1EndDate - baseDate) : 0.0;
            double tRateEnd2         = hasRate2 ? CalcUtils.DaysToYears(fRate2EndDate - baseDate) : 0.0;
            double tRateEnd12        = tRateEnd2 - tRateEnd1;                                                                    // Time from rate 1 end date to rate 2 end date.
            double tAccrualEnd       = CalcUtils.DaysToYears(deal.Accrual_End_Date - baseDate);
            double interpCoefficient = Math.Abs(tRateEnd12) >= CalcUtils.MinTime ? (tAccrualEnd - tRateEnd1) / tRateEnd12 : 0.0; // Coefficient used to calculate interpolated rate.

            VectorEngine.For(tgi, () =>
            {
                using (var cache = Vector.Cache(numScenarios))
                {
                    Vector pv = cache.Get();

                    if (tgi.Date <= fPaymentDate && fPaymentDate > fCutoffDate)
                    {
                        Vector interpRate = cache.GetClear();
                        Vector rate1      = cache.GetClear();
                        Vector rate2      = cache.GetClear();

                        if (hasRate1)
                        {
                            if (fKnownResetRate1.HasValue)
                            {
                                rate1.Assign(fKnownResetRate1.Value);
                            }
                            else
                            {
                                InterestRateUtils.LiborRate(rate1, forecastRate1, tgi.T, tReset, tRateStart, tRateEnd1, fRate1YearFraction);
                            }
                        }

                        if (hasRate2)
                        {
                            if (fKnownResetRate2.HasValue)
                            {
                                rate2.Assign(fKnownResetRate2.Value);
                            }
                            else
                            {
                                InterestRateUtils.LiborRate(rate2, forecastRate2, tgi.T, tReset, tRateStart, tRateEnd2, fRate2YearFraction);
                            }
                        }

                        if (hasRate1 && hasRate2)
                        {
                            if (Math.Abs(tRateEnd12) >= CalcUtils.MinTime)
                            {
                                interpRate.Assign(rate1 + interpCoefficient * (rate2 - rate1));
                            }
                            else
                            {
                                interpRate.Assign(0.5 * rate1 + 0.5 * rate2);
                            }
                        }
                        else
                        {
                            interpRate.Assign(hasRate1 ? rate1 : rate2);
                        }

                        // Round the calculated rate, regardless whether the valuation date is before or after the reset date.
                        CFFloatingInterestList.RoundRateTo(deal.Interpolated_Rate_Rounding, interpRate);

                        pv.Assign(scale * (interpRate + deal.Margin) * fAccrualYearFraction);

                        CFFixedList.RoundCashflow(pv, Cashflow_Rounding);

                        if (tgi.Date < fPaymentDate)
                        {
                            pv.MultiplyBy(discountRate.Get(tgi.T, tPay));
                        }
                        else if (tgi.Date == fPaymentDate)
                        {
                            cashResults.Accumulate(fxRate, fPaymentDate, pv);
                        }
                    }
                    else
                    {
                        pv.Clear();
                    }

                    pvResults.AppendVector(tgi.Date, pv * fxRate.Get(tgi.T));
                }
            });

            // After maturity
            pvResults.Complete(timeGrid);
        }
        /// <summary>
        /// Calculate a valuation profile for the deal for the current scenario.
        /// </summary>
        public override void Value(ValuationResults valuationResults, PriceFactorList factors, BaseTimeGrid baseTimes)
        {
            PreValue(factors);

            var deal = (CFListBaseDeal <TCashflowList>)fDeal;

            double baseDate = factors.BaseDate;

            var              tgi              = new TimeGridIterator(fT);
            PVProfiles       result           = valuationResults.Profile;
            CashAccumulators cashAccumulators = valuationResults.Cash;

            double endDate = deal.EndDate();

            using (IntraValuationDiagnosticsHelper.StartDeal(fIntraValuationDiagnosticsWriter, fDeal))
            {
                using (var outerCache = Vector.Cache(factors.NumScenarios))
                {
                    Vector defaultDate = fCreditRating != null?outerCache.Get(CalcUtils.DateTimeMaxValueAsDouble) : null;

                    var  defaultedBeforeBaseDate = CreditRating.DefaultedBeforeBaseDate(fCreditRating, baseDate);
                    bool collectCash             = ValueOnCashflowDates();

                    var saccrResult = SACCRResultFactory.Create(valuationResults, deal.GetDealReferenceProvider().DealReference,
                                                                () => new SACCROptionResult(factors.NumScenarios));

                    VectorEngine.For(tgi, () =>
                    {
                        using (var cache = Vector.Cache(factors.NumScenarios))
                        {
                            Vector pv   = cache.GetClear();
                            Vector cash = collectCash ? cache.GetClear() : null;

                            if (!defaultedBeforeBaseDate)
                            {
                                using (IntraValuationDiagnosticsHelper.StartCashflowsOnDate(fIntraValuationDiagnosticsWriter, tgi.Date))
                                {
                                    using (IntraValuationDiagnosticsHelper.StartCashflows(fIntraValuationDiagnosticsWriter, fFxRate, tgi.T, deal))
                                    {
                                        Value(pv, cash, baseDate, tgi.Date, saccrResult, fIntraValuationDiagnosticsWriter);
                                        IntraValuationDiagnosticsHelper.AddCashflowsPV(fIntraValuationDiagnosticsWriter, pv);
                                    }
                                }

                                if (fCreditRating != null)
                                {
                                    UpdateDefaultDate(fCreditRating, tgi.Date, tgi.T, defaultDate);
                                    GetDefaultValue(baseDate, tgi.Date, defaultDate, fRecoveryRate, pv, cash);
                                }
                            }

                            result.AppendVector(tgi.Date, pv * fFxRate.Get(tgi.T));

                            if (!cashAccumulators.Ignore && cash != null)
                            {
                                // Realise all value as cash on deal end date
                                if (tgi.Date == endDate)
                                {
                                    cash.Assign(pv);
                                }

                                cashAccumulators.Accumulate(fFxRate, tgi.Date, cash);
                            }
                        }
                    });

                    if (!cashAccumulators.Ignore && !collectCash)
                    {
                        CollectCashflows(cashAccumulators, baseDate, fT.fHorizon);

                        // Consolidate and net in order to avoid getting Net incoming and outgoing cashflows with the same payment date,
                        // e.g. for compounding swaps with both positive and negative rates.
                        cashAccumulators.ConsolidateAndNet(fCurrency, factors);
                    }

                    result.Complete(fT);
                }
            }
        }
Example #17
0
        /// <summary>
        /// Vector valuation function.
        /// </summary>
        public override void Value(ValuationResults valuationResults, PriceFactorList factors, BaseTimeGrid baseTimes)
        {
            PreValue(factors);

            TimeGridIterator         tgi         = new TimeGridIterator(fT);
            PVProfiles               result      = valuationResults.Profile;
            CashAccumulators         accumulator = valuationResults.Cash;
            DealCreditLinkedNoteBase deal        = (DealCreditLinkedNoteBase)fDeal;

            ISurvivalProb SP = GetSurvivalProbability(factors);
            RecoveryRate  RR = GetRecoveryRate(factors);
            CreditRating  CR = GetCreditRating(factors);

            double tEffective    = CalcUtils.DaysToYears(deal.Effective_Date - factors.BaseDate);
            double scale         = (deal.Buy_Sell == BuySell.Buy) ? +deal.Notional_Amount : -deal.Notional_Amount;
            double purchasePrice = Percentage.PercentagePoint * deal.Price;
            double couponRate    = (deal.Coupon_Type == InterestRateType.Fixed) ? Percentage.PercentagePoint * deal.Coupon_Rate : 0.0;
            double couponSpread  = (deal.Coupon_Type == InterestRateType.Fixed) ? 0.0 : BasisPoint.BasisPointValue * deal.Coupon_Spread;
            double indexTenor    = (deal.Index_Tenor > 0.0) ? deal.Index_Tenor : deal.Coupon_Interval;

            using (var cache = Vector.Cache(factors.NumScenarios))
            {
                bool[] hasDefaulted       = (Respect_Default == YesNo.Yes) ? new bool[factors.NumScenarios] : null;
                Vector defaultTime        = (Respect_Default == YesNo.Yes) ? cache.Get() : null;
                Vector historicalRecovery = (Respect_Default == YesNo.Yes) ? cache.GetClear() : null;

                if (hasDefaulted != null && CR != null)
                {
                    DefaultTime(defaultTime, CR);
                }

                Vector npv      = cache.Get();
                Vector cash     = cache.Get();
                Vector pStart   = cache.Get();
                Vector pEnd     = cache.Get();
                Vector amount   = cache.Get();
                Vector recovery = cache.Get();
                Vector dfLast   = cache.Get();
                Vector df       = cache.Get();

                cash.Clear();
                var defaultedBeforeTheBaseDate = Respect_Default == YesNo.Yes &&
                                                 CreditRating.DefaultedBeforeBaseDate(CR, factors.BaseDate);
                while (tgi.Next())
                {
                    if (defaultedBeforeTheBaseDate)
                    {
                        npv.Clear();
                        result.AppendVector(tgi.Date, npv);
                        break;
                    }

                    if (!deal.Principal_Guaranteed && Respect_Default == YesNo.Yes)
                    {
                        RealizedRecoveryRate(recovery, RR, tgi.T);
                    }

                    // Assume defaults are rare and start by valuing under all scenarios without realized defaults

                    // Value of principal repayment
                    SurvivalProbability(pEnd, factors, SP, tgi.T, fT.fLast);
                    fDiscountRate.GetValue(dfLast, tgi.T, fT.fLast);
                    if (deal.Principal_Guaranteed)
                    {
                        npv.Assign(dfLast);
                    }
                    else
                    {
                        npv.Assign(dfLast * pEnd);
                    }
                    if (accumulator != null && tgi.T == fT.fLast)
                    {
                        cash.Assign(npv);
                    }

                    // Value of coupons
                    for (int i = PayDates.Count - 1; i >= 0 && tgi.Date <= PayDates[i]; --i)
                    {
                        double tPay      = CalcUtils.DaysToYears(PayDates[i] - factors.BaseDate);
                        double tReset    = CalcUtils.DaysToYears(ResetDates[i] - factors.BaseDate);
                        double tPrevious = Math.Max(tgi.T, tReset);
                        SurvivalProbability(pStart, factors, SP, tgi.T, tPrevious);

                        if (deal.Coupon_Type == InterestRateType.Floating)
                        {
                            // Forecast a coupon, add the spread
                            InterestRateUtils.LiborRate(amount, fForecastRate, tgi.T, tReset, tReset, tReset + indexTenor, deal.Index_Day_Count);
                            amount.Add(couponSpread);
                            amount.MultiplyBy(Accruals[i]);
                        }
                        else
                        {
                            // Fixed coupon
                            amount.Assign(couponRate * Accruals[i]);
                        }

                        // The value of the coupon if no default
                        npv.Add(amount * fDiscountRate.Get(tgi.T, tPay) * pEnd);
                        if (accumulator != null && tgi.T == tPay)
                        {
                            cash.Assign(amount);
                        }

                        // The recovery value on default - assume guaranteed principal paid at end, recovery paid immediately
                        if (!deal.Principal_Guaranteed)
                        {
                            npv.Add(fDiscountRate.Get(tgi.T, 0.5 * (tPay + tPrevious)) * (pStart - pEnd) * PricingRecoveryRate(SP));
                        }

                        pEnd.DestructiveAssign(pStart);
                    }

                    // Now check for realized default scenario by scenario, overwriting NPV and cash as appropriate
                    if (Respect_Default == YesNo.Yes && defaultTime != null)
                    {
                        if (tgi.T < tEffective)
                        {
                            fDiscountRate.GetValue(df, tgi.T, tEffective);
                        }

                        for (int i = 0; i < npv.Count; ++i)
                        {
                            if (defaultTime[i] > tgi.T)
                            {
                                continue;
                            }

                            if (deal.Principal_Guaranteed)
                            {
                                npv[i] = dfLast[i];   // full principal paid at maturity
                            }
                            else
                            {
                                if (!hasDefaulted[i])
                                {
                                    historicalRecovery[i] = recovery[i];   // record the historical recovery rate
                                }
                                if (tgi.T < tEffective)
                                {
                                    npv[i] = df[i] * historicalRecovery[i];   // The discounted recovery value of the principal will be paid out on the effective date
                                }
                                else if (tgi.T == tEffective || !hasDefaulted[i])
                                {
                                    npv[i] = historicalRecovery[i];           // The full recovery amount is paid out
                                }
                                else
                                {
                                    npv[i] = 0.0;                             // default is in the past but we are after effective date; settlement has already occurred.
                                }
                            }

                            hasDefaulted[i] = true;
                        }
                    }

                    // Value of purchase price
                    if (tgi.T < tEffective)
                    {
                        npv.Add(-purchasePrice * fDiscountRate.Get(tgi.T, tEffective));
                    }
                    else if (tgi.T == tEffective)
                    {
                        npv.Add(-purchasePrice);
                        if (accumulator != null)
                        {
                            cash.Add(-purchasePrice);
                        }
                    }

                    result.AppendVector(tgi.Date, scale * npv * fFxRate.Get(tgi.T));
                    if (accumulator != null)
                    {
                        accumulator.Accumulate(fFxRate, tgi.Date, scale * cash);
                    }
                }

                // After maturity
                result.Complete(fT);
            }
        }
        /// <summary>
        /// Value the deal on all dates within the valuation grid (vectorised).
        /// </summary>
        public override void Value(ValuationResults valuationResults, PriceFactorList factors, BaseTimeGrid baseTimes)
        {
            var    deal             = (AverageForwardExplicitDealBase)Deal;
            double tMaturity        = CalcUtils.DaysToYears(deal.Maturity_Date - factors.BaseDate); // Discount Factor and Forward Factor times are in Act365.
            int    numSamplingDates = fSamplingTimes.Length;

            PreValue(factors);

            PVProfiles       result = valuationResults.Profile;
            CashAccumulators cash   = valuationResults.Cash;
            var tgi = new TimeGridIterator(fT);

            using (var pricerCache = Vector.Cache(factors.NumScenarios))
            {
                double historicalObservations;
                double futureObservations;
                int    currentDateCount;
                Vector realisedSum  = pricerCache.GetClear();             // sum to value date.
                Vector forecastSum  = pricerCache.Get();
                Vector spotPrice    = pricerCache.Get();
                Vector forwardPrice = pricerCache.Get();

                double tSpotPrice = double.NegativeInfinity;
                GetForwardPrice(0.0, deal.Tenor, true, ref tSpotPrice, spotPrice, forwardPrice);
                fSamplingData.GetInitialSum(null, factors.BaseDate, forwardPrice, realisedSum, out historicalObservations, out futureObservations, out currentDateCount);

                VectorEngine.For(tgi, () =>
                {
                    using (var cache = Vector.Cache(factors.NumScenarios))
                    {
                        Vector overallAverage = cache.Get();
                        Vector value          = cache.Get();
                        Vector payoffRate     = cache.Get();

                        UpdateSum(tgi.Date, realisedSum, ref tSpotPrice, spotPrice, ref historicalObservations, ref futureObservations, ref currentDateCount);
                        forecastSum.Clear();

                        // all the sampling dates that are in the future (compared to our valuation date)
                        VectorEngine.For(currentDateCount, numSamplingDates, i =>
                        {
                            GetForwardPrice(tgi.T, fSamplingTimesPlusTenor[i], false, ref tSpotPrice, spotPrice,
                                            forwardPrice);
                            forecastSum.AddProduct(fSamplingData[i].Weight, forwardPrice);

                            return(LoopAction.Continue);
                        });

                        forecastSum.MultiplyBy(spotPrice);
                        double totalWeight = historicalObservations + futureObservations;
                        if (totalWeight > 0.0)
                        {
                            overallAverage.Assign((realisedSum + forecastSum) / totalWeight);
                        }
                        else
                        {
                            overallAverage.Clear();
                        }

                        PayoffRate(payoffRate, overallAverage, ref tSpotPrice, spotPrice, tgi.T, tMaturity);
                        value.Assign(fScale * fDiscountRate.Get(tgi.T, tMaturity) * payoffRate);

                        if (tgi.Date == deal.Maturity_Date)
                        {
                            cash.Accumulate(fPayoffFxRate, tgi.Date, value);
                        }

                        result.AppendVector(tgi.Date, value * fPayoffFxRate.Get(tgi.T));
                    }
                });

                result.Complete(fT);
            }
        }
Example #19
0
        /// <summary>
        /// Calculate valuation profiles.
        /// </summary>
        public override void Value(ValuationResults valuationResults, PriceFactorList factors, BaseTimeGrid baseTimes)
        {
            PreValue(factors);

            TimeGridIterator tgi             = new TimeGridIterator(fT);
            PVProfiles       result          = valuationResults.Profile;
            CashAccumulators cashAccumulator = valuationResults.Cash;
            double           baseDate        = factors.BaseDate;

            CallableStructuredDeal deal = (CallableStructuredDeal)fDeal;

            int buySellSign = deal.Buy_Sell == BuySell.Buy ? +1 : -1;
            int callPutSign = deal.Option_Type == OptionType.Call ? 1 : -1;

            InterestRateOptionPricer optionPricer = CreateOptionPricer(factors);

            CalcUtils.CreateDealProfilesIfRequired(valuationResults, fItems, factors);

            bool needRating = Respect_Default == YesNo.Yes && !string.IsNullOrEmpty(deal.Issuer);

            using (var cache = Vector.Cache(factors.NumScenarios))
            {
                Vector exercised      = cache.GetClear(); // vector taking value 0 or 1 indicating exercise before tgi.date
                Vector exercisedToday = cache.Get();      // vector taking value 0 or 1 indicating exercise at tgi.date

                Vector optionPv = cache.Get();
                Vector pv       = cache.Get();
                Vector cash     = cache.Get();
                Vector settlementDateAtExercise = cache.GetClear();
                Vector defaultDate = needRating ? cache.Get(CalcUtils.DateTimeMaxValueAsDouble) : null;

                var defaultedBeforeBaseDate = needRating &&
                                              CreditRating.DefaultedBeforeBaseDate(fCreditRating, baseDate);

                while (tgi.Next())
                {
                    if (defaultedBeforeBaseDate)
                    {
                        pv.Clear();
                        result.AppendVector(tgi.Date, pv);
                        break;
                    }

                    if (needRating)
                    {
                        UpdateDefaultDate(fCreditRating, tgi.Date, tgi.T, defaultDate);
                    }

                    double val;
                    bool   allExercised = exercised.AllElementsTheSame(out val) && val == 1.0;

                    if (deal.Settlement_Style == SettlementType2.Physical)
                    {
                        // Calculate value of option (option value is zero after last exercise date)
                        if (!allExercised)
                        {
                            optionPricer.Value(baseDate, tgi.Date, optionPv, exercised, exercisedToday, settlementDateAtExercise, defaultDate);
                        }

                        // Calculate value of underlying cashflows after settlementDateAtExercise
                        pv.Clear();
                        cash.Clear();
                        InterestRateOptionPricer.ValueDeals(fItems, pv, cash, baseDate, tgi.Date, settlementDateAtExercise, defaultDate, fDiscountRate, fForecastRate, fRepoRate, fInterestRateVol, fInterestYieldVol, fSurvivalProb, fRecoveryRate);
                        pv.MultiplyBy(callPutSign);
                        cash.MultiplyBy(callPutSign);

                        if (!allExercised)
                        {
                            // If exercised today the cashflow is the value of the option minus the value of the physically settled part
                            // Else if already exercised, cash is the unnderlying cash.
                            // Else (before exercise) there is no cash.
                            cash.AssignConditional(exercisedToday, optionPv - pv, exercised * cash);

                            // If already exercised, pv is the unnderlying pv.
                            // Else (before exercise or exercised today), pv is the option pv.
                            pv.AssignConditional(exercised, pv, optionPv);
                            pv.AssignConditional(exercisedToday, optionPv, pv);
                        }
                    }
                    else
                    {
                        if (allExercised)
                        {
                            // Already exercised on all scenarios
                            result.AppendZeroVector(tgi.Date);
                            continue;
                        }

                        if (deal.Settlement_Style == SettlementType2.Cash)
                        {
                            // Calculate value of option
                            optionPricer.Value(baseDate, tgi.Date, pv, exercised, exercisedToday, settlementDateAtExercise, defaultDate);

                            // If exercised today then option pv is settled today, otherwise there is no cash
                            cash.AssignProduct(pv, exercisedToday);
                        }
                        else // Embedded option (callable or puttable)
                        {
                            // Calculate underlying value
                            pv.Clear();
                            cash.Clear();
                            InterestRateOptionPricer.ValueDeals(fItems, pv, cash, baseDate, tgi.Date, null, defaultDate, fDiscountRate, fForecastRate, fRepoRate, fInterestRateVol, fInterestYieldVol, fSurvivalProb, fRecoveryRate);

                            // Calculate value of option
                            optionPricer.Value(baseDate, tgi.Date, optionPv, exercised, exercisedToday, settlementDateAtExercise, defaultDate);

                            // Add or subtract value of embedded option
                            pv.AddProduct(-callPutSign, optionPv);

                            // Option payoff is Max(callPutSign * (underlyingPv - accruedInterest - discountedFee), 0)
                            // Callable/puttable payoff on exercise is
                            // underlyingPv - callPutSign * (callPutSign * (underlyingPv - accruedInterest - discountedFee))
                            // = accruedInterest + discountedFee

                            // Set pv and cash to zero if already exercised.
                            // If exercised today then the pv is settled today.
                            pv.AssignConditional(exercised, exercisedToday * pv, pv);
                            cash.AssignConditional(exercised, exercisedToday * pv, cash);
                        }
                    }

                    pv.MultiplyBy(buySellSign);
                    cash.MultiplyBy(buySellSign);
                    result.AppendVector(tgi.Date, fFxRate.Get(tgi.T) * pv);
                    cashAccumulator.Accumulate(fFxRate, tgi.Date, cash);
                }
            }

            result.Complete(fT);
        }
        /// <summary>
        /// Collect cashflows realised along the scenario path up to endDate.
        /// </summary>
        public override void CollectCashflows(CashAccumulators cashAccumulators, double baseDate, double endDate)
        {
            CFFixedListDeal deal = (CFFixedListDeal)Deal;

            deal.Cashflows.CollectCashflows(cashAccumulators, fFxRate, baseDate, endDate, fBuySellSign, fCutoffDate);
        }